Compare commits

...

74 Commits

Author SHA1 Message Date
Samuel Degueldre 9dcbbe54eb [REL] v2.2.7
# v2.2.7

 - [IMP] types: correctly support `Function` type for props-validation
 - [IMP] app: allow to instantiate templates lazily
 - [FIX] compiler: compile named slot in t-component in named slot
 - [IMP] devtools: update the devtools documentation
 - [IMP] owl-vision: syntax scripts, single quotes attributes and slot props highlight and switch below command
 - [IMP] doc: improve documentation of useExternalListener
 - [FIX] devtools: remove highlights when out of devtools
 - [IMP] devtools: highlight component on select
 - [ADD] owl-vision: vscode extension initial commit
2023-12-06 14:56:12 +01:00
Samuel Degueldre e94428a186 [IMP] types: correctly support Function type for props-validation
Previously, having a Function as a type in the static props description
of a component would only work if the component was not the root
component, as the static props description on Component was "any",
whereas the static props description on ComponentConstructor was
"Schema". This meant that static props description on non-root
components was not type-checked, and on root components it was
type-checked only on the mount call.

This commit makes it so that static type description is of type "Schema"
on Component, now causing static props description to be type-checked,
and adds `typeof Function` to the `BaseType` union, which allows
declaring that a component expects a function as a prop.

Closes #1448
2023-12-04 14:42:39 +01:00
Pierre Rousseau 941190dfa8 [IMP] app: allow to instantiate templates lazily
With this commit, the templates that are given while instantiating the
App class can be an object with templates not yet parsed (i.e. string,
not Document). This allow to instantiate the App class with templates
that are not yet parsed, and these templates will be parsed only when
needed.

Part of task-id 3601257
2023-11-29 11:45:43 +01:00
Samuel Degueldre a53e42518f [FIX] compiler: compile named slot in t-component in named slot
Previously, if a t-set-slot was inside a t-component itself inside a
t-set-slot the parser would crash, because the slot is removed from the
template before compiling its content, causing a further check's
assumption to be broken (the t-set-slot remains connected to the
component's xml node)
2023-11-15 13:45:54 +01:00
Julien Carion (juca) b7c37ca69a [IMP] devtools: update the devtools documentation
This commit updates the devtools documentation to match with its latest
content and updates screenshots to odoo v17.
2023-11-13 12:20:32 +01:00
Bastien Fafchamps (bafa) 34489a2494 [IMP] owl-vision: syntax scripts, single quotes attributes and slot props highlight and switch below command
This commit adds the following:

- Syntax builder scripts to make syntaxes easier to read and edit
- Syntax highlight in single quote attributes
- Syntax highlight for slot props
- Basic syntax highlight for xpaths
- Added `Switch Below` command

This commit fixes the following:

- Using `Switch Besides` or `Switch Below` does not open a new panel if one was already open
- Fixed missing space in component's snippet indentation
2023-11-02 14:38:31 +01:00
Samuel Degueldre 398df543fe [IMP] doc: improve documentation of useExternalListener
closes odoo/owl#1530
2023-10-25 13:50:38 +02:00
Julien Carion (juca) aa6a4a5d46 [FIX] devtools: remove highlights when out of devtools
This commit fixes an issue with the highlight element functionality
which would leave the highlight active when the search bar is not empty
and the user changes view. It will now disappear as long as the user
moves his cursor anywhere in the page. Also, highlights are now removed
when the user scrolls while the html selector is active.
2023-10-25 11:48:55 +02:00
Julien Carion (juca) db3499f5e5 [IMP] devtools: highlight component on select
Small imp to highlight a component when it gets selected in the tree to
provide better visual feedback to the user when he is using arrow keys
navigation.
2023-10-24 16:17:28 +02:00
Bastien Fafchamps (bafa) 166cada8ff [ADD] owl-vision: vscode extension initial commit
Owl Vision is a vscode extension that improves owl developpement by adding
syntax highlights in templates and commands to easly navigate between
components and templates.

It also adds a Component snippet.

Commands:

* `Owl Vision: Find Template`:
    - If the cursor is on a template name, finds the corresponding template.
    - If the cursor is on a component, finds the template of the selected component.
* `Owl Vision: Find Component`: Finds the selected component definition.
* `Owl Vision: Switch`: Finds the corresponding template or component
    depending on the current file.
* `Owl Vision: Switch Besides`: Finds the corresponding template or component
    depending on the current file and opens it besides.

Settings:

* `owl-vision.js.include`: Javascript files to include in search.
* `owl-vision.js.exclude`: Javascript files to exclude in search.
* `owl-vision.xml.include`: XML files to include in search.
* `owl-vision.xml.exclude`: XML files to exclude in search.
2023-10-23 15:53:49 +02:00
Julien Carion (juca) acbe316689 [REL] devtools: chrome v1.2.2, firefox v1.0.0 2023-10-18 15:15:29 +02:00
Julien Carion (juca) fb013ccc72 [FIX] devtools: fix display and message passing for firefox
This commit fixes 2 issues specific to the firefox version of the
extension:
First issue concerns the computation the position of the
border between the subwindows of the components tab which could go
terribly wrong due to the fact that the innerwidth of the window is
implicitly set to 10 when the owl devtools window is hidden.
Second issue comes from changes in the runtime.onMessage method of
browser which now requires to directly return the response instead of
using the sendResponse method.
Also perform a little cleanup on usage of browserInstance and in the
manifest.
2023-10-18 15:15:12 +02:00
Julien Carion (juca) fee3eecd7f [FIX] devtools: context menu should be above the border
This commit increases the z-index of the context menu so that the border
won't be clickable anymore when behind the menu.
2023-10-18 15:09:58 +02:00
FrancoisGe 6037018dd2 [FIX] reactivity: don't react when we set the same object
The purpose of this commit is to not notify reactivity when an object is
replaced by the same object (same reference) in an reactive object.
2023-10-16 10:59:37 +02:00
Lucas Lefèvre (lul) eec7cc4ea7 [FIX] hooks: remove useEffect type circular dependency
`useEffect` type is not compatible with later versions of Typescript.
(I tried with Typescript 5.2, I didn't check which specific
version had the breaking change)

This prevents other projects using owl (such as o-spreadsheet) to
upgrade their own version of Typescript.

`<T extends [...T]>` raises the two following errors:

`Type parameter 'T' has a circular constraint.ts(2313)`
`A rest element type must be an array type.`
2023-10-09 11:12:04 +02:00
Julien Carion (juca) 035895b043 [IMP] devtools: icons and UI improvements
This commit adapts the layout of icons in the UI to be more intuitive
and also adds some feedback on hover on some elements for clarity. Also
fixes a bug where an object line could be toggled on select.
2023-10-05 10:05:11 +02:00
Julien Carion (juca) ff5ef82ea2 [FIX] devtools: don't unfold env base object prototype
This commit prevents the base object prototype from being unfolded when
the env of a component gets unfolded since it does not contain useful
information.
2023-10-04 13:36:11 +02:00
Samuel Degueldre 0048205636 [IMP] tests: use inline snapshots for lifecycle checks
This allows them to be updated automatically when needed instead of
having to update them by hand.
2023-10-04 12:55:20 +02:00
Julien Carion (juca) 0d341d9e7b [IMP] devtools: fixed subwindows minimum width
This commit changes the the minimum width of the subwindows to be fixed
so that the icons display stays clean even on very small widths.
2023-10-04 11:34:58 +02:00
Julien Carion (juca) 4c7f572dbe [FIX] devtools: update search results on tree change
This commit ensures that search results are properly updated when the
components tree is updated so that it remains coherent if search results
appear or disappear from the view.
2023-10-04 11:33:46 +02:00
Julien Carion (juca) 610c272104 [IMP] devtools: highlight searched components
This commit makes the component search more interactive by highlighting
the component search results on the page when navigating through them.
2023-10-03 16:18:25 +02:00
Rodolpho Cammarosano 32e4565131 [FIX] doc: onWillDestroy mistasken for onWillUnmount 2023-10-03 08:12:49 +02:00
Rodolpho Cammarosano 9b9c15e4a9 [FIX] doc: error handling example
A few corrections to make the example more realistic:
- The component has no `error` property, so the writer probably meant `state.error`.
- The "content" slot is not being set, and "default" does the job in this case.
- The closing tag was missing in the `ErrorBoundary`'s template.
2023-10-03 08:11:44 +02:00
Géry Debongnie b1690f19cc [IMP] tools: add extra information in release script 2023-09-25 13:58:01 +02:00
Géry Debongnie 5dcee2564c [REL] v2.2.6
# v2.2.6

 - [IMP] devtools: add svg elements detection
 - [FIX] reactivity: do not notify for NOOPs on collections
 - [IMP] app: export apps set as static property
 - [IMP] runtime: do not check template equality outside dev mode
 - [FIX] runtime: properly support t-foreach on strings
2023-09-25 13:48:13 +02:00
Julien Carion (juca) 752160fd85 [IMP] devtools: add svg elements detection
This commit extends the detection of component related dom elements to
svg elements in the page so that they can be searched and highlighted
correctly with the devtools.
2023-09-25 11:43:39 +02:00
Samuel Degueldre 3937966b74 [FIX] reactivity: do not notify for NOOPs on collections
Previously, if a reactive was observing the presence of an item in a
set that was originally not present, it would get notified when that
item was "deleted" from the set (even though there was nothing to delete
and the set did not change). The same applied to the key already being
present and then being "added". The same thing occured with Map, both
for presence but also for values (setting a key to the value it was
already set to would notify).

This commit fixes that.
2023-09-22 14:36:35 +02:00
Géry Debongnie e7ebb92104 [IMP] app: export apps set as static property
Before this commit, Owl would export the list of apps in a global object
`__OWL_DEVTOOLS__`.  However, it is sometimes useful to be able to
access that set, even outside of the devtools (for example, to register
templates in all active apps).

closes #1515
2023-09-04 15:01:48 +02:00
Samuel Degueldre c78e070636 [IMP] runtime: do not check template equality outside dev mode
When defining a template with a name that the template set already
contains, we currently always check whether the template is the same and
throw an error when it's not. This is potentially expensive as it can
involve serializing a pretty large XML document. This check is only
supposed to help during development so this commit disables this check
outside dev mode.
2023-08-25 09:24:18 +02:00
Samuel Degueldre 610ed02373 [FIX] runtime: properly support t-foreach on strings
Previously, support for iterables was added to t-foreach. The idea was
that anything that you can spread or on which you can use for..of would
be supported. Due to an implementation mistakes, strings, which are
iterable were not supported because we checked that the typeof the
iterable was 'object'.

To fix this, we coerce the iterable to an object and check whether that
coerced value has a Symbol.iterator property, which is what happens
behind the scenes when using for..of or spreading a primitive.

Closes: odoo/owl#1503
2023-08-25 09:24:04 +02:00
Samuel Degueldre 4b23f51974 [REL] v2.2.5
# v2.2.5

 - [FIX] compiler: fix xmlns attribute not being set correctly in firefox
 - [FIX] compiler: fix t-call at root of template causing crashes
 - [REF] compiler: minor cleanup
 - [FIX] devtools: fix inspected path
2023-08-07 12:26:46 +02:00
Samuel Degueldre b25e988628 [FIX] compiler: fix xmlns attribute not being set correctly in firefox
Firefox will not serialize the xmlns attributes of node inside
XMLDocuments, see https://bugzilla.mozilla.org/show_bug.cgi?id=175946
it will only output an xmlns attribute if the node being serialized has
a non-null namespaceURI.

When compiling templates, we currently use a special attribute,
"block-ns" to keep track of the namespace, but we do not make use of the
namespace to create the elements that will be serialized to the compiled
block string. This causes a difference in behaviour between Chrome and
Firefox: since we end up with an Element with two attributes: the
block-ns attribute and the xmlns attribute. Chrome will serialize both,
but Firefox will only serialize the block-ns because the Element does
not have a namespaceURI.

To fix this issue, we get rid of the block-ns magic attribute
completely, and use xmlns instead. We also use the namespace when
creating intermediate elements that will be used to create the
serialized block string: the namespace is only used to create the
elements but *not* set as an attribute, as this would cause chrome to
serialize it twice, causing a duplicate attribute error when parsing it
further down the line.

When creating the template element for the block at runtime, the xmlns
attribute is used both as the namespace with which to create the
element, and set as an attribute, this doesn't cause issues when
serializing later because the namespaceURI is never serialized as an
attribute when serializing an HTML document[1], so we avoid the
double-serialization in Chrome, and when doing HTML serialization,
Firefox will correctly serialize the attribute.

It's desirable that the xmlns is set as an attribute to allow users to
use owl to render SVG, and then use the HTML serialization of it as a
SVG even outside the context of an HTML document (eg to generate an SVG
file or an SVG data URL).

[1]: https://w3c.github.io/DOM-Parsing/#xml-serialization
2023-08-07 12:21:43 +02:00
Julien Carion (juca) e0758c0e9e [REL] devtools: chrome v1.2.1 2023-08-04 11:49:14 +02:00
Samuel Degueldre ba34811f71 [FIX] compiler: fix t-call at root of template causing crashes
Because the default content of a t-call is compiled before the block of
the t-call is created, the default content can sometimes incorrectly be
treated as though it is at the root of the template. This causes various
issues, in the case of a t-if, the default content will just replace the
t-call entirely when truthy, and when falsy the template will not return
anything, leading to a crash. Similar things occur with t-foreach and
t-out with a default content.

This commit fixes that by moving the block creation for the t-call ahead
of the compilation of the default content. In doing so, it makes the
context attribute "preventRoot" obsolete: the purpose of this attribute
is to somehow make the code aware that the root of the template will be
defined later, but because it wasn't propagated everywhere properly it
caused this issue. Now that the root already exists before we compile
the default content, we don't need it anymore.
2023-08-04 11:44:54 +02:00
Samuel Degueldre 28672096a2 [REF] compiler: minor cleanup
This commit merges two nested ifs and explicitly joins an array instead
of relying on array -> string coercion
2023-08-04 11:44:54 +02:00
Julien Carion (juca) 9823a4e7dd [FIX] devtools: fix inspected path
This commit fixes the handling of the inspected path in the
getComponentsTree method so that it is reset when the given one does
not exist anymore. It solves a crash of the method anytime this would
happen which would prevent the tree from updating correctly.
2023-08-02 15:50:11 +02:00
Samuel Degueldre 105ec7ced8 [REL] v2.2.4
# v2.2.4

 - [FIX] compiler: fix swapped key/value using t-foreach on Map
 - [FIX] devtools: fix crash while highlighting env
 - [FIX] *: move OwlError to common
 - [FIX] playground: todo app clear complete tasks
 - [IMP] compiler: improve error message when failing to compile template
2023-08-02 08:20:14 +02:00
Samuel Degueldre 8f9ad987b9 [FIX] compiler: fix swapped key/value using t-foreach on Map
In odoo/owl#1352 we added support for using t-foreach on Map objects,
maps should behave the same as objects where keys are available under
the name specified in t-as and values under that same name with the
suffix `_value`. Unfortunately, because the code for objects was written
in a confusing way (values were stored in a variable named `keys` and
vice versa), the implementation for Map was incorrect and keys and
values were swapped.

This commit fixes that and rewrites the code to be less confusing: keys
are extracted from the variables `k_block` and values from `v_block`,
which swaps the behaviour, and the code to prepare a list from an object
now extracts the keys in `keys` and the values in `values`
2023-08-02 08:15:43 +02:00
Julien Carion (juca) 6050827689 [FIX] devtools: fix crash while highlighting env
This commit fixes a crash that could happen in the keepEnvLit method
when passing through the env of the inspected component.
2023-07-26 15:15:20 +02:00
Julien Carion (juca) 9b1ec5dc0e [FIX] *: move OwlError to common
This commit moves OwlError to its own file in the new common folder
such that it is no longer associated with the runtime.
2023-07-26 15:15:20 +02:00
Pierre Pulinckx (pipu) 9b1c270501 [FIX] playground: todo app clear complete tasks
Just fix a little bug when clicked on "Clear Completed"
Also removed unusefull method.
2023-07-26 11:31:49 +02:00
Samuel Degueldre 9d99f8936b [IMP] compiler: improve error message when failing to compile template
Previously, when a template failed to compile because of a syntax error
(typically because we don't do any syntax checking when compiling
expression, allowing invalid expressions to be transpiled successfully),
the error reporting was very minimal: you would only get the error
message itself (eg: "Unexpected token") with the stack information of
the error pointing to the call to `new Function` in owl, which is not
very useful.

This commit catches the compilation error and completes it with
information about the template name when available, and also adds the
generated code to the error message, allowing the user to just
copy/paste it in their web console or code editor to get a more precise
location for the error.
2023-07-20 09:46:18 +02:00
Géry Debongnie 7bc9d34a64 [REL] v2.2.3
# v2.2.3

 - [FIX] app: sync destroy everythig when app is destroyed
2023-07-20 08:05:40 +02:00
Géry Debongnie b1a3b322ee [FIX] app: sync destroy everythig when app is destroyed
Before this commit, the App destroy method would not destroy everything
synchronously. The code scheduled a flush, which is asynchronous, to
finally clean up the task lists, and destroy the cancelled nodes. But
this is not really good for tests: we need a stronger guarantee that
nothing will happen after the destroy.

With this commit, we simply call the processTask method immediately
after destroying the root component, so all cancelled nodes will be
destroyed immediately.
2023-07-20 08:02:26 +02:00
Géry Debongnie ca688d8640 [REL] v2.2.2
# v2.2.2

 - [FIX] tools: include proper version number in released build
2023-07-19 15:37:09 +02:00
Géry Debongnie ea9f533536 [FIX] tools: include proper version number in released build
Before this commit, the release script would build the code, then update
the version number, so the released code would have the previous release
number instead of the current.
2023-07-19 15:34:20 +02:00
Géry Debongnie 875ebdcfb0 [REL] v2.2.1
# v2.2.1

 - [FIX] compiler: allow t-out on component tag
2023-07-19 15:22:35 +02:00
Géry Debongnie 2e07799250 [FIX] compiler: allow t-out on component tag
Before this commit, the template parser would allow using t-esc on a
component tag (<MyComponent t-esc="expr"/>) but would incorrectly ignore
the component when parsing a t-out: <MyComponent t-out="expr"/> would be
parsed as <t t-out="expr"/>

This commit solves the issue, and also, moves the `t-out` parsing code
next to `t-esc` so they have the same priority relatively to other
directives.

closes #1483
2023-07-19 15:16:26 +02:00
Géry Debongnie 0d9d21a5c1 [REL] v2.2
# v2.2

 - [IMP] runtime: add support for Map and other iterables in t-foreach
 - [IMP] runtime: only destroy component in raf callback
 - [REF] runtime: simplify implementation of batched
 - [FIX] compiler: allow t-model.number to work with select
 - [FIX] devtools: Fix crash when no root node
 - [FIX] devtools: fix/imp env display
 - [FIX] devtools: fix symbols handling and display
2023-07-18 16:07:37 +02:00
Samuel Degueldre 836e12b1c5 [IMP] runtime: add support for Map and other iterables in t-foreach
closes: #1352
2023-07-18 13:41:07 +02:00
Géry Debongnie 7538aeae0e [IMP] runtime: only destroy component in raf callback
Before this commit, most of the time, components are destroyed when the
virtual dom is patched and a component node is removed. However, since
Owl is asynchronous and a component may take some time to get ready
(with onWillStart), it can happen that a component is created, then
before it is ready, it is recreated.  In that case, the initial instance
has to be destroyed.

Before this commit, the destroy operation was done immediately, when we
cancel the current fibers.  However, this means that we cannot have a
guarantee between micro task ticks that a component has not been
destroyed in the meantime.

For example, in Odoo, it is common to use the rpc service, which will
throw an error if called by a destroyed component. But because of the
possible destruction of a component at any time, the following code is
unsafe:

async loadSomeData() {
  // guaranteed to be called when component is alive
  await Promise.resolve();
  // however here, component may have been destroyed
  this.rpc(...)
}

So, to prevent this issue, we can slightly delay the destroy operation.
It is not entirely trivial, since we need to find a way to neutralize
the component in the meantime. But it seems like performing all that
kind of operation at the "commit" phase (so, the request animation frame
callback) makes sense to me.

So, this commit modifies the code to add a new component status
(cancelled) and use it to cancel components that are waiting to be
destroyed. These components will then be destroyed as soon as the
requestanimation frame starts, before all other dom operations.
2023-07-17 11:05:34 +02:00
Samuel Degueldre 3e9ba9ca8e [REF] runtime: simplify implementation of batched
Currently the implementation of batched is quite complicated and
difficult to read. This is because this approach tried to block all
calls at the same point and then only let the first one go through, but
an alternative approach is to simply throw away the calls that are made
after the first one has been scheduled. This change makes the
implementation much simpler to understand.

Co-authored-by: Aaron Bohy <aab@odoo.com>
2023-07-17 10:48:00 +02:00
Géry Debongnie e4c296a7d2 [FIX] compiler: allow t-model.number to work with select
Before this commit, owl parser would ignore the `.number` suffix on
<select> options. I do not see a good reason for that, and it prevents
some legitimate usecases.

closes #1444
2023-07-12 10:23:36 +02:00
Julien Carion (juca) 44748270da [FIX] devtools: Fix crash when no root node
This commit fixes a crash in the retrieval of the components tree which
happened when the first app did not contain a root node. The default
inspected component is now set to be the first root component found in
the apps.
2023-07-12 10:01:38 +02:00
Julien Carion (juca) 8b1dc4c43d [FIX] devtools: fix/imp env display
This commit first fixes how object prototype are detected so that it
won't stop as soon as the constructor name of the object is "Object".
This allows displaying every single prototype encountered and closes
https://github.com/odoo/owl/issues/1467.

This commit also improves how the env of a component is displayed by
expanding its chain of prototypes by default while keeping its keys lit
as long as it is their first occurence in the chain.
2023-07-05 11:27:42 +02:00
Julien Carion (juca) c105c6da38 [FIX] devtools: fix symbols handling and display
This commit fixes the three following issues:
- Symbols could never appear in shortened display of objects
- Objects which contained only symbols as keys would be considered to be
  empty and therefore not expandable
- Symbol value edition would create a new property on the object with
  the stringified symbol as key instead of updating its value

closes https://github.com/odoo/owl/issues/1464
2023-06-29 14:15:44 +02:00
Géry Debongnie 3001420a1d [REL] v2.1.4
# v2.1.3

 - [FIX] components: properly differentiate t-call subcomponents
 - [REF] devtools: Better messages forwarding
 - [FIX] devtools: Fix app methods patching
 - [DOC] Fix a code bug in the example of slots
2023-06-28 11:17:24 +02:00
Samuel Degueldre 432ff444a1 [FIX] devtools: fix incorrect path resolution for subscriptions
Since we now omit some observed objects when listing subscriptions, the
index of the subscription is no longer the index of the raw
subscription. This causes issue with the resolution of object paths when
they are inside a subscription. This commit fixes that by adding the
index to the raw subscription.

We also need to adapt the code that traverses the old tree, since the
index of the subscription in the component is no longer the same as the
index of the subscription "child" in the object tree.
2023-06-23 16:15:02 +02:00
Samuel Degueldre aa3c88a6c4 [IMP] devtools: present observed keys in a more compact way
Previously, the keys were displayed separately from the target, on top
of being displayed in bold inside the object when unfolded. This is
redundant, and in most cases you have to unfold the object anyway
because there are more keys observed than can be displayed.

The only "key" that cannot be displayed in bold inside the object is the
"key changes" magic key. This commit replaces it by a small +/- badge on
the right of the object's short content.

This commit also stops displaying observed object that are nested inside
other observed objects at the top level, as it can be confusing, and it
also heuristically gives a name to observed objects: if the observed
object is a property of the component or one of its props it will be
named accordingly, if not it will be named `[unknown]` (which may happen
when reobserving reactive objects inside a service or inside the env,
but is pretty rare in practice).
2023-06-23 14:32:55 +02:00
Julien Carion (juca) 601a98e649 [IMP] devtools: patch app methods only when needed
This commit changes the moment when all methods that need patching
to handle events are actually patched: the complete method of RootFiber
is now patched at devtools startup (when the tab owl tab is opened) and
every other method is patched at first activation of the event recording
functionality. This makes sure that the devtools will have no impact on
performance whatsoever when they are not directly put in use.
2023-06-23 08:51:23 +02:00
Géry Debongnie 23c7d19ef0 [FIX] blockdom: properly merge dynamic class values
Class attributes are managed in a specific way in owl: they are merged
with existing class attributes, and also, they can be defined in
multiple ways (t-att-class, t-attf-class, t-att=['class', ...] and each
of these can be combined together.

Before this commit, the `t-att` syntax was handled as a normal
attribute, and therefore, would not combine as required with existing
classes.

closes #1453
2023-06-20 08:25:36 +02:00
Julien Carion (juca) 59c49b5833 [IMP] devtools: add border for new animation frame
This commit adds a colored border between events in list view when
a new animation frame was created.
2023-06-15 10:05:08 +02:00
Julien Carion (juca) 2cca0bd819 [FIX] devtools: Fix race conditions in tree lodaing
This commit fixes some race conditions that were happening due to the
loading of the tree being sometimes triggered at the same moment as the
DOM patch. This would result in some destroyed component still being
present in the devtools' tree. This commit also ensures that the loading
of the tree is synchronous in regard to the component details loading.
2023-06-14 15:39:22 +02:00
Géry Debongnie fbf4c4add2 [FIX] parser: make t-on stricter
Before this commit, the `t-on` directive assumed that the next character
would be a -, and ignored it, so if someone would write `t-onclick` by
mistake, Owl would then add an event handler on the `lick` event,
instead of `click`.

With this commit, we improve the parser to make it stricter and fail if
there is no dash.

closes #1441
2023-05-30 13:30:56 +02:00
Julien Carion (juca) 78d6ff735e [REL] devtools: chrome v1.1.1 2023-05-26 15:15:56 +02:00
Julien Carion (juca) a7f51fa666 [FIX] devtools: fix context menus flickering
This commit makes it so the position of the context menu doesn't require
an additional render to apply so it fixes the flickering.
2023-05-24 15:40:18 +02:00
Julien Carion (juca) 5175f95289 [REL] devtools: chrome v1.1 2023-05-24 14:28:30 +02:00
Julien Carion (juca) 3c9f4a8ae9 [IMP] devtools: Add blacklist to components toggle
This commit adds the functionnality to add components to the toggle
blacklist so that it won't be expanded by default when launching or
reloading the devtools components tree.
2023-05-24 14:28:30 +02:00
Julien Carion (juca) 310730782c [FIX] devtools: Missing global owl
This commit adapts the behavior of the devtools global hook to get
the toRaw and reactive functions from the __OWL_DEVTOOLS__ variable
instead of the global owl when it is missing. Also adds the functions
to the __OWL_DEVTOOLS__ variable for the former to work.
This allows the devtools to work in environments where owl is loaded
through ES modules.
Also quickly fixes iframes detection update on page reload.
2023-05-24 13:34:11 +02:00
Julien Carion (juca) 77a413d750 [FIX] devtools: fix issue when treeElement have same name
This commit fixes the key of the sub tree elements in the details
window to be 100% unique since the name of the elements could not
be unique so it would silently crash and not display. It also removes
the default size property of maps and sets since there's already a
getter available for it.
2023-05-24 11:12:35 +02:00
Julien Carion (juca) fe31f93c94 [FIX] devtools: fix apps patching and reload
This commit fixes issues introduced in the previous fix for the apps
methods patching and also fixes the status of the profiler tracing
on reload.
2023-05-24 11:12:03 +02:00
Michael (mcm) 9cc0f88e02 [IMP] hooks: add types to useEffect to improve DX 2023-05-16 14:26:27 +02:00
Samuel Degueldre 412fda10fd [FIX] gh-page: fix 'unexpected token export' error on landing page
When refactoring the playground to use es-modules, a script that loads
owl as a non-module was forgotten in the head of the page and causes an
error in the console, as the script is not declared as type="module"
despite being an es-module. This script is also useless as owl is loaded
by being imported by the counter component in the page.

The importmap has also been moved to the head because of a bug in
firefox where importmaps can fail to be taken into account if they are
after a script that is not of type="module", see:
https://bugzilla.mozilla.org/show_bug.cgi?id=1833371

Closes #1436
2023-05-16 14:15:10 +02:00
Géry Debongnie aa441274c7 [FIX] compiler: apply translations to t-set text body
Before this commit, the translate function was not applied to text
content inside the body of a t-set (unless that content was itself
inside some html). This is not clearly not intended.

To fix it, we just need to call the translate function at the
appropriate moment.

closes #1434
2023-05-16 10:38:22 +02:00
161 changed files with 14092 additions and 3595 deletions
+8 -1
View File
@@ -15,7 +15,7 @@ yarn-debug.log*
yarn-error.log*
#ide's
.vscode
**/.vscode/*
.idea
node_modules
@@ -26,3 +26,10 @@ release-notes.md
# useful in some cases
/temp
# owl-vision
*/owl-vision/out/
*/owl-vision/.vs/
**/*.vsix
!*/owl-vision/.vscode/launch.json
!*/owl-vision/.vscode/tasks.json
+2 -1
View File
@@ -357,7 +357,7 @@ cleaning operation, since the component may be destroyed before it has even been
mounted. The `willDestroy` hook is useful in that situation, since it is always
called.
The `onWillUnmount` hook is used to register a function that will be executed at
The `onWillDestroy` hook is used to register a function that will be executed at
this moment:
```javascript
@@ -451,5 +451,6 @@ console.log(status(component));
// logs either:
// - 'new', if the component is new and has not been mounted yet
// - 'mounted', if the component is currently mounted
// - 'cancelled', if the component has not been mounted yet but will be destroyed soon
// - 'destroyed' if the component is currently destroyed
```
+2 -2
View File
@@ -51,8 +51,8 @@ that render its content, and a fallback if an error happened.
```js
class ErrorBoundary extends Component {
static template = xml`
<t t-if="error" t-slot="fallback">An error occurred</t>
<t t-else="" t-slot="content"`;
<t t-if="state.error" t-slot="fallback">An error occurred</t>
<t t-else="" t-slot="default"/>`;
setup() {
this.state = useState({ error: false });
+3 -2
View File
@@ -190,12 +190,13 @@ will then be updated accordingly.
### `useExternalListener`
The `useExternalListener` hook helps solve a very common problem: adding and removing
a listener on some target whenever a component is mounted/unmounted. For example,
a listener on some target whenever a component is mounted/unmounted. It takes a target
as its first argument, forwards the other arguments to `addEventListener`. For example,
a dropdown menu (or its parent) may need to listen to a `click` event on `window`
to be closed:
```js
useExternalListener(window, "click", this.closeMenu);
useExternalListener(window, "click", this.closeMenu, { capture: true });
```
### `useComponent`
+8 -7
View File
@@ -376,15 +376,16 @@ An important difference should be made with the usual `QWeb` behaviour: Owl
requires the presence of a `t-key` directive, to be able to properly reconcile
renderings.
`t-foreach` can iterate on an array (the current item will be the current value)
or an object (the current item will be the current key).
`t-foreach` can iterate on any iterable, and also has special support for objects
and maps, it will expose the key of the current iteration as the contents of the
`t-as`, and the corresponding value with the same name and the suffix `_value`.
In addition to the name passed via t-as, `t-foreach` provides a few other
variables for various data points (note: `$as` will be replaced with the name
passed to `t-as`):
In addition to the name passed via t-as, `t-foreach` provides a few other useful
variables (note: `$as` will be replaced with the name passed to `t-as`):
- `$as_value`: the current iteration value, identical to `$as` for lists and
integers, but for objects, it provides the value (where `$as` provides the key)
- `$as_value`: the current iteration value, identical to `$as` for arrays and
other iterables, but for objects and maps, it provides the value (where `$as`
provides the key)
- `$as_index`: the current iteration index (the first item of the iteration has index 0)
- `$as_first`: whether the current item is the first of the iteration
(equivalent to `$as_index == 0`)
+30 -25
View File
@@ -35,13 +35,13 @@ The components tab is separated into two sub windows: the components tree in the
the component details in the right. The components tree will display all the different
components that are present in the tab in the form of a tree. The root of this tree is
actually the app which is not a component but can still be inspected by the devtools like
one. There can also be multiple apps loaded in the page like in the following:
one. There can also be multiple apps loaded in the page like in website:
<img src="screenshots/multi_apps.png"/>
There is a convenient search bar at the top of the components tree which will help finding
the components tou want in the tree and also, an element picker can be used to directly select
the component you want to focus on in the page which is especially useful when trying to find
the component you want to focus on in the page which is especially useful when 1trying to find
what you want. Just click on the elements picker icon and click on the element you want to focus
on in the page and it will be selected in the devtools accordingly. Hovering any element in the
page in this mode will highlight it and the same happens anytime in the components tree.
@@ -64,25 +64,18 @@ as its env, props, observed states and all the other variables that are present
While the props and the env are already present on the actual instance of the component and are
pretty explicit by themselves, the observed state value is a bit more complicated to grasp.
The observed state is actually information about which variables are observed by the component
which will trigger a rerender of the component when it is modified. The keys represent which part of the
variable is actually observed and the target is the actual variable. For simplicity, the properties
that are not observed by the component are greyed out while the others are in bold. This means that
editing bold ones will trigger a rerender while the greyed out ones will not.
The observed state is actually information about which variables are being observed by the component:
when any property of a reactive object is being read by the component, the component will subscribe
to this property which means it will listen to any change that can occur on the property and render
when such a change occurs. This can be visualized easily within the devtools inside of the observed
state section: observed properties of the reactive object(s) are displayed in bold while the others
are greyed out. Do keep in mind that a greyed out property in the observed state of one component
may be observed by another and the other way around is also possible. Here is an example for some
user Field component:
<img src="screenshots/states.png"/>
In the given example, we have two keys/target pairs for two different variables. The first one indicates
that adding or removing an element to the array will trigger a rerender since the length will have changed.
Replacing the element at index 0, 1 or 2 will also have the same effect as implied by the keys. It doesn't
mean that editing the properties of element at index 0, 1 or 2 will rerender the component though. It may
be the case for some but this will be described in another keys/target pair. The second keys/target pair
is actually the element at index 0 of the first pair. It only has id in the keys meaning that only the
id property will actually trigger a rerender the component when modified. Be aware however that the other
properties may be in the observed state of another component like a child one in this case. A greyed out
property only implies it is not reactive for the selected component and not for the others.
The navigation inside the properties is also similar to the one in console variables: properties have
Navigation inside the properties is also similar to the one in console variables: properties have
their prototype displayed and getters will get their value when clicked on (...). It is also possible to
send any property to the console using the right-click context menu on it and functions can be inspected
in the sources tab as well.
@@ -96,8 +89,10 @@ component's name. Using the left click on the component's name will focus it in
It is also possible to edit any of the leaf node properties. To do so, you must double click on the
property's value and modify it using the freshly created input then press enter to apply the changes.
Do note that the modified values should be written in JSON format in order to be valid (examples:
89, "yes", undefined, null, \["hello", 15\], {"a": 1}, true, ...). Whether it has an impact on the
component or not and whether it produces an error is the responsability of the user.
89, "yes", undefined, null, \["hello", 15\], {"a": 1}, true, ...). Editing any value will produce a
manual render of the component (or the root component of the application in the case of env values).
Whether the edition has an impact on the component or not and whether it produces an error is the
responsability of the user.
<img src="screenshots/edit.png"/>
@@ -117,7 +112,8 @@ are intercepted by the devtools using the record button.
The second button is used to clear all the events that have been recorded. The select can be used to
switch between the tree view (which shows the causality between renders) and the events log view which
simply displays the events in the exact order they were triggered. In this view, you can expand the create,
update and destroy events which reveals the component that initiated the event.
update and destroy events which reveals the component that initiated the event. Also, a transition line will
appear each time a new animation frame has been loaded between events.
<img src="screenshots/events_log.png"/>
@@ -131,20 +127,29 @@ There is also the Trace Renderings and Trace Subscriptions features. These featu
recording of events and have no effect on the profiler tab. The Trace Renderings option is used to log in
the console all the render events and allows to show their traceback information. Similarly, the Trace
Subscriptions option logs all the properties that caused a render event and also allows to see the traceback
of the modification
of the modification.
<img src="screenshots/trace_rendering.png"/>
<img src="screenshots/trace_subscriptions.png"/>
The Owl Devtools also allow to inspect iframes coded in Owl: when an Owl iframe is detected in the page,
the iframe selector will appear next to the tabs. This allows to switch from an iframe to another easily.
Be aware that switching iframes will clear all record events from the profiler tab. Iframes detection is
currently not working in the firefox version, we are aware of this issue and will try to address it in the
future.
<img src="screenshots/iframes.png"/>
## Options
The owl devtools extension has a dark mode feature which defaults to your general devtools settings and can
be toggled using the sun/moon icon at the top-right corner of the tab. All the examples above were created
with the dark mode enabled. There is also a refresh button to completely reset the owl devtools.
be toggled using the sun/moon icon at the top-right corner of the tab. There is also a refresh button to
completely reset the owl devtools.
<img src="screenshots/darkmode.png"/>
## Troubleshooting
If the feedback from the page to the devtools seems to be cut, just close the devtools and refresh the page.
If the feedback from the page to the devtools seems to be cut, you can first try to use the refresh
button mentioned above but if it still doesn't seem to work, just close the devtools and refresh the page.
This will eventually happen any time a tab stays opened for too long without being refreshed.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 333 KiB

After

Width:  |  Height:  |  Size: 545 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 210 KiB

After

Width:  |  Height:  |  Size: 387 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 197 KiB

After

Width:  |  Height:  |  Size: 266 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 185 KiB

After

Width:  |  Height:  |  Size: 320 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 206 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 166 KiB

After

Width:  |  Height:  |  Size: 329 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 86 KiB

After

Width:  |  Height:  |  Size: 166 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 311 KiB

After

Width:  |  Height:  |  Size: 536 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 336 KiB

After

Width:  |  Height:  |  Size: 488 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

After

Width:  |  Height:  |  Size: 177 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 146 KiB

After

Width:  |  Height:  |  Size: 182 KiB

+1 -2
View File
@@ -10,7 +10,7 @@
<link rel="stylesheet" href="assets/milligram.css">
<link rel="stylesheet" href="assets/highlight.tomorrow.css">
<link rel="stylesheet" href="assets/main.css">
<script src="./owl.js"></script>
<script type="importmap">{ "imports": { "@odoo/owl": "./owl.js" } }</script>
</head>
<body>
<header class="container">
@@ -68,7 +68,6 @@
<p><a href=".">OWL</a> is licensed under LGPLv3.<br>Logo from <a href="https://github.com/googlefonts/noto-emoji">Google Noto Emoji Font</a>, licensed under Apache License 2.0</p>
</footer>
<script src="assets/highlight.pack.js"></script>
<script type="importmap">{ "imports": { "@odoo/owl": "./owl.js" } }</script>
<script type="module" src="display_code.js"></script>
<script type="module" src="counter.js"></script>
</body>
+264 -193
View File
@@ -82,65 +82,6 @@ function toggler(key, child) {
// Custom error class that wraps error that happen in the owl lifecycle
class OwlError extends Error {
}
// Maps fibers to thrown errors
const fibersInError = new WeakMap();
const nodeErrorHandlers = new WeakMap();
function _handleError(node, error) {
if (!node) {
return false;
}
const fiber = node.fiber;
if (fiber) {
fibersInError.set(fiber, error);
}
const errorHandlers = nodeErrorHandlers.get(node);
if (errorHandlers) {
let handled = false;
// execute in the opposite order
for (let i = errorHandlers.length - 1; i >= 0; i--) {
try {
errorHandlers[i](error);
handled = true;
break;
}
catch (e) {
error = e;
}
}
if (handled) {
return true;
}
}
return _handleError(node.parent, error);
}
function handleError(params) {
let { error } = params;
// Wrap error if it wasn't wrapped by wrapError (ie when not in dev mode)
if (!(error instanceof OwlError)) {
error = Object.assign(new OwlError(`An error occured in the owl lifecycle (see this Error's "cause" property)`), { cause: error });
}
const node = "node" in params ? params.node : params.fiber.node;
const fiber = "fiber" in params ? params.fiber : node.fiber;
// resets the fibers on components if possible. This is important so that
// new renderings can be properly included in the initial one, if any.
let current = fiber;
do {
current.node.fiber = current;
current = current.parent;
} while (current);
fibersInError.set(fiber.root, error);
const handled = _handleError(node, error);
if (!handled) {
console.warn(`[Owl] Unhandled error. Destroying the root component`);
try {
node.app.destroy();
}
catch (e) {
console.error(e);
}
throw error;
}
}
const { setAttribute: elemSetAttribute, removeAttribute } = Element.prototype;
@@ -175,11 +116,21 @@ function createAttrUpdater(attr) {
}
function attrsSetter(attrs) {
if (isArray(attrs)) {
setAttribute.call(this, attrs[0], attrs[1]);
if (attrs[0] === "class") {
setClass.call(this, attrs[1]);
}
else {
setAttribute.call(this, attrs[0], attrs[1]);
}
}
else {
for (let k in attrs) {
setAttribute.call(this, k, attrs[k]);
if (k === "class") {
setClass.call(this, attrs[k]);
}
else {
setAttribute.call(this, k, attrs[k]);
}
}
}
}
@@ -191,7 +142,12 @@ function attrsUpdater(attrs, oldAttrs) {
if (val === oldAttrs[1]) {
return;
}
setAttribute.call(this, name, val);
if (name === "class") {
updateClass.call(this, val, oldAttrs[1]);
}
else {
setAttribute.call(this, name, val);
}
}
else {
removeAttribute.call(this, oldAttrs[0]);
@@ -201,13 +157,23 @@ function attrsUpdater(attrs, oldAttrs) {
else {
for (let k in oldAttrs) {
if (!(k in attrs)) {
removeAttribute.call(this, k);
if (k === "class") {
updateClass.call(this, "", oldAttrs[k]);
}
else {
removeAttribute.call(this, k);
}
}
}
for (let k in attrs) {
const val = attrs[k];
if (val !== oldAttrs[k]) {
setAttribute.call(this, k, val);
if (k === "class") {
updateClass.call(this, val, oldAttrs[k]);
}
else {
setAttribute.call(this, k, val);
}
}
}
}
@@ -286,20 +252,13 @@ function updateClass(val, oldVal) {
* @returns a batched version of the original callback
*/
function batched(callback) {
let called = false;
return async () => {
// This await blocks all calls to the callback here, then releases them sequentially
// in the next microtick. This line decides the granularity of the batch.
await Promise.resolve();
if (!called) {
called = true;
// wait for all calls in this microtick to fall through before resetting "called"
// so that only the first call to the batched function calls the original callback.
// Schedule this before calling the callback so that calls to the batched function
// within the callback will proceed only after resetting called to false, and have
// a chance to execute the callback again
Promise.resolve().then(() => (called = false));
callback();
let scheduled = false;
return async (...args) => {
if (!scheduled) {
scheduled = true;
await Promise.resolve();
scheduled = false;
callback(...args);
}
};
}
@@ -751,12 +710,7 @@ function buildTree(node, parent = null, domParentTree = null) {
info.push({ type: "child", idx: index });
el = document.createTextNode("");
}
const attrs = node.attributes;
const ns = attrs.getNamedItem("block-ns");
if (ns) {
attrs.removeNamedItem("block-ns");
currentNS = ns.value;
}
currentNS || (currentNS = node.namespaceURI);
if (!el) {
el = currentNS
? document.createElementNS(currentNS, tagName)
@@ -772,6 +726,7 @@ function buildTree(node, parent = null, domParentTree = null) {
const fragment = document.createElement("template").content;
fragment.appendChild(el);
}
const attrs = node.attributes;
for (let i = 0; i < attrs.length; i++) {
const attrName = attrs[i].name;
const attrValue = attrs[i].value;
@@ -1583,6 +1538,68 @@ function remove(vnode, withBeforeRemove = false) {
vnode.remove();
}
// Maps fibers to thrown errors
const fibersInError = new WeakMap();
const nodeErrorHandlers = new WeakMap();
function _handleError(node, error) {
if (!node) {
return false;
}
const fiber = node.fiber;
if (fiber) {
fibersInError.set(fiber, error);
}
const errorHandlers = nodeErrorHandlers.get(node);
if (errorHandlers) {
let handled = false;
// execute in the opposite order
for (let i = errorHandlers.length - 1; i >= 0; i--) {
try {
errorHandlers[i](error);
handled = true;
break;
}
catch (e) {
error = e;
}
}
if (handled) {
return true;
}
}
return _handleError(node.parent, error);
}
function handleError(params) {
let { error } = params;
// Wrap error if it wasn't wrapped by wrapError (ie when not in dev mode)
if (!(error instanceof OwlError)) {
error = Object.assign(new OwlError(`An error occured in the owl lifecycle (see this Error's "cause" property)`), { cause: error });
}
const node = "node" in params ? params.node : params.fiber.node;
const fiber = "fiber" in params ? params.fiber : node.fiber;
if (fiber) {
// resets the fibers on components if possible. This is important so that
// new renderings can be properly included in the initial one, if any.
let current = fiber;
do {
current.node.fiber = current;
current = current.parent;
} while (current);
fibersInError.set(fiber.root, error);
}
const handled = _handleError(node, error);
if (!handled) {
console.warn(`[Owl] Unhandled error. Destroying the root component`);
try {
node.app.destroy();
}
catch (e) {
console.error(e);
}
throw error;
}
}
function makeChildFiber(node, parent) {
let current = node.fiber;
if (current) {
@@ -1632,8 +1649,7 @@ function cancelFibers(fibers) {
let node = fiber.node;
fiber.render = throwOnRender;
if (node.status === 0 /* NEW */) {
node.destroy();
delete node.parent.children[node.parentKey];
node.cancel();
}
node.fiber = null;
if (fiber.bdom) {
@@ -2057,7 +2073,7 @@ function basicProxyHandler(callback) {
set(target, key, value, receiver) {
const hadKey = objectHasOwnProperty.call(target, key);
const originalValue = Reflect.get(target, key, receiver);
const ret = Reflect.set(target, key, value, receiver);
const ret = Reflect.set(target, key, toRaw(value), receiver);
if (!hadKey && objectHasOwnProperty.call(target, key)) {
notifyReactives(target, KEYCHANGES);
}
@@ -2161,7 +2177,7 @@ function delegateAndNotify(setterName, getterName, target) {
if (hadKey !== hasKey) {
notifyReactives(target, KEYCHANGES);
}
if (originalValue !== value) {
if (originalValue !== target[getterName](key)) {
notifyReactives(target, key);
}
return ret;
@@ -2360,6 +2376,9 @@ class ComponentNode {
}
}
async render(deep) {
if (this.status >= 2 /* CANCELLED */) {
return;
}
let current = this.fiber;
if (current && (current.root.locked || current.bdom === true)) {
await Promise.resolve();
@@ -2385,7 +2404,7 @@ class ComponentNode {
this.fiber = fiber;
this.app.scheduler.addFiber(fiber);
await Promise.resolve();
if (this.status === 2 /* DESTROYED */) {
if (this.status >= 2 /* CANCELLED */) {
return;
}
// We only want to actually render the component if the following two
@@ -2403,6 +2422,18 @@ class ComponentNode {
fiber.render();
}
}
cancel() {
this._cancel();
delete this.parent.children[this.parentKey];
this.app.scheduler.scheduleDestroy(this);
}
_cancel() {
this.status = 2 /* CANCELLED */;
const children = this.children;
for (let childKey in children) {
children[childKey]._cancel();
}
}
destroy() {
let shouldRemove = this.status === 1 /* MOUNTED */;
this._destroy();
@@ -2430,7 +2461,7 @@ class ComponentNode {
this.app.handleError({ error: e, node: this });
}
}
this.status = 2 /* DESTROYED */;
this.status = 3 /* DESTROYED */;
}
async updateAndRender(props, parentFiber) {
this.nextProps = props;
@@ -2963,12 +2994,20 @@ function prepareList(collection) {
keys = collection;
values = collection;
}
else if (collection) {
values = Object.keys(collection);
keys = Object.values(collection);
else if (collection instanceof Map) {
keys = [...collection.keys()];
values = [...collection.values()];
}
else if (Symbol.iterator in Object(collection)) {
keys = [...collection];
values = keys;
}
else if (collection && typeof collection === "object") {
values = Object.values(collection);
keys = Object.keys(collection);
}
else {
throw new OwlError("Invalid loop expression");
throw new OwlError(`Invalid loop expression: "${collection}" is not iterable`);
}
const n = values.length;
return [keys, values, n, new Array(n)];
@@ -3158,7 +3197,14 @@ class TemplateSet {
this.translateFn = config.translateFn;
this.translatableAttributes = config.translatableAttributes;
if (config.templates) {
this.addTemplates(config.templates);
if (config.templates instanceof Document || typeof config.templates === "string") {
this.addTemplates(config.templates);
}
else {
for (const name in config.templates) {
this.addTemplate(name, config.templates[name]);
}
}
}
}
static registerTemplate(name, fn) {
@@ -3166,6 +3212,10 @@ class TemplateSet {
}
addTemplate(name, template) {
if (name in this.rawTemplates) {
// this check can be expensive, just silently ignore double definitions outside dev mode
if (!this.dev) {
return;
}
const rawTemplate = this.rawTemplates[name];
const currentAsString = typeof rawTemplate === "string"
? rawTemplate
@@ -3809,7 +3859,7 @@ class CodeGenerator {
createBlock(parentBlock, type, ctx) {
const hasRoot = this.target.hasRoot;
const block = new BlockDescription(this.target, type);
if (!hasRoot && !ctx.preventRoot) {
if (!hasRoot) {
this.target.hasRoot = true;
block.isRoot = true;
}
@@ -3832,7 +3882,7 @@ class CodeGenerator {
if (ctx.tKeyExpr) {
blockExpr = `toggler(${ctx.tKeyExpr}, ${blockExpr})`;
}
if (block.isRoot && !ctx.preventRoot) {
if (block.isRoot) {
if (this.target.on) {
blockExpr = this.wrapWithEventCatcher(blockExpr, this.target.on);
}
@@ -3875,6 +3925,10 @@ class CodeGenerator {
})
.join("");
}
translate(str) {
const match = translationRE.exec(str);
return match[1] + this.translateFn(match[2]) + match[3];
}
/**
* @returns the newly created block name, if any
*/
@@ -3952,8 +4006,7 @@ class CodeGenerator {
let { block, forceNewBlock } = ctx;
let value = ast.value;
if (value && ctx.translate !== false) {
const match = translationRE.exec(value);
value = match[1] + this.translateFn(match[2]) + match[3];
value = this.translate(value);
}
if (!ctx.inPreTag) {
value = value.replace(whitespaceRE, " ");
@@ -4005,11 +4058,6 @@ class CodeGenerator {
}
// attributes
const attrs = {};
const nameSpace = ast.ns || ctx.nameSpace;
if (nameSpace && isNewBlock) {
// specific namespace uri
attrs["block-ns"] = nameSpace;
}
for (let key in ast.attrs) {
let expr, attrName;
if (key.startsWith("t-attf")) {
@@ -4125,7 +4173,10 @@ class CodeGenerator {
const idx = block.insertData(setRefStr, "ref");
attrs["block-ref"] = String(idx);
}
const dom = xmlDoc.createElement(ast.tag);
const nameSpace = ast.ns || ctx.nameSpace;
const dom = nameSpace
? xmlDoc.createElementNS(nameSpace, ast.tag)
: xmlDoc.createElement(ast.tag);
for (const [attr, val] of Object.entries(attrs)) {
if (!(attr === "class" && val === "")) {
dom.setAttribute(attr, val);
@@ -4167,7 +4218,7 @@ class CodeGenerator {
break;
}
}
this.addLine(`let ${block.children.map((c) => c.varName)};`, codeIdx);
this.addLine(`let ${block.children.map((c) => c.varName).join(", ")};`, codeIdx);
}
}
return block.varName;
@@ -4270,7 +4321,7 @@ class CodeGenerator {
break;
}
}
this.addLine(`let ${block.children.map((c) => c.varName)};`, codeIdx);
this.addLine(`let ${block.children.map((c) => c.varName).join(", ")};`, codeIdx);
}
// note: this part is duplicated from end of compilemulti:
const args = block.children.map((c) => c.varName).join(", ");
@@ -4299,18 +4350,18 @@ class CodeGenerator {
}
this.addLine(`for (let ${loopVar} = 0; ${loopVar} < ${l}; ${loopVar}++) {`);
this.target.indentLevel++;
this.addLine(`ctx[\`${ast.elem}\`] = ${vals}[${loopVar}];`);
this.addLine(`ctx[\`${ast.elem}\`] = ${keys}[${loopVar}];`);
if (!ast.hasNoFirst) {
this.addLine(`ctx[\`${ast.elem}_first\`] = ${loopVar} === 0;`);
}
if (!ast.hasNoLast) {
this.addLine(`ctx[\`${ast.elem}_last\`] = ${loopVar} === ${vals}.length - 1;`);
this.addLine(`ctx[\`${ast.elem}_last\`] = ${loopVar} === ${keys}.length - 1;`);
}
if (!ast.hasNoIndex) {
this.addLine(`ctx[\`${ast.elem}_index\`] = ${loopVar};`);
}
if (!ast.hasNoValue) {
this.addLine(`ctx[\`${ast.elem}_value\`] = ${keys}[${loopVar}];`);
this.addLine(`ctx[\`${ast.elem}_value\`] = ${vals}[${loopVar}];`);
}
this.define(`key${this.target.loopLevel}`, ast.key ? compileExpr(ast.key) : loopVar);
if (this.dev) {
@@ -4385,7 +4436,6 @@ class CodeGenerator {
block,
index,
forceNewBlock: !isTSet,
preventRoot: ctx.preventRoot,
isLast: ctx.isLast && i === l - 1,
});
this.compileAST(child, subCtx);
@@ -4394,21 +4444,19 @@ class CodeGenerator {
}
}
if (isNewBlock) {
if (block.hasDynamicChildren) {
if (block.children.length) {
const code = this.target.code;
const children = block.children.slice();
let current = children.shift();
for (let i = codeIdx; i < code.length; i++) {
if (code[i].trimStart().startsWith(`const ${current.varName} `)) {
code[i] = code[i].replace(`const ${current.varName}`, current.varName);
current = children.shift();
if (!current)
break;
}
if (block.hasDynamicChildren && block.children.length) {
const code = this.target.code;
const children = block.children.slice();
let current = children.shift();
for (let i = codeIdx; i < code.length; i++) {
if (code[i].trimStart().startsWith(`const ${current.varName} `)) {
code[i] = code[i].replace(`const ${current.varName}`, current.varName);
current = children.shift();
if (!current)
break;
}
this.addLine(`let ${block.children.map((c) => c.varName)};`, codeIdx);
}
this.addLine(`let ${block.children.map((c) => c.varName).join(", ")};`, codeIdx);
}
const args = block.children.map((c) => c.varName).join(", ");
this.insertBlock(`multi([${args}])`, block, ctx);
@@ -4422,24 +4470,23 @@ class CodeGenerator {
ctxVar = generateId("ctx");
this.addLine(`let ${ctxVar} = ${compileExpr(ast.context)};`);
}
const isDynamic = INTERP_REGEXP.test(ast.name);
const subTemplate = isDynamic ? interpolate(ast.name) : "`" + ast.name + "`";
if (block && !forceNewBlock) {
this.insertAnchor(block);
}
block = this.createBlock(block, "multi", ctx);
if (ast.body) {
this.addLine(`${ctxVar} = Object.create(${ctxVar});`);
this.addLine(`${ctxVar}[isBoundary] = 1;`);
this.helpers.add("isBoundary");
const subCtx = createContext(ctx, { preventRoot: true, ctxVar });
const subCtx = createContext(ctx, { ctxVar });
const bl = this.compileMulti({ type: 3 /* Multi */, content: ast.body }, subCtx);
if (bl) {
this.helpers.add("zero");
this.addLine(`${ctxVar}[zero] = ${bl};`);
}
}
const isDynamic = INTERP_REGEXP.test(ast.name);
const subTemplate = isDynamic ? interpolate(ast.name) : "`" + ast.name + "`";
if (block) {
if (!forceNewBlock) {
this.insertAnchor(block);
}
}
const key = `key + \`${this.generateComponentKey()}\``;
if (isDynamic) {
const templateVar = generateId("template");
@@ -4447,7 +4494,6 @@ class CodeGenerator {
this.staticDefs.push({ id: "call", expr: `app.callTemplate.bind(app)` });
}
this.define(templateVar, subTemplate);
block = this.createBlock(block, "multi", ctx);
this.insertBlock(`call(this, ${templateVar}, ${ctxVar}, node, ${key})`, block, {
...ctx,
forceNewBlock: !block,
@@ -4456,7 +4502,6 @@ class CodeGenerator {
else {
const id = generateId(`callTemplate_`);
this.staticDefs.push({ id, expr: `app.getTemplate(${subTemplate})` });
block = this.createBlock(block, "multi", ctx);
this.insertBlock(`${id}.call(this, ${ctxVar}, node, ${key})`, block, {
...ctx,
forceNewBlock: !block,
@@ -4494,11 +4539,12 @@ class CodeGenerator {
else {
let value;
if (ast.defaultValue) {
const defaultValue = ctx.translate ? this.translate(ast.defaultValue) : ast.defaultValue;
if (ast.value) {
value = `withDefault(${expr}, \`${ast.defaultValue}\`)`;
value = `withDefault(${expr}, \`${defaultValue}\`)`;
}
else {
value = `\`${ast.defaultValue}\``;
value = `\`${defaultValue}\``;
}
}
else {
@@ -4777,7 +4823,7 @@ function parse(xml) {
}
function _parse(xml) {
normalizeXML(xml);
const ctx = { inPreTag: false, inSVG: false };
const ctx = { inPreTag: false };
return parseNode(xml, ctx) || { type: 0 /* Text */, value: "" };
}
function parseNode(node, ctx) {
@@ -4791,10 +4837,10 @@ function parseNode(node, ctx) {
parseTCall(node, ctx) ||
parseTCallBlock(node) ||
parseTEscNode(node, ctx) ||
parseTOutNode(node, ctx) ||
parseTKey(node, ctx) ||
parseTTranslation(node, ctx) ||
parseTSlot(node, ctx) ||
parseTOutNode(node, ctx) ||
parseComponent(node, ctx) ||
parseDOMNode(node, ctx) ||
parseTSetNode(node, ctx) ||
@@ -4868,9 +4914,7 @@ function parseDOMNode(node, ctx) {
if (tagName === "pre") {
ctx.inPreTag = true;
}
const shouldAddSVGNS = ROOT_SVG_TAGS.has(tagName) && !ctx.inSVG;
ctx.inSVG = ctx.inSVG || shouldAddSVGNS;
const ns = shouldAddSVGNS ? "http://www.w3.org/2000/svg" : null;
let ns = !ctx.nameSpace && ROOT_SVG_TAGS.has(tagName) ? "http://www.w3.org/2000/svg" : null;
const ref = node.getAttribute("t-ref");
node.removeAttribute("t-ref");
const nodeAttrsNames = node.getAttributeNames();
@@ -4879,10 +4923,10 @@ function parseDOMNode(node, ctx) {
let model = null;
for (let attr of nodeAttrsNames) {
const value = node.getAttribute(attr);
if (attr.startsWith("t-on")) {
if (attr === "t-on") {
throw new OwlError("Missing event name with t-on directive");
}
if (attr === "t-on" || attr === "t-on-") {
throw new OwlError("Missing event name with t-on directive");
}
if (attr.startsWith("t-on-")) {
on = on || {};
on[attr.slice(5)] = value;
}
@@ -4907,10 +4951,8 @@ function parseDOMNode(node, ctx) {
const typeAttr = node.getAttribute("type");
const isInput = tagName === "input";
const isSelect = tagName === "select";
const isTextarea = tagName === "textarea";
const isCheckboxInput = isInput && typeAttr === "checkbox";
const isRadioInput = isInput && typeAttr === "radio";
const isOtherInput = isInput && !isCheckboxInput && !isRadioInput;
const hasLazyMod = attr.includes(".lazy");
const hasNumberMod = attr.includes(".number");
const hasTrimMod = attr.includes(".trim");
@@ -4922,8 +4964,8 @@ function parseDOMNode(node, ctx) {
specialInitTargetAttr: isRadioInput ? "checked" : null,
eventType,
hasDynamicChildren: false,
shouldTrim: hasTrimMod && (isOtherInput || isTextarea),
shouldNumberize: hasNumberMod && (isOtherInput || isTextarea),
shouldTrim: hasTrimMod,
shouldNumberize: hasNumberMod,
};
if (isSelect) {
// don't pollute the original ctx
@@ -4934,6 +4976,9 @@ function parseDOMNode(node, ctx) {
else if (attr.startsWith("block-")) {
throw new OwlError(`Invalid attribute: '${attr}'`);
}
else if (attr === "xmlns") {
ns = value;
}
else if (attr !== "t-name") {
if (attr.startsWith("t-") && !attr.startsWith("t-att")) {
throw new OwlError(`Unknown QWeb directive: '${attr}'`);
@@ -4946,6 +4991,9 @@ function parseDOMNode(node, ctx) {
attrs[attr] = value;
}
}
if (ns) {
ctx.nameSpace = ns;
}
const children = parseChildren(node, ctx);
return {
type: 2 /* DomNode */,
@@ -4986,9 +5034,6 @@ function parseTEscNode(node, ctx) {
content: [tesc],
};
}
if (ast.type === 11 /* TComponent */) {
throw new OwlError("t-esc is not supported on Component nodes");
}
return tesc;
}
// -----------------------------------------------------------------------------
@@ -5241,14 +5286,14 @@ function parseComponent(node, ctx) {
// be ignored)
let el = slotNode.parentElement;
let isInSubComponent = false;
while (el !== clone) {
while (el && el !== clone) {
if (el.hasAttribute("t-component") || el.tagName[0] === el.tagName[0].toUpperCase()) {
isInSubComponent = true;
break;
}
el = el.parentElement;
}
if (isInSubComponent) {
if (isInSubComponent || !el) {
continue;
}
slotNode.removeAttribute("t-set-slot");
@@ -5430,19 +5475,21 @@ function normalizeTIf(el) {
*
* @param el the element containing the tree that should be normalized
*/
function normalizeTEsc(el) {
const elements = [...el.querySelectorAll("[t-esc]")].filter((el) => el.tagName[0] === el.tagName[0].toUpperCase() || el.hasAttribute("t-component"));
for (const el of elements) {
if (el.childNodes.length) {
throw new OwlError("Cannot have t-esc on a component that already has content");
function normalizeTEscTOut(el) {
for (const d of ["t-esc", "t-out"]) {
const elements = [...el.querySelectorAll(`[${d}]`)].filter((el) => el.tagName[0] === el.tagName[0].toUpperCase() || el.hasAttribute("t-component"));
for (const el of elements) {
if (el.childNodes.length) {
throw new OwlError(`Cannot have ${d} on a component that already has content`);
}
const value = el.getAttribute(d);
el.removeAttribute(d);
const t = el.ownerDocument.createElement("t");
if (value != null) {
t.setAttribute(d, value);
}
el.appendChild(t);
}
const value = el.getAttribute("t-esc");
el.removeAttribute("t-esc");
const t = el.ownerDocument.createElement("t");
if (value != null) {
t.setAttribute("t-esc", value);
}
el.appendChild(t);
}
}
/**
@@ -5453,7 +5500,7 @@ function normalizeTEsc(el) {
*/
function normalizeXML(el) {
normalizeTIf(el);
normalizeTEsc(el);
normalizeTEscTOut(el);
}
/**
* Parses an XML string into an XML document, throwing errors on parser errors
@@ -5502,11 +5549,20 @@ function compile(template, options = {}) {
const codeGenerator = new CodeGenerator(ast, { ...options, hasSafeContext });
const code = codeGenerator.generateCode();
// template function
return new Function("app, bdom, helpers", code);
try {
return new Function("app, bdom, helpers", code);
}
catch (originalError) {
const { name } = options;
const nameStr = name ? `template "${name}"` : "anonymous template";
const err = new OwlError(`Failed to compile ${nameStr}: ${originalError.message}\n\ngenerated code:\nfunction(app, bdom, helpers) {\n${code}\n}`);
err.cause = originalError;
throw err;
}
}
// do not modify manually. This file is generated by the release script.
const version = "2.1.2";
const version = "2.2.7";
// -----------------------------------------------------------------------------
// Scheduler
@@ -5516,11 +5572,18 @@ class Scheduler {
this.tasks = new Set();
this.frame = 0;
this.delayedRenders = [];
this.cancelledNodes = new Set();
this.requestAnimationFrame = Scheduler.requestAnimationFrame;
}
addFiber(fiber) {
this.tasks.add(fiber.root);
}
scheduleDestroy(node) {
this.cancelledNodes.add(node);
if (this.frame === 0) {
this.frame = this.requestAnimationFrame(() => this.processTasks());
}
}
/**
* Process all current tasks. This only applies to the fibers that are ready.
* Other tasks are left unchanged.
@@ -5530,21 +5593,28 @@ class Scheduler {
let renders = this.delayedRenders;
this.delayedRenders = [];
for (let f of renders) {
if (f.root && f.node.status !== 2 /* DESTROYED */ && f.node.fiber === f) {
if (f.root && f.node.status !== 3 /* DESTROYED */ && f.node.fiber === f) {
f.render();
}
}
}
if (this.frame === 0) {
this.frame = this.requestAnimationFrame(() => {
this.frame = 0;
this.tasks.forEach((fiber) => this.processFiber(fiber));
for (let task of this.tasks) {
if (task.node.status === 2 /* DESTROYED */) {
this.tasks.delete(task);
}
}
});
this.frame = this.requestAnimationFrame(() => this.processTasks());
}
}
processTasks() {
this.frame = 0;
for (let node of this.cancelledNodes) {
node._destroy();
}
this.cancelledNodes.clear();
for (let task of this.tasks) {
this.processFiber(task);
}
for (let task of this.tasks) {
if (task.node.status === 3 /* DESTROYED */) {
this.tasks.delete(task);
}
}
}
processFiber(fiber) {
@@ -5557,7 +5627,7 @@ class Scheduler {
this.tasks.delete(fiber);
return;
}
if (fiber.node.status === 2 /* DESTROYED */) {
if (fiber.node.status === 3 /* DESTROYED */) {
this.tasks.delete(fiber);
return;
}
@@ -5581,11 +5651,8 @@ const DEV_MSG = () => {
This is not suitable for production use.
See https://github.com/odoo/owl/blob/${hash}/doc/reference/app.md#configuration for more information.`;
};
window.__OWL_DEVTOOLS__ || (window.__OWL_DEVTOOLS__ = {
apps: new Set(),
Fiber: Fiber,
RootFiber: RootFiber,
});
const apps = new Set();
window.__OWL_DEVTOOLS__ || (window.__OWL_DEVTOOLS__ = { apps, Fiber, RootFiber, toRaw, reactive });
class App extends TemplateSet {
constructor(Root, config = {}) {
super(config);
@@ -5593,7 +5660,7 @@ class App extends TemplateSet {
this.root = null;
this.name = config.name || "";
this.Root = Root;
window.__OWL_DEVTOOLS__.apps.add(this);
apps.add(this);
if (config.test) {
this.dev = true;
}
@@ -5647,10 +5714,10 @@ class App extends TemplateSet {
}
destroy() {
if (this.root) {
this.scheduler.flush();
this.root.destroy();
this.scheduler.processTasks();
}
window.__OWL_DEVTOOLS__.apps.delete(this);
apps.delete(this);
}
createComponent(name, isStatic, hasSlotsProp, hasDynamicPropList, propList) {
const isDynamic = !isStatic;
@@ -5725,6 +5792,7 @@ class App extends TemplateSet {
}
}
App.validateTarget = validateTarget;
App.apps = apps;
App.version = version;
async function mount(C, target, config = {}) {
return new App(C, config).mount(target, config);
@@ -5779,9 +5847,11 @@ function status(component) {
switch (component.__owl__.status) {
case 0 /* NEW */:
return "new";
case 2 /* CANCELLED */:
return "cancelled";
case 1 /* MOUNTED */:
return "mounted";
case 2 /* DESTROYED */:
case 3 /* DESTROYED */:
return "destroyed";
}
}
@@ -5837,8 +5907,9 @@ function useChildSubEnv(envExtension) {
* will run a cleanup function before patching and before unmounting the
* the component.
*
* @param {Effect} effect the effect to run on component mount and/or patch
* @param {()=>any[]} [computeDependencies=()=>[NaN]] a callback to compute
* @template T
* @param {Effect<T>} effect the effect to run on component mount and/or patch
* @param {()=>[...T]} [computeDependencies=()=>[NaN]] a callback to compute
* dependencies that will decide if the effect needs to be cleaned up and
* run again. If the dependencies did not change, the effect will not run
* again. The default value returns an array containing only NaN because
@@ -5920,6 +5991,6 @@ TemplateSet.prototype._compileTemplate = function _compileTemplate(name, templat
export { App, Component, EventBus, OwlError, __info__, blockDom, loadFile, markRaw, markup, mount, onError, onMounted, onPatched, onRendered, onWillDestroy, onWillPatch, onWillRender, onWillStart, onWillUnmount, onWillUpdateProps, reactive, status, toRaw, useChildSubEnv, useComponent, useEffect, useEnv, useExternalListener, useRef, useState, useSubEnv, validate, validateType, whenReady, xml };
__info__.date = '2023-04-29T07:45:54.333Z';
__info__.hash = 'aabb755';
__info__.date = '2023-12-06T13:56:01.636Z';
__info__.hash = 'e94428a';
__info__.url = 'https://github.com/odoo/owl';
+1 -5
View File
@@ -43,10 +43,6 @@ class TaskList {
}
}
toggleTask(task) {
task.isCompleted = !task.isCompleted;
}
toggleTask(id) {
const task = this.tasks.find(t => t.id === id);
task.isCompleted = !task.isCompleted;
@@ -61,7 +57,7 @@ class TaskList {
clearCompleted() {
const tasks = this.tasks.filter(t => t.isCompleted);
for (let task of tasks) {
this.deleteTask(task);
this.deleteTask(task.id);
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@odoo/owl",
"version": "2.1.3",
"version": "2.2.7",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@odoo/owl",
"version": "2.1.3",
"version": "2.2.7",
"description": "Odoo Web Library (OWL)",
"main": "dist/owl.cjs.js",
"module": "dist/owl.es.js",
+4
View File
@@ -0,0 +1,4 @@
// Custom error class that wraps error that happen in the owl lifecycle
export class OwlError extends Error {
cause?: any;
}
+39 -42
View File
@@ -29,7 +29,7 @@ import {
Attrs,
EventHandlers,
} from "./parser";
import { OwlError } from "../runtime/error_handling";
import { OwlError } from "../common/owl_error";
type BlockType = "block" | "text" | "multi" | "list" | "html" | "comment";
const whitespaceRE = /\s+/g;
@@ -160,7 +160,6 @@ interface Context {
block: BlockDescription | null;
index: number | string;
forceNewBlock: boolean;
preventRoot?: boolean;
isLast?: boolean;
translate: boolean;
tKeyExpr: string | null;
@@ -377,7 +376,7 @@ export class CodeGenerator {
): BlockDescription {
const hasRoot = this.target.hasRoot;
const block = new BlockDescription(this.target, type);
if (!hasRoot && !ctx.preventRoot) {
if (!hasRoot) {
this.target.hasRoot = true;
block.isRoot = true;
}
@@ -403,7 +402,7 @@ export class CodeGenerator {
blockExpr = `toggler(${ctx.tKeyExpr}, ${blockExpr})`;
}
if (block.isRoot && !ctx.preventRoot) {
if (block.isRoot) {
if (this.target.on) {
blockExpr = this.wrapWithEventCatcher(blockExpr, this.target.on);
}
@@ -447,6 +446,11 @@ export class CodeGenerator {
.join("");
}
translate(str: string): string {
const match = translationRE.exec(str) as any;
return match[1] + this.translateFn(match[2]) + match[3];
}
/**
* @returns the newly created block name, if any
*/
@@ -527,8 +531,7 @@ export class CodeGenerator {
let value = ast.value;
if (value && ctx.translate !== false) {
const match = translationRE.exec(value) as any;
value = match[1] + this.translateFn(match[2]) + match[3];
value = this.translate(value);
}
if (!ctx.inPreTag) {
value = value.replace(whitespaceRE, " ");
@@ -582,11 +585,6 @@ export class CodeGenerator {
}
// attributes
const attrs: Attrs = {};
const nameSpace = ast.ns || ctx.nameSpace;
if (nameSpace && isNewBlock) {
// specific namespace uri
attrs["block-ns"] = nameSpace;
}
for (let key in ast.attrs) {
let expr, attrName;
@@ -715,7 +713,10 @@ export class CodeGenerator {
attrs["block-ref"] = String(idx);
}
const dom = xmlDoc.createElement(ast.tag);
const nameSpace = ast.ns || ctx.nameSpace;
const dom = nameSpace
? xmlDoc.createElementNS(nameSpace, ast.tag)
: xmlDoc.createElement(ast.tag);
for (const [attr, val] of Object.entries(attrs)) {
if (!(attr === "class" && val === "")) {
dom.setAttribute(attr, val);
@@ -757,7 +758,7 @@ export class CodeGenerator {
if (!current) break;
}
}
this.addLine(`let ${block!.children.map((c) => c.varName)};`, codeIdx);
this.addLine(`let ${block!.children.map((c) => c.varName).join(", ")};`, codeIdx);
}
}
return block!.varName;
@@ -859,7 +860,7 @@ export class CodeGenerator {
if (!current) break;
}
}
this.addLine(`let ${block!.children.map((c) => c.varName)};`, codeIdx);
this.addLine(`let ${block!.children.map((c) => c.varName).join(", ")};`, codeIdx);
}
// note: this part is duplicated from end of compilemulti:
@@ -890,18 +891,18 @@ export class CodeGenerator {
}
this.addLine(`for (let ${loopVar} = 0; ${loopVar} < ${l}; ${loopVar}++) {`);
this.target.indentLevel++;
this.addLine(`ctx[\`${ast.elem}\`] = ${vals}[${loopVar}];`);
this.addLine(`ctx[\`${ast.elem}\`] = ${keys}[${loopVar}];`);
if (!ast.hasNoFirst) {
this.addLine(`ctx[\`${ast.elem}_first\`] = ${loopVar} === 0;`);
}
if (!ast.hasNoLast) {
this.addLine(`ctx[\`${ast.elem}_last\`] = ${loopVar} === ${vals}.length - 1;`);
this.addLine(`ctx[\`${ast.elem}_last\`] = ${loopVar} === ${keys}.length - 1;`);
}
if (!ast.hasNoIndex) {
this.addLine(`ctx[\`${ast.elem}_index\`] = ${loopVar};`);
}
if (!ast.hasNoValue) {
this.addLine(`ctx[\`${ast.elem}_value\`] = ${keys}[${loopVar}];`);
this.addLine(`ctx[\`${ast.elem}_value\`] = ${vals}[${loopVar}];`);
}
this.define(`key${this.target.loopLevel}`, ast.key ? compileExpr(ast.key) : loopVar);
if (this.dev) {
@@ -985,7 +986,6 @@ export class CodeGenerator {
block,
index,
forceNewBlock: !isTSet,
preventRoot: ctx.preventRoot,
isLast: ctx.isLast && i === l - 1,
});
this.compileAST(child, subCtx);
@@ -994,20 +994,18 @@ export class CodeGenerator {
}
}
if (isNewBlock) {
if (block!.hasDynamicChildren) {
if (block!.children.length) {
const code = this.target.code;
const children = block!.children.slice();
let current = children.shift();
for (let i = codeIdx; i < code.length; i++) {
if (code[i].trimStart().startsWith(`const ${current!.varName} `)) {
code[i] = code[i].replace(`const ${current!.varName}`, current!.varName);
current = children.shift();
if (!current) break;
}
if (block!.hasDynamicChildren && block!.children.length) {
const code = this.target.code;
const children = block!.children.slice();
let current = children.shift();
for (let i = codeIdx; i < code.length; i++) {
if (code[i].trimStart().startsWith(`const ${current!.varName} `)) {
code[i] = code[i].replace(`const ${current!.varName}`, current!.varName);
current = children.shift();
if (!current) break;
}
this.addLine(`let ${block!.children.map((c) => c.varName)};`, codeIdx);
}
this.addLine(`let ${block!.children.map((c) => c.varName).join(", ")};`, codeIdx);
}
const args = block!.children.map((c) => c.varName).join(", ");
@@ -1023,24 +1021,24 @@ export class CodeGenerator {
ctxVar = generateId("ctx");
this.addLine(`let ${ctxVar} = ${compileExpr(ast.context)};`);
}
const isDynamic = INTERP_REGEXP.test(ast.name);
const subTemplate = isDynamic ? interpolate(ast.name) : "`" + ast.name + "`";
if (block && !forceNewBlock) {
this.insertAnchor(block);
}
block = this.createBlock(block, "multi", ctx);
if (ast.body) {
this.addLine(`${ctxVar} = Object.create(${ctxVar});`);
this.addLine(`${ctxVar}[isBoundary] = 1;`);
this.helpers.add("isBoundary");
const subCtx = createContext(ctx, { preventRoot: true, ctxVar });
const subCtx = createContext(ctx, { ctxVar });
const bl = this.compileMulti({ type: ASTType.Multi, content: ast.body }, subCtx);
if (bl) {
this.helpers.add("zero");
this.addLine(`${ctxVar}[zero] = ${bl};`);
}
}
const isDynamic = INTERP_REGEXP.test(ast.name);
const subTemplate = isDynamic ? interpolate(ast.name) : "`" + ast.name + "`";
if (block) {
if (!forceNewBlock) {
this.insertAnchor(block);
}
}
const key = `key + \`${this.generateComponentKey()}\``;
if (isDynamic) {
const templateVar = generateId("template");
@@ -1048,7 +1046,6 @@ export class CodeGenerator {
this.staticDefs.push({ id: "call", expr: `app.callTemplate.bind(app)` });
}
this.define(templateVar, subTemplate);
block = this.createBlock(block, "multi", ctx);
this.insertBlock(`call(this, ${templateVar}, ${ctxVar}, node, ${key})`, block!, {
...ctx,
forceNewBlock: !block,
@@ -1056,7 +1053,6 @@ export class CodeGenerator {
} else {
const id = generateId(`callTemplate_`);
this.staticDefs.push({ id, expr: `app.getTemplate(${subTemplate})` });
block = this.createBlock(block, "multi", ctx);
this.insertBlock(`${id}.call(this, ${ctxVar}, node, ${key})`, block!, {
...ctx,
forceNewBlock: !block,
@@ -1095,10 +1091,11 @@ export class CodeGenerator {
} else {
let value: string;
if (ast.defaultValue) {
const defaultValue = ctx.translate ? this.translate(ast.defaultValue) : ast.defaultValue;
if (ast.value) {
value = `withDefault(${expr}, \`${ast.defaultValue}\`)`;
value = `withDefault(${expr}, \`${defaultValue}\`)`;
} else {
value = `\`${ast.defaultValue}\``;
value = `\`${defaultValue}\``;
}
} else {
value = expr;
+12 -1
View File
@@ -2,6 +2,7 @@ import type { TemplateSet } from "../runtime/template_set";
import type { BDom } from "../runtime/blockdom";
import { CodeGenerator, Config } from "./code_generator";
import { parse } from "./parser";
import { OwlError } from "../common/owl_error";
export type Template = (context: any, vnode: any, key?: string) => BDom;
@@ -27,5 +28,15 @@ export function compile(
const codeGenerator = new CodeGenerator(ast, { ...options, hasSafeContext });
const code = codeGenerator.generateCode();
// template function
return new Function("app, bdom, helpers", code) as TemplateFunction;
try {
return new Function("app, bdom, helpers", code) as TemplateFunction;
} catch (originalError: any) {
const { name } = options;
const nameStr = name ? `template "${name}"` : "anonymous template";
const err = new OwlError(
`Failed to compile ${nameStr}: ${originalError.message}\n\ngenerated code:\nfunction(app, bdom, helpers) {\n${code}\n}`
);
err.cause = originalError;
throw err;
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
import { OwlError } from "../runtime/error_handling";
import { OwlError } from "../common/owl_error";
/**
* Owl QWeb Expression Parser
+36 -35
View File
@@ -1,4 +1,4 @@
import { OwlError } from "../runtime/error_handling";
import { OwlError } from "../common/owl_error";
// -----------------------------------------------------------------------------
// AST Type definition
@@ -213,14 +213,14 @@ export function parse(xml: string | Element): AST {
function _parse(xml: Element): AST {
normalizeXML(xml);
const ctx = { inPreTag: false, inSVG: false };
const ctx = { inPreTag: false };
return parseNode(xml, ctx) || { type: ASTType.Text, value: "" };
}
interface ParsingContext {
tModelInfo?: TModelInfo | null;
nameSpace?: string;
inPreTag: boolean;
inSVG: boolean;
}
function parseNode(node: Node, ctx: ParsingContext): AST | null {
@@ -235,10 +235,10 @@ function parseNode(node: Node, ctx: ParsingContext): AST | null {
parseTCall(node, ctx) ||
parseTCallBlock(node, ctx) ||
parseTEscNode(node, ctx) ||
parseTOutNode(node, ctx) ||
parseTKey(node, ctx) ||
parseTTranslation(node, ctx) ||
parseTSlot(node, ctx) ||
parseTOutNode(node, ctx) ||
parseComponent(node, ctx) ||
parseDOMNode(node, ctx) ||
parseTSetNode(node, ctx) ||
@@ -323,9 +323,8 @@ function parseDOMNode(node: Element, ctx: ParsingContext): AST | null {
if (tagName === "pre") {
ctx.inPreTag = true;
}
const shouldAddSVGNS = ROOT_SVG_TAGS.has(tagName) && !ctx.inSVG;
ctx.inSVG = ctx.inSVG || shouldAddSVGNS;
const ns = shouldAddSVGNS ? "http://www.w3.org/2000/svg" : null;
let ns = !ctx.nameSpace && ROOT_SVG_TAGS.has(tagName) ? "http://www.w3.org/2000/svg" : null;
const ref = node.getAttribute("t-ref");
node.removeAttribute("t-ref");
@@ -336,10 +335,10 @@ function parseDOMNode(node: Element, ctx: ParsingContext): AST | null {
for (let attr of nodeAttrsNames) {
const value = node.getAttribute(attr)!;
if (attr.startsWith("t-on")) {
if (attr === "t-on") {
throw new OwlError("Missing event name with t-on directive");
}
if (attr === "t-on" || attr === "t-on-") {
throw new OwlError("Missing event name with t-on directive");
}
if (attr.startsWith("t-on-")) {
on = on || {};
on[attr.slice(5)] = value;
} else if (attr.startsWith("t-model")) {
@@ -365,10 +364,8 @@ function parseDOMNode(node: Element, ctx: ParsingContext): AST | null {
const typeAttr = node.getAttribute("type");
const isInput = tagName === "input";
const isSelect = tagName === "select";
const isTextarea = tagName === "textarea";
const isCheckboxInput = isInput && typeAttr === "checkbox";
const isRadioInput = isInput && typeAttr === "radio";
const isOtherInput = isInput && !isCheckboxInput && !isRadioInput;
const hasLazyMod = attr.includes(".lazy");
const hasNumberMod = attr.includes(".number");
const hasTrimMod = attr.includes(".trim");
@@ -381,8 +378,8 @@ function parseDOMNode(node: Element, ctx: ParsingContext): AST | null {
specialInitTargetAttr: isRadioInput ? "checked" : null,
eventType,
hasDynamicChildren: false,
shouldTrim: hasTrimMod && (isOtherInput || isTextarea),
shouldNumberize: hasNumberMod && (isOtherInput || isTextarea),
shouldTrim: hasTrimMod,
shouldNumberize: hasNumberMod,
};
if (isSelect) {
// don't pollute the original ctx
@@ -391,6 +388,8 @@ function parseDOMNode(node: Element, ctx: ParsingContext): AST | null {
}
} else if (attr.startsWith("block-")) {
throw new OwlError(`Invalid attribute: '${attr}'`);
} else if (attr === "xmlns") {
ns = value;
} else if (attr !== "t-name") {
if (attr.startsWith("t-") && !attr.startsWith("t-att")) {
throw new OwlError(`Unknown QWeb directive: '${attr}'`);
@@ -403,6 +402,9 @@ function parseDOMNode(node: Element, ctx: ParsingContext): AST | null {
attrs[attr] = value;
}
}
if (ns) {
ctx.nameSpace = ns;
}
const children = parseChildren(node, ctx);
return {
@@ -446,9 +448,6 @@ function parseTEscNode(node: Element, ctx: ParsingContext): AST | null {
content: [tesc],
};
}
if (ast.type === ASTType.TComponent) {
throw new OwlError("t-esc is not supported on Component nodes");
}
return tesc;
}
@@ -741,14 +740,14 @@ function parseComponent(node: Element, ctx: ParsingContext): AST | null {
// be ignored)
let el = slotNode.parentElement!;
let isInSubComponent = false;
while (el !== clone) {
while (el && el !== clone) {
if (el!.hasAttribute("t-component") || el!.tagName[0] === el!.tagName[0].toUpperCase()) {
isInSubComponent = true;
break;
}
el = el.parentElement!;
}
if (isInSubComponent) {
if (isInSubComponent || !el) {
continue;
}
@@ -943,21 +942,23 @@ function normalizeTIf(el: Element) {
*
* @param el the element containing the tree that should be normalized
*/
function normalizeTEsc(el: Element) {
const elements = [...el.querySelectorAll("[t-esc]")].filter(
(el) => el.tagName[0] === el.tagName[0].toUpperCase() || el.hasAttribute("t-component")
);
for (const el of elements) {
if (el.childNodes.length) {
throw new OwlError("Cannot have t-esc on a component that already has content");
function normalizeTEscTOut(el: Element) {
for (const d of ["t-esc", "t-out"]) {
const elements = [...el.querySelectorAll(`[${d}]`)].filter(
(el) => el.tagName[0] === el.tagName[0].toUpperCase() || el.hasAttribute("t-component")
);
for (const el of elements) {
if (el.childNodes.length) {
throw new OwlError(`Cannot have ${d} on a component that already has content`);
}
const value = el.getAttribute(d);
el.removeAttribute(d);
const t = el.ownerDocument.createElement("t");
if (value != null) {
t.setAttribute(d, value);
}
el.appendChild(t);
}
const value = el.getAttribute("t-esc");
el.removeAttribute("t-esc");
const t = el.ownerDocument.createElement("t");
if (value != null) {
t.setAttribute("t-esc", value);
}
el.appendChild(t);
}
}
@@ -969,7 +970,7 @@ function normalizeTEsc(el: Element) {
*/
function normalizeXML(el: Element) {
normalizeTIf(el);
normalizeTEsc(el);
normalizeTEscTOut(el);
}
/**
+12 -9
View File
@@ -1,12 +1,14 @@
import { version } from "../version";
import { Component, ComponentConstructor, Props } from "./component";
import { ComponentNode } from "./component_node";
import { nodeErrorHandlers, OwlError, handleError } from "./error_handling";
import { nodeErrorHandlers, handleError } from "./error_handling";
import { OwlError } from "../common/owl_error";
import { Fiber, RootFiber, MountOptions } from "./fibers";
import { Scheduler } from "./scheduler";
import { validateProps } from "./template_helpers";
import { TemplateSet, TemplateSetConfig } from "./template_set";
import { validateTarget } from "./utils";
import { toRaw, reactive } from "./reactivity";
// reimplement dev mode stuff see last change in 0f7a8289a6fb8387c3c1af41c6664b2a8448758f
@@ -33,21 +35,21 @@ This is not suitable for production use.
See https://github.com/odoo/owl/blob/${hash}/doc/reference/app.md#configuration for more information.`;
};
const apps = new Set<App>();
declare global {
interface Window {
__OWL_DEVTOOLS__: {
apps: Set<App>;
Fiber: typeof Fiber;
RootFiber: typeof RootFiber;
toRaw: typeof toRaw;
reactive: typeof reactive;
};
}
}
window.__OWL_DEVTOOLS__ ||= {
apps: new Set<App>(),
Fiber: Fiber,
RootFiber: RootFiber,
};
window.__OWL_DEVTOOLS__ ||= { apps, Fiber, RootFiber, toRaw, reactive };
export class App<
T extends abstract new (...args: any) => any = any,
@@ -55,6 +57,7 @@ export class App<
E = any
> extends TemplateSet {
static validateTarget = validateTarget;
static apps = apps;
static version = version;
name: string;
@@ -69,7 +72,7 @@ export class App<
super(config);
this.name = config.name || "";
this.Root = Root;
window.__OWL_DEVTOOLS__.apps.add(this);
apps.add(this);
if (config.test) {
this.dev = true;
}
@@ -131,10 +134,10 @@ export class App<
destroy() {
if (this.root) {
this.scheduler.flush();
this.root.destroy();
this.scheduler.processTasks();
}
window.__OWL_DEVTOOLS__.apps.delete(this);
apps.delete(this);
}
createComponent<P extends Props>(
+25 -5
View File
@@ -36,10 +36,18 @@ export function createAttrUpdater(attr: string): Setter<HTMLElement> {
export function attrsSetter(this: HTMLElement, attrs: any) {
if (isArray(attrs)) {
setAttribute.call(this, attrs[0], attrs[1]);
if (attrs[0] === "class") {
setClass.call(this, attrs[1]);
} else {
setAttribute.call(this, attrs[0], attrs[1]);
}
} else {
for (let k in attrs) {
setAttribute.call(this, k, attrs[k]);
if (k === "class") {
setClass.call(this, attrs[k]);
} else {
setAttribute.call(this, k, attrs[k]);
}
}
}
}
@@ -52,7 +60,11 @@ export function attrsUpdater(this: HTMLElement, attrs: any, oldAttrs: any) {
if (val === oldAttrs[1]) {
return;
}
setAttribute.call(this, name, val);
if (name === "class") {
updateClass.call(this, val, oldAttrs[1]);
} else {
setAttribute.call(this, name, val);
}
} else {
removeAttribute.call(this, oldAttrs[0]);
setAttribute.call(this, name, val);
@@ -60,13 +72,21 @@ export function attrsUpdater(this: HTMLElement, attrs: any, oldAttrs: any) {
} else {
for (let k in oldAttrs) {
if (!(k in attrs)) {
removeAttribute.call(this, k);
if (k === "class") {
updateClass.call(this, "", oldAttrs[k]);
} else {
removeAttribute.call(this, k);
}
}
}
for (let k in attrs) {
const val = attrs[k];
if (val !== oldAttrs[k]) {
setAttribute.call(this, k, val);
if (k === "class") {
updateClass.call(this, val, oldAttrs[k]);
} else {
setAttribute.call(this, k, val);
}
}
}
}
+3 -7
View File
@@ -1,4 +1,4 @@
import { OwlError } from "../error_handling";
import { OwlError } from "../../common/owl_error";
import { attrsSetter, attrsUpdater, createAttrUpdater, setClass, updateClass } from "./attributes";
import { config } from "./config";
import { createEventHandler } from "./events";
@@ -144,12 +144,7 @@ function buildTree(
info.push({ type: "child", idx: index });
el = document.createTextNode("");
}
const attrs = (node as Element).attributes;
const ns = attrs.getNamedItem("block-ns");
if (ns) {
attrs.removeNamedItem("block-ns");
currentNS = ns.value;
}
currentNS ||= (node as Element).namespaceURI;
if (!el) {
el = currentNS
? document.createElementNS(currentNS, tagName)
@@ -165,6 +160,7 @@ function buildTree(
const fragment = document.createElement("template").content;
fragment.appendChild(el);
}
const attrs = (node as Element).attributes;
for (let i = 0; i < attrs.length; i++) {
const attrName = attrs[i].name;
const attrValue = attrs[i].value;
+1 -1
View File
@@ -23,7 +23,7 @@ export type ComponentConstructor<P extends Props = any, E = any> = (new (
export class Component<Props = any, Env = any> {
static template: string = "";
static props?: any;
static props?: Schema;
static defaultProps?: any;
props: Props;
+20 -2
View File
@@ -1,7 +1,8 @@
import type { App, Env } from "./app";
import { BDom, VNode } from "./blockdom";
import { Component, ComponentConstructor, Props } from "./component";
import { fibersInError, OwlError } from "./error_handling";
import { fibersInError } from "./error_handling";
import { OwlError } from "../common/owl_error";
import { Fiber, makeChildFiber, makeRootFiber, MountFiber, MountOptions } from "./fibers";
import { clearReactivesForCallback, getSubscriptions, reactive, targets } from "./reactivity";
import { STATUS } from "./status";
@@ -145,6 +146,9 @@ export class ComponentNode<P extends Props = any, E = any> implements VNode<Comp
}
async render(deep: boolean) {
if (this.status >= STATUS.CANCELLED) {
return;
}
let current = this.fiber;
if (current && (current.root!.locked || (current as any).bdom === true)) {
await Promise.resolve();
@@ -171,7 +175,7 @@ export class ComponentNode<P extends Props = any, E = any> implements VNode<Comp
this.app.scheduler.addFiber(fiber);
await Promise.resolve();
if (this.status === STATUS.DESTROYED) {
if (this.status >= STATUS.CANCELLED) {
return;
}
// We only want to actually render the component if the following two
@@ -190,6 +194,20 @@ export class ComponentNode<P extends Props = any, E = any> implements VNode<Comp
}
}
cancel() {
this._cancel();
delete this.parent!.children[this.parentKey!];
this.app.scheduler.scheduleDestroy(this);
}
_cancel() {
this.status = STATUS.CANCELLED;
const children = this.children;
for (let childKey in children) {
children[childKey]._cancel();
}
}
destroy() {
let shouldRemove = this.status === STATUS.MOUNTED;
this._destroy();
+12 -14
View File
@@ -1,11 +1,7 @@
import { OwlError } from "../common/owl_error";
import type { ComponentNode } from "./component_node";
import type { Fiber } from "./fibers";
// Custom error class that wraps error that happen in the owl lifecycle
export class OwlError extends Error {
cause?: any;
}
// Maps fibers to thrown errors
export const fibersInError: WeakMap<Fiber, any> = new WeakMap();
export const nodeErrorHandlers: WeakMap<ComponentNode, ((error: any) => void)[]> = new WeakMap();
@@ -51,17 +47,19 @@ export function handleError(params: ErrorParams) {
);
}
const node = "node" in params ? params.node : params.fiber.node;
const fiber = "fiber" in params ? params.fiber : node.fiber!;
const fiber = "fiber" in params ? params.fiber : node.fiber;
// resets the fibers on components if possible. This is important so that
// new renderings can be properly included in the initial one, if any.
let current: Fiber | null = fiber;
do {
current.node.fiber = current;
current = current.parent;
} while (current);
if (fiber) {
// resets the fibers on components if possible. This is important so that
// new renderings can be properly included in the initial one, if any.
let current: Fiber | null = fiber;
do {
current.node.fiber = current;
current = current.parent;
} while (current);
fibersInError.set(fiber.root!, error);
fibersInError.set(fiber.root!, error);
}
const handled = _handleError(node, error);
if (!handled) {
+1 -1
View File
@@ -1,6 +1,6 @@
import { filterOutModifiersFromData } from "./blockdom/config";
import { STATUS } from "./status";
import { OwlError } from "./error_handling";
import { OwlError } from "../common/owl_error";
export const mainEventHandler = (data: any, ev: Event, currentTarget?: EventTarget | null) => {
const { data: _data, modifiers } = filterOutModifiersFromData(data);
+3 -3
View File
@@ -1,6 +1,7 @@
import { BDom, mount } from "./blockdom";
import type { ComponentNode } from "./component_node";
import { fibersInError, OwlError } from "./error_handling";
import { fibersInError } from "./error_handling";
import { OwlError } from "../common/owl_error";
import { STATUS } from "./status";
export function makeChildFiber(node: ComponentNode, parent: Fiber): Fiber {
@@ -55,8 +56,7 @@ function cancelFibers(fibers: Fiber[]): number {
let node = fiber.node;
fiber.render = throwOnRender;
if (node.status === STATUS.NEW) {
node.destroy();
delete node.parent!.children[node.parentKey!];
node.cancel();
}
node.fiber = null;
if (fiber.bdom) {
+13 -6
View File
@@ -59,28 +59,35 @@ export function useChildSubEnv(envExtension: Env) {
// useEffect
// -----------------------------------------------------------------------------
type EffectDeps<T extends unknown[]> = T | (T extends [...infer H, never] ? EffectDeps<H> : never);
/**
* @param {...any} dependencies the dependencies computed by computeDependencies
* @template T
* @param {...T} dependencies the dependencies computed by computeDependencies
* @returns {void|(()=>void)} a cleanup function that reverses the side
* effects of the effect callback.
*/
type Effect = (...dependencies: any[]) => void | (() => void);
type Effect<T extends unknown[]> = (...dependencies: EffectDeps<T>) => void | (() => void);
/**
* This hook will run a callback when a component is mounted and patched, and
* will run a cleanup function before patching and before unmounting the
* the component.
*
* @param {Effect} effect the effect to run on component mount and/or patch
* @param {()=>any[]} [computeDependencies=()=>[NaN]] a callback to compute
* @template T
* @param {Effect<T>} effect the effect to run on component mount and/or patch
* @param {()=>[...T]} [computeDependencies=()=>[NaN]] a callback to compute
* dependencies that will decide if the effect needs to be cleaned up and
* run again. If the dependencies did not change, the effect will not run
* again. The default value returns an array containing only NaN because
* NaN !== NaN, which will cause the effect to rerun on every patch.
*/
export function useEffect(effect: Effect, computeDependencies: () => any[] = () => [NaN]) {
export function useEffect<T extends unknown[]>(
effect: Effect<T>,
computeDependencies: () => [...T] = () => [NaN] as never
) {
let cleanup: (() => void) | void;
let dependencies: any[];
let dependencies: T;
onMounted(() => {
dependencies = computeDependencies();
cleanup = effect(...dependencies);
+1 -1
View File
@@ -55,7 +55,7 @@ export {
onError,
} from "./lifecycle_hooks";
export { validate, validateType } from "./validation";
export { OwlError } from "./error_handling";
export { OwlError } from "../common/owl_error";
export const __info__ = {
version: App.version,
+2 -1
View File
@@ -1,5 +1,6 @@
import { getCurrent } from "./component_node";
import { nodeErrorHandlers, OwlError } from "./error_handling";
import { nodeErrorHandlers } from "./error_handling";
import { OwlError } from "../common/owl_error";
const TIMEOUT = Symbol("timeout");
function wrapError(fn: (...args: any[]) => any, hookName: string) {
+2 -2
View File
@@ -1,7 +1,7 @@
import { onMounted, onWillUnmount } from "./lifecycle_hooks";
import { BDom, text, VNode } from "./blockdom";
import { Component } from "./component";
import { OwlError } from "./error_handling";
import { OwlError } from "../common/owl_error";
const VText: any = text("").constructor;
@@ -65,7 +65,7 @@ export class Portal extends Component {
type: String,
},
slots: true,
};
} as const;
setup() {
const node: any = this.__owl__;
+3 -3
View File
@@ -1,5 +1,5 @@
import type { Callback } from "./utils";
import { OwlError } from "./error_handling";
import { OwlError } from "../common/owl_error";
// Special key to subscribe to, to be notified of key creation/deletion
const KEYCHANGES = Symbol("Key changes");
@@ -249,7 +249,7 @@ function basicProxyHandler<T extends Target>(callback: Callback): ProxyHandler<T
set(target, key, value, receiver) {
const hadKey = objectHasOwnProperty.call(target, key);
const originalValue = Reflect.get(target, key, receiver);
const ret = Reflect.set(target, key, value, receiver);
const ret = Reflect.set(target, key, toRaw(value), receiver);
if (!hadKey && objectHasOwnProperty.call(target, key)) {
notifyReactives(target, KEYCHANGES);
}
@@ -368,7 +368,7 @@ function delegateAndNotify(
if (hadKey !== hasKey) {
notifyReactives(target, KEYCHANGES);
}
if (originalValue !== value) {
if (originalValue !== target[getterName](key)) {
notifyReactives(target, key);
}
return ret;
+26 -9
View File
@@ -1,3 +1,4 @@
import type { ComponentNode } from "./component_node";
import { fibersInError } from "./error_handling";
import { Fiber, RootFiber } from "./fibers";
import { STATUS } from "./status";
@@ -14,6 +15,7 @@ export class Scheduler {
requestAnimationFrame: Window["requestAnimationFrame"];
frame: number = 0;
delayedRenders: Fiber[] = [];
cancelledNodes: Set<ComponentNode> = new Set();
constructor() {
this.requestAnimationFrame = Scheduler.requestAnimationFrame;
@@ -23,6 +25,13 @@ export class Scheduler {
this.tasks.add(fiber.root!);
}
scheduleDestroy(node: ComponentNode) {
this.cancelledNodes.add(node);
if (this.frame === 0) {
this.frame = this.requestAnimationFrame(() => this.processTasks());
}
}
/**
* Process all current tasks. This only applies to the fibers that are ready.
* Other tasks are left unchanged.
@@ -39,15 +48,23 @@ export class Scheduler {
}
if (this.frame === 0) {
this.frame = this.requestAnimationFrame(() => {
this.frame = 0;
this.tasks.forEach((fiber) => this.processFiber(fiber));
for (let task of this.tasks) {
if (task.node.status === STATUS.DESTROYED) {
this.tasks.delete(task);
}
}
});
this.frame = this.requestAnimationFrame(() => this.processTasks());
}
}
processTasks() {
this.frame = 0;
for (let node of this.cancelledNodes) {
node._destroy();
}
this.cancelledNodes.clear();
for (let task of this.tasks) {
this.processFiber(task);
}
for (let task of this.tasks) {
if (task.node.status === STATUS.DESTROYED) {
this.tasks.delete(task);
}
}
}
+6 -1
View File
@@ -7,15 +7,20 @@ import type { Component } from "./component";
export const enum STATUS {
NEW,
MOUNTED, // is ready, and in DOM. It has a valid el
// component has been created, but has been replaced by a newer component before being mounted
// it is cancelled until the next animation frame where it will be destroyed
CANCELLED,
DESTROYED,
}
type STATUS_DESCR = "new" | "mounted" | "destroyed";
type STATUS_DESCR = "new" | "mounted" | "cancelled" | "destroyed";
export function status(component: Component): STATUS_DESCR {
switch (component.__owl__.status) {
case STATUS.NEW:
return "new";
case STATUS.CANCELLED:
return "cancelled";
case STATUS.MOUNTED:
return "mounted";
case STATUS.DESTROYED:
+14 -8
View File
@@ -4,7 +4,7 @@ import { html } from "./blockdom/index";
import { isOptional, validateSchema } from "./validation";
import type { ComponentConstructor } from "./component";
import { markRaw } from "./reactivity";
import { OwlError } from "./error_handling";
import { OwlError } from "../common/owl_error";
import type { ComponentNode } from "./component_node";
const ObjectCreate = Object.create;
@@ -60,18 +60,24 @@ function withKey(elem: any, k: string) {
return elem;
}
function prepareList(collection: any): [any[], any[], number, any[]] {
let keys: any[];
let values: any[];
function prepareList(collection: unknown): [unknown[], unknown[], number, undefined[]] {
let keys: unknown[];
let values: unknown[];
if (Array.isArray(collection)) {
keys = collection;
values = collection;
} else if (collection) {
values = Object.keys(collection);
keys = Object.values(collection);
} else if (collection instanceof Map) {
keys = [...collection.keys()];
values = [...collection.values()];
} else if (Symbol.iterator in Object(collection)) {
keys = [...(<Iterable<unknown>>collection)];
values = keys;
} else if (collection && typeof collection === "object") {
values = Object.values(collection);
keys = Object.keys(collection);
} else {
throw new OwlError("Invalid loop expression");
throw new OwlError(`Invalid loop expression: "${collection}" is not iterable`);
}
const n = values.length;
return [keys, values, n, new Array(n)];
+13 -3
View File
@@ -3,7 +3,7 @@ import { comment, createBlock, html, list, multi, text, toggler } from "./blockd
import { getCurrent } from "./component_node";
import { Portal, portalTemplate } from "./portal";
import { helpers } from "./template_helpers";
import { OwlError } from "./error_handling";
import { OwlError } from "../common/owl_error";
const bdom = { text, createBlock, list, multi, html, toggler, comment };
@@ -41,7 +41,7 @@ export interface TemplateSetConfig {
dev?: boolean;
translatableAttributes?: string[];
translateFn?: (s: string) => string;
templates?: string | Document;
templates?: string | Document | Record<string, string>;
}
export class TemplateSet {
@@ -60,12 +60,22 @@ export class TemplateSet {
this.translateFn = config.translateFn;
this.translatableAttributes = config.translatableAttributes;
if (config.templates) {
this.addTemplates(config.templates);
if (config.templates instanceof Document || typeof config.templates === "string") {
this.addTemplates(config.templates);
} else {
for (const name in config.templates) {
this.addTemplate(name, config.templates[name]);
}
}
}
}
addTemplate(name: string, template: string | Element) {
if (name in this.rawTemplates) {
// this check can be expensive, just silently ignore double definitions outside dev mode
if (!this.dev) {
return;
}
const rawTemplate = this.rawTemplates[name];
const currentAsString =
typeof rawTemplate === "string"
+8 -15
View File
@@ -1,4 +1,4 @@
import { OwlError } from "./error_handling";
import { OwlError } from "../common/owl_error";
export type Callback = () => void;
/**
@@ -9,20 +9,13 @@ export type Callback = () => void;
* @returns a batched version of the original callback
*/
export function batched(callback: Callback): Callback {
let called = false;
return async () => {
// This await blocks all calls to the callback here, then releases them sequentially
// in the next microtick. This line decides the granularity of the batch.
await Promise.resolve();
if (!called) {
called = true;
// wait for all calls in this microtick to fall through before resetting "called"
// so that only the first call to the batched function calls the original callback.
// Schedule this before calling the callback so that calls to the batched function
// within the callback will proceed only after resetting called to false, and have
// a chance to execute the callback again
Promise.resolve().then(() => (called = false));
callback();
let scheduled = false;
return async (...args) => {
if (!scheduled) {
scheduled = true;
await Promise.resolve();
scheduled = false;
callback(...args);
}
};
}
+2 -1
View File
@@ -1,4 +1,4 @@
import { OwlError } from "./error_handling";
import { OwlError } from "../common/owl_error";
import { toRaw } from "./reactivity";
type BaseType =
@@ -8,6 +8,7 @@ type BaseType =
| typeof Date
| typeof Object
| typeof Array
| typeof Function
| true
| "*";
+1 -1
View File
@@ -1,2 +1,2 @@
// do not modify manually. This file is generated by the release script.
export const version = "2.1.3";
export const version = "2.2.7";
+1 -1
View File
@@ -353,7 +353,7 @@ exports[`Reactivity: useState useless atoms should be deleted 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(Object.keys(ctx['state']));;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`id\`] = v_block2[i1];
ctx[\`id\`] = k_block2[i1];
const key1 = ctx['id'];
c_block2[i1] = withKey(comp1({id: ctx['id']}, key + \`__1__\${key1}\`, node, this, null), key1);
}
+41
View File
@@ -15,6 +15,34 @@ exports[`app App supports env with getters/setters 1`] = `
}"
`;
exports[`app app: clear scheduler tasks and destroy cancelled nodes immediately on destroy 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
const comp1 = app.createComponent(\`B\`, true, false, false, []);
return function template(ctx, node, key = \\"\\") {
let b2, b3;
b2 = text(\`A\`);
if (ctx['state'].value) {
b3 = comp1({}, key + \`__1\`, node, this, null);
}
return multi([b2, b3]);
}
}"
`;
exports[`app app: clear scheduler tasks and destroy cancelled nodes immediately on destroy 3`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(\`B\`);
}
}"
`;
exports[`app can configure an app with props 1`] = `
"function anonymous(app, bdom, helpers
) {
@@ -29,6 +57,19 @@ exports[`app can configure an app with props 1`] = `
}"
`;
exports[`app can load templates from an object name-string 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div class=\\"hello\\">hello</div>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
exports[`app can mount app in an iframe 1`] = `
"function anonymous(app, bdom, helpers
) {
+92 -2
View File
@@ -1,6 +1,15 @@
import { App, Component, mount, xml } from "../../src";
import { App, Component, mount, onWillStart, useState, xml } from "../../src";
import { status } from "../../src/runtime/status";
import { makeTestFixture, snapshotEverything, nextTick, elem } from "../helpers";
import {
makeTestFixture,
snapshotEverything,
nextTick,
elem,
useLogLifecycle,
makeDeferred,
nextMicroTick,
steps,
} from "../helpers";
let fixture: HTMLElement;
@@ -94,4 +103,85 @@ describe("app", () => {
expect(iframeDoc.contains(div)).toBe(false);
expect(status(comp)).toBe("destroyed");
});
test("app: clear scheduler tasks and destroy cancelled nodes immediately on destroy", async () => {
let def = makeDeferred();
class B extends Component {
static template = xml`B`;
setup() {
useLogLifecycle();
onWillStart(() => def);
}
}
class A extends Component {
static template = xml`A<t t-if="state.value"><B/></t>`;
static components = { B };
state = useState({ value: false });
setup() {
useLogLifecycle();
}
}
const app = new App(A);
const comp = await app.mount(fixture);
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"A:setup",
"A:willStart",
"A:willRender",
"A:rendered",
"A:mounted",
]
`);
comp.state.value = true;
await nextTick();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"A:willRender",
"B:setup",
"B:willStart",
"A:rendered",
]
`);
// rerender to force the instantiation of a new B component (and cancelling the first)
comp.render();
await nextMicroTick();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"A:willRender",
"B:setup",
"B:willStart",
"A:rendered",
]
`);
app.destroy();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"A:willUnmount",
"B:willDestroy",
"A:willDestroy",
"B:willDestroy",
]
`);
});
test("can load templates from an object name-string", async () => {
const templates = {
hello: `<div class="hello">hello</div>`,
world: `<div>world</div>`,
};
class SomeComponent extends Component {
static template = "hello";
}
const app = new App(SomeComponent, { templates });
await app.mount(fixture);
expect(fixture.querySelector(".hello")).toBeDefined();
// Only the "hello" template is used, so the "world" template is not yet loaded
expect(Object.keys(app.templates)).toEqual(["hello"]);
expect(Object.keys(app.rawTemplates)).toEqual(["hello", "world"]);
});
});
+4 -2
View File
@@ -244,12 +244,14 @@ describe("misc", () => {
});
test("namespace is not propagated to siblings", () => {
const block = createBlock(`<div><svg block-ns="someNameSpace"><g/></svg><div></div></div>`);
const block = createBlock(`<div><svg xmlns="someNameSpace"><g/></svg><div></div></div>`);
const fixture = makeTestFixture();
mount(block(), fixture);
expect(fixture.innerHTML).toBe("<div><svg><g></g></svg><div></div></div>");
expect(fixture.innerHTML).toBe(
'<div><svg xmlns="someNameSpace"><g></g></svg><div></div></div>'
);
expect(fixture.querySelector("svg")!.namespaceURI).toBe("someNameSpace");
expect(fixture.querySelector("g")!.namespaceURI).toBe("someNameSpace");
const allDivs = fixture.querySelectorAll("div");
+31
View File
@@ -145,3 +145,34 @@ test("class attribute (with a preexisting value", async () => {
patch(tree, block([""]));
expect(fixture.innerHTML).toBe(`<div class="tomato"></div>`);
});
test("block-class attributes with preexisting class attribute", async () => {
const block = createBlock('<div block-attributes="0" class="owl"></div>');
const tree = block([{ class: "eagle" }]);
mount(tree, fixture);
expect(fixture.innerHTML).toBe(`<div class="owl eagle"></div>`);
patch(tree, block([{ class: "falcon" }]));
expect(fixture.innerHTML).toBe(`<div class="owl falcon"></div>`);
patch(tree, block([{}]));
expect(fixture.innerHTML).toBe(`<div class="owl"></div>`);
});
test("block-class attributes (array syntax) with preexisting class attribute", async () => {
const block = createBlock('<div block-attributes="0" class="owl"></div>');
const tree = block([["class", "eagle"]]);
mount(tree, fixture);
expect(fixture.innerHTML).toBe(`<div class="owl eagle"></div>`);
patch(tree, block([["class", "falcon"]]));
expect(fixture.innerHTML).toBe(`<div class="owl falcon"></div>`);
patch(tree, block([["class", ""]]));
expect(fixture.innerHTML).toBe(`<div class="owl"></div>`);
patch(tree, block([["class", "buzzard"]]));
expect(fixture.innerHTML).toBe(`<div class="owl buzzard"></div>`);
});
+7 -7
View File
@@ -30,22 +30,22 @@ describe("namespace", () => {
expect(fixture.firstElementChild!.namespaceURI).toBe(XHTML_URI);
});
test("namespace can be changed with block-ns", () => {
const block = createBlock(`<tag block-ns="${SVG_URI}"/>`);
test("namespace can be changed with xmlns", () => {
const block = createBlock(`<tag xmlns="${SVG_URI}"/>`);
const tree = block();
mount(tree, fixture);
expect(fixture.innerHTML).toBe("<tag></tag>");
expect(fixture.innerHTML).toBe(`<tag xmlns="${SVG_URI}"></tag>`);
expect(fixture.firstElementChild!.namespaceURI).toBe(SVG_URI);
});
test("namespace is kept for children", () => {
const block = createBlock(
`<parent block-ns="${SVG_URI}"><child><subchild/></child><child/></parent>`
`<parent xmlns="${SVG_URI}"><child><subchild/></child><child/></parent>`
);
const tree = block();
mount(tree, fixture);
expect(fixture.innerHTML).toBe(
"<parent><child><subchild></subchild></child><child></child></parent>"
`<parent xmlns="${SVG_URI}"><child><subchild></subchild></child><child></child></parent>`
);
const parent = fixture.firstElementChild!;
const child1 = parent.firstElementChild!;
@@ -58,10 +58,10 @@ describe("namespace", () => {
});
test("various namespaces in same block", () => {
const block = createBlock(`<none><one block-ns="one"/><two block-ns="two"/></none>`);
const block = createBlock(`<none><one xmlns="one"/><two xmlns="two"/></none>`);
const tree = block();
mount(tree, fixture);
expect(fixture.innerHTML).toBe("<none><one></one><two></two></none>");
expect(fixture.innerHTML).toBe('<none><one xmlns="one"></one><two xmlns="two"></two></none>');
const none = fixture.firstElementChild!;
const one = none.firstElementChild!;
const two = one.nextElementSibling!;
@@ -707,6 +707,123 @@ exports[`attributes updating classes (with obj notation) 1`] = `
}"
`;
exports[`attributes various combinations of class, t-att-class, and t-att 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div block-attributes=\\"0\\" class=\\"c\\">content</div>\`);
return function template(ctx, node, key = \\"\\") {
let attr1 = {class:'a'};
return block1([attr1]);
}
}"
`;
exports[`attributes various combinations of class, t-att-class, and t-att 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div block-attributes=\\"0\\" block-attribute-1=\\"class\\" class=\\"c\\">content</div>\`);
return function template(ctx, node, key = \\"\\") {
let attr1 = {class:'a'};
let attr2 = {'b':true};
return block1([attr1, attr2]);
}
}"
`;
exports[`attributes various combinations of class, t-att-class, and t-att 3`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div block-attributes=\\"0\\" class=\\"c\\" block-attribute-1=\\"class\\">content</div>\`);
return function template(ctx, node, key = \\"\\") {
let attr1 = {class:'a'};
let attr2 = {'b':true};
return block1([attr1, attr2]);
}
}"
`;
exports[`attributes various combinations of class, t-att-class, and t-att 4`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div class=\\"c\\" block-attributes=\\"0\\" block-attribute-1=\\"class\\">content</div>\`);
return function template(ctx, node, key = \\"\\") {
let attr1 = {class:'a'};
let attr2 = {'b':true};
return block1([attr1, attr2]);
}
}"
`;
exports[`attributes various combinations of class, t-att-class, and t-att 5`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div class=\\"c\\" block-attribute-0=\\"class\\" block-attributes=\\"1\\">content</div>\`);
return function template(ctx, node, key = \\"\\") {
let attr1 = {'b':true};
let attr2 = {class:'a'};
return block1([attr1, attr2]);
}
}"
`;
exports[`attributes various combinations of class, t-att-class, and t-att 6`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div class=\\"c\\" block-attribute-0=\\"class\\">content</div>\`);
return function template(ctx, node, key = \\"\\") {
let attr1 = {'b':true};
return block1([attr1]);
}
}"
`;
exports[`attributes various combinations of class, t-att-class, and t-att 7`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div class=\\"c\\" block-attribute-0=\\"class\\">content</div>\`);
return function template(ctx, node, key = \\"\\") {
let attr1 = ('b');
return block1([attr1]);
}
}"
`;
exports[`attributes various combinations of class, t-att-class, and t-att 8`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div block-attributes=\\"0\\" block-attribute-1=\\"class\\">content</div>\`);
return function template(ctx, node, key = \\"\\") {
let attr1 = {class:'a'};
let attr2 = {'b':true};
return block1([attr1, attr2]);
}
}"
`;
exports[`attributes various escapes 1`] = `
"function anonymous(app, bdom, helpers
) {
@@ -34,7 +34,7 @@ exports[`comments properly handle comments between t-if/t-else 1`] = `
let block3 = createBlock(\`<span>owl</span>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (true) {
b2 = block2();
} else {
@@ -72,7 +72,7 @@ exports[`t-on can bind handlers with empty object (with non empty inner string)
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(['someval']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`action\`] = v_block2[i1];
ctx[\`action\`] = k_block2[i1];
ctx[\`action_index\`] = i1;
const key1 = ctx['action_index'];
const v1 = ctx['activate'];
@@ -142,7 +142,7 @@ exports[`t-on handler is bound to proper owner, part 2 1`] = `
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList([1]);;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`value\`] = v_block1[i1];
ctx[\`value\`] = k_block1[i1];
const key1 = ctx['value'];
let hdlr1 = [ctx['add'], ctx];
c_block1[i1] = withKey(block2([hdlr1]), key1);
@@ -189,11 +189,11 @@ exports[`t-on handler is bound to proper owner, part 4 1`] = `
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList([1]);;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`value\`] = v_block1[i1];
ctx[\`value\`] = k_block1[i1];
ctx[\`value_first\`] = i1 === 0;
ctx[\`value_last\`] = i1 === v_block1.length - 1;
ctx[\`value_last\`] = i1 === k_block1.length - 1;
ctx[\`value_index\`] = i1;
ctx[\`value_value\`] = k_block1[i1];
ctx[\`value_value\`] = v_block1[i1];
const key1 = ctx['value'];
c_block1[i1] = withKey(callTemplate_1.call(this, ctx, node, key + \`__1__\${key1}\`), key1);
}
@@ -348,7 +348,7 @@ exports[`t-on t-on modifiers (native listener) t-on with prevent modifier in t-f
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['projects']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`project\`] = v_block2[i1];
ctx[\`project\`] = k_block2[i1];
const key1 = ctx['project'];
const v1 = ctx['onEdit'];
const v2 = ctx['project'];
+21 -21
View File
@@ -18,7 +18,7 @@ exports[`misc complex template 1`] = `
let block13 = createBlock(\`<i class=\\"fa fa-fw fa-clock-o\\" title=\\"This commit is the head of a base branch\\"/>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3,b4,b6,b8;
let b2, b3, b4, b6, b8;
let attr1 = \`batch_tile \${ctx['options'].more?'more':'nomore'}\`;
let attr2 = \`card bg-\${ctx['klass']}-light\`;
let attr3 = \`/runbot/batch/\${ctx['batch'].id}\`;
@@ -33,7 +33,7 @@ exports[`misc complex template 1`] = `
ctx = Object.create(ctx);
const [k_block4, v_block4, l_block4, c_block4] = prepareList(ctx['batch'].slot_ids.filter(_slot=>_slot.build_id.id&&!_slot.trigger_id.manual&&(ctx['options'].trigger_display[_slot.trigger_id.id])));;
for (let i1 = 0; i1 < l_block4; i1++) {
ctx[\`slot\`] = v_block4[i1];
ctx[\`slot\`] = k_block4[i1];
const key1 = ctx['slot'].id;
c_block4[i1] = withKey(comp1({class: ctx['slot_container'],slot: ctx['slot']}, key + \`__1__\${key1}\`, node, this, null), key1);
}
@@ -42,7 +42,7 @@ exports[`misc complex template 1`] = `
ctx = Object.create(ctx);
const [k_block6, v_block6, l_block6, c_block6] = prepareList([1,2,3,4]);;
for (let i1 = 0; i1 < l_block6; i1++) {
ctx[\`x\`] = v_block6[i1];
ctx[\`x\`] = k_block6[i1];
const key1 = ctx['x'];
c_block6[i1] = withKey(block7(), key1);
}
@@ -51,9 +51,9 @@ exports[`misc complex template 1`] = `
ctx = Object.create(ctx);
const [k_block8, v_block8, l_block8, c_block8] = prepareList(ctx['commit_links']);;
for (let i1 = 0; i1 < l_block8; i1++) {
ctx[\`commit_link\`] = v_block8[i1];
ctx[\`commit_link\`] = k_block8[i1];
const key1 = ctx['commit_link'].id;
let b10,b11,b12,b13;
let b10, b11, b12, b13;
let attr5 = \`/runbot/commit/\${ctx['commit_link'].commit_id}\`;
let attr6 = \`badge badge-light batch_commit match_type_\${ctx['commit_link'].match_type}\`;
if (ctx['commit_link'].match_type=='new') {
@@ -99,11 +99,11 @@ exports[`misc global 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList([4,5,6]);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`value\`] = v_block2[i1];
ctx[\`value\`] = k_block2[i1];
ctx[\`value_first\`] = i1 === 0;
ctx[\`value_last\`] = i1 === v_block2.length - 1;
ctx[\`value_last\`] = i1 === k_block2.length - 1;
ctx[\`value_index\`] = i1;
ctx[\`value_value\`] = k_block2[i1];
ctx[\`value_value\`] = v_block2[i1];
const key1 = ctx['value'];
let txt1 = ctx['value'];
const b4 = block4([txt1]);
@@ -112,16 +112,16 @@ exports[`misc global 1`] = `
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
setContextValue(ctx, \\"foo\\", 'aaa');
const b6 = callTemplate_1.call(this, ctx, node, key + \`__1__\${key1}\`);
const b7 = callTemplate_1.call(this, ctx, node, key + \`__1__\${key1}\`);
ctx = ctx.__proto__;
const b7 = callTemplate_2.call(this, ctx, node, key + \`__2__\${key1}\`);
const b8 = callTemplate_2.call(this, ctx, node, key + \`__2__\${key1}\`);
setContextValue(ctx, \\"foo\\", 'bbb');
const b8 = callTemplate_3.call(this, ctx, node, key + \`__3__\${key1}\`);
const b5 = multi([b6, b7, b8]);
ctx[zero] = b5;
const b9 = callTemplate_4.call(this, ctx, node, key + \`__4__\${key1}\`);
const b9 = callTemplate_3.call(this, ctx, node, key + \`__3__\${key1}\`);
const b6 = multi([b7, b8, b9]);
ctx[zero] = b6;
const b5 = callTemplate_4.call(this, ctx, node, key + \`__4__\${key1}\`);
ctx = ctx.__proto__;
c_block2[i1] = withKey(multi([b4, b9]), key1);
c_block2[i1] = withKey(multi([b4, b5]), key1);
}
ctx = ctx.__proto__;
const b2 = list(c_block2);
@@ -217,13 +217,13 @@ exports[`misc other complex template 1`] = `
let block25 = createBlock(\`<div><block-child-0/><block-child-1/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b4,b14,b17,b22,b23,b24,b25;
let b2, b4, b14, b17, b22, b23, b24, b25;
let attr1 = \`/runbot/\${ctx['project'].slug}\`;
let txt1 = ctx['project'].name;
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['projects']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`project\`] = v_block2[i1];
ctx[\`project\`] = k_block2[i1];
const key1 = ctx['project'].id;
let hdlr1 = [ctx['selectProject'](ctx['project']), ctx];
let txt2 = ctx['project'].name;
@@ -232,12 +232,12 @@ exports[`misc other complex template 1`] = `
ctx = ctx.__proto__;
b2 = list(c_block2);
if (ctx['user']) {
let b5,b6;
let b5, b6;
if (ctx['user'].public) {
let attr2 = \`/web/login?redirect=/\`;
b5 = block5([attr2]);
} else {
let b7,b10,b13;
let b7, b10, b13;
if (ctx['nb_assigned_errors']&&ctx['nb_assigned_errors']>0) {
let attr3 = \`You have \${ctx['nb_assigned_errors']} random bug assigned\`;
let txt3 = ctx['nb_assigned_errors'];
@@ -263,7 +263,7 @@ exports[`misc other complex template 1`] = `
ctx = Object.create(ctx);
const [k_block15, v_block15, l_block15, c_block15] = prepareList(ctx['categories']);;
for (let i1 = 0; i1 < l_block15; i1++) {
ctx[\`category\`] = v_block15[i1];
ctx[\`category\`] = k_block15[i1];
const key1 = ctx['category'].id;
let attr6 = ctx['category'].id;
let prop1 = new Boolean(ctx['category'].id==ctx['options'].active_category_id);
@@ -284,7 +284,7 @@ exports[`misc other complex template 1`] = `
ctx = Object.create(ctx);
const [k_block18, v_block18, l_block18, c_block18] = prepareList(ctx['triggers']);;
for (let i1 = 0; i1 < l_block18; i1++) {
ctx[\`trigger\`] = v_block18[i1];
ctx[\`trigger\`] = k_block18[i1];
const key1 = ctx['trigger'].id;
let b20;
if (!ctx['trigger'].manual&&ctx['trigger'].project_id===ctx['project'].id&&ctx['trigger'].category_id===ctx['options'].active_category_id) {
@@ -12,7 +12,7 @@ exports[`memory t-foreach does not leak stuff in global scope 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList([3,2,1]);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`item\`] = v_block2[i1];
ctx[\`item\`] = k_block2[i1];
ctx[\`item_index\`] = i1;
const key1 = ctx['item_index'];
c_block2[i1] = withKey(text(ctx['item']), key1);
+11 -11
View File
@@ -5,7 +5,7 @@ exports[`properly support svg add proper namespace to g tags 1`] = `
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<g block-ns=\\"http://www.w3.org/2000/svg\\"><circle cx=\\"50\\" cy=\\"50\\" r=\\"4\\" stroke=\\"green\\" stroke-width=\\"1\\" fill=\\"yellow\\"/> </g>\`);
let block1 = createBlock(\`<g xmlns=\\"http://www.w3.org/2000/svg\\"><circle cx=\\"50\\" cy=\\"50\\" r=\\"4\\" stroke=\\"green\\" stroke-width=\\"1\\" fill=\\"yellow\\"/> </g>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
@@ -18,7 +18,7 @@ exports[`properly support svg add proper namespace to svg 1`] = `
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<svg block-ns=\\"http://www.w3.org/2000/svg\\" width=\\"100px\\" height=\\"90px\\"><circle cx=\\"50\\" cy=\\"50\\" r=\\"4\\" stroke=\\"green\\" stroke-width=\\"1\\" fill=\\"yellow\\"/> </svg>\`);
let block1 = createBlock(\`<svg xmlns=\\"http://www.w3.org/2000/svg\\" width=\\"100px\\" height=\\"90px\\"><circle cx=\\"50\\" cy=\\"50\\" r=\\"4\\" stroke=\\"green\\" stroke-width=\\"1\\" fill=\\"yellow\\"/> </svg>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
@@ -31,7 +31,7 @@ exports[`properly support svg namespace to g tags not added if already in svg na
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<svg block-ns=\\"http://www.w3.org/2000/svg\\"><g/></svg>\`);
let block1 = createBlock(\`<svg xmlns=\\"http://www.w3.org/2000/svg\\"><g/></svg>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
@@ -44,7 +44,7 @@ exports[`properly support svg namespace to svg tags added even if already in svg
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<svg block-ns=\\"http://www.w3.org/2000/svg\\"><svg/></svg>\`);
let block1 = createBlock(\`<svg xmlns=\\"http://www.w3.org/2000/svg\\"><svg/></svg>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
@@ -58,8 +58,8 @@ exports[`properly support svg svg creates new block if it is within html -- 2 1`
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div><block-child-0/></div>\`);
let block2 = createBlock(\`<svg block-ns=\\"http://www.w3.org/2000/svg\\"><polygon fill=\\"#000000\\" points=\\"0 0 4 4 8 0\\" transform=\\"translate(5 7)\\"/><block-child-0/></svg>\`);
let block3 = createBlock(\`<path block-ns=\\"http://www.w3.org/2000/svg\\"/>\`);
let block2 = createBlock(\`<svg xmlns=\\"http://www.w3.org/2000/svg\\"><polygon fill=\\"#000000\\" points=\\"0 0 4 4 8 0\\" transform=\\"translate(5 7)\\"/><block-child-0 xmlns=\\"\\"/></svg>\`);
let block3 = createBlock(\`<path xmlns=\\"http://www.w3.org/2000/svg\\"/>\`);
return function template(ctx, node, key = \\"\\") {
let b3;
@@ -78,7 +78,7 @@ exports[`properly support svg svg creates new block if it is within html 1`] = `
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div><block-child-0/></div>\`);
let block2 = createBlock(\`<svg block-ns=\\"http://www.w3.org/2000/svg\\"><polygon fill=\\"#000000\\" points=\\"0 0 4 4 8 0\\" transform=\\"translate(5 7)\\"/></svg>\`);
let block2 = createBlock(\`<svg xmlns=\\"http://www.w3.org/2000/svg\\"><polygon fill=\\"#000000\\" points=\\"0 0 4 4 8 0\\" transform=\\"translate(5 7)\\"/></svg>\`);
return function template(ctx, node, key = \\"\\") {
const b2 = block2();
@@ -93,7 +93,7 @@ exports[`properly support svg svg namespace added to sub templates if root tag i
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
const callTemplate_1 = app.getTemplate(\`path\`);
let block1 = createBlock(\`<svg block-ns=\\"http://www.w3.org/2000/svg\\"><block-child-0/></svg>\`);
let block1 = createBlock(\`<svg xmlns=\\"http://www.w3.org/2000/svg\\"><block-child-0 xmlns=\\"\\"/></svg>\`);
return function template(ctx, node, key = \\"\\") {
const b2 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
@@ -107,7 +107,7 @@ exports[`properly support svg svg namespace added to sub templates if root tag i
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<path block-ns=\\"http://www.w3.org/2000/svg\\"/>\`);
let block1 = createBlock(\`<path xmlns=\\"http://www.w3.org/2000/svg\\"/>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
@@ -120,8 +120,8 @@ exports[`properly support svg svg namespace added to sub-blocks 1`] = `
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<svg block-ns=\\"http://www.w3.org/2000/svg\\"><block-child-0/></svg>\`);
let block2 = createBlock(\`<path block-ns=\\"http://www.w3.org/2000/svg\\"/>\`);
let block1 = createBlock(\`<svg xmlns=\\"http://www.w3.org/2000/svg\\"><block-child-0 xmlns=\\"\\"/></svg>\`);
let block2 = createBlock(\`<path xmlns=\\"http://www.w3.org/2000/svg\\"/>\`);
return function template(ctx, node, key = \\"\\") {
let b2;
+203 -75
View File
@@ -61,19 +61,19 @@ exports[`t-call (template calling) call with several sub nodes on same line 1`]
const callTemplate_1 = app.getTemplate(\`sub\`);
let block1 = createBlock(\`<div><block-child-0/></div>\`);
let block3 = createBlock(\`<span>hey</span>\`);
let block5 = createBlock(\`<span>yay</span>\`);
let block4 = createBlock(\`<span>hey</span>\`);
let block6 = createBlock(\`<span>yay</span>\`);
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
const b3 = block3();
const b4 = text(\` \`);
const b5 = block5();
const b2 = multi([b3, b4, b5]);
ctx[zero] = b2;
const b6 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
return block1([], [b6]);
const b4 = block4();
const b5 = text(\` \`);
const b6 = block6();
const b3 = multi([b4, b5, b6]);
ctx[zero] = b3;
const b2 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
return block1([], [b2]);
}
}"
`;
@@ -101,19 +101,19 @@ exports[`t-call (template calling) cascading t-call t-out='0' 1`] = `
const callTemplate_1 = app.getTemplate(\`subTemplate\`);
let block1 = createBlock(\`<div><block-child-0/></div>\`);
let block3 = createBlock(\`<span>hey</span>\`);
let block5 = createBlock(\`<span>yay</span>\`);
let block4 = createBlock(\`<span>hey</span>\`);
let block6 = createBlock(\`<span>yay</span>\`);
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
const b3 = block3();
const b4 = text(\` \`);
const b5 = block5();
const b2 = multi([b3, b4, b5]);
ctx[zero] = b2;
const b6 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
return block1([], [b6]);
const b4 = block4();
const b5 = text(\` \`);
const b6 = block6();
const b3 = multi([b4, b5, b6]);
ctx[zero] = b3;
const b2 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
return block1([], [b2]);
}
}"
`;
@@ -126,17 +126,17 @@ exports[`t-call (template calling) cascading t-call t-out='0' 2`] = `
const callTemplate_1 = app.getTemplate(\`subSubTemplate\`);
let block1 = createBlock(\`<div><block-child-0/></div>\`);
let block3 = createBlock(\`<span>cascade 0</span>\`);
let block4 = createBlock(\`<span>cascade 0</span>\`);
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
const b3 = block3();
const b4 = ctx[zero];
const b2 = multi([b3, b4]);
ctx[zero] = b2;
const b5 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
return block1([], [b5]);
const b4 = block4();
const b5 = ctx[zero];
const b3 = multi([b4, b5]);
ctx[zero] = b3;
const b2 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
return block1([], [b2]);
}
}"
`;
@@ -149,17 +149,17 @@ exports[`t-call (template calling) cascading t-call t-out='0' 3`] = `
const callTemplate_1 = app.getTemplate(\`finalTemplate\`);
let block1 = createBlock(\`<div><block-child-0/></div>\`);
let block3 = createBlock(\`<span>cascade 1</span>\`);
let block4 = createBlock(\`<span>cascade 1</span>\`);
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
const b3 = block3();
const b4 = ctx[zero];
const b2 = multi([b3, b4]);
ctx[zero] = b2;
const b5 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
return block1([], [b5]);
const b4 = block4();
const b5 = ctx[zero];
const b3 = multi([b4, b5]);
ctx[zero] = b3;
const b2 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
return block1([], [b2]);
}
}"
`;
@@ -186,17 +186,17 @@ exports[`t-call (template calling) cascading t-call t-out='0', without external
let { isBoundary, zero } = helpers;
const callTemplate_1 = app.getTemplate(\`subTemplate\`);
let block2 = createBlock(\`<span>hey</span>\`);
let block4 = createBlock(\`<span>yay</span>\`);
let block3 = createBlock(\`<span>hey</span>\`);
let block5 = createBlock(\`<span>yay</span>\`);
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
const b2 = block2();
const b3 = text(\` \`);
const b4 = block4();
const b1 = multi([b2, b3, b4]);
ctx[zero] = b1;
const b3 = block3();
const b4 = text(\` \`);
const b5 = block5();
const b2 = multi([b3, b4, b5]);
ctx[zero] = b2;
return callTemplate_1.call(this, ctx, node, key + \`__1\`);
}
}"
@@ -209,15 +209,15 @@ exports[`t-call (template calling) cascading t-call t-out='0', without external
let { isBoundary, zero } = helpers;
const callTemplate_1 = app.getTemplate(\`subSubTemplate\`);
let block2 = createBlock(\`<span>cascade 0</span>\`);
let block3 = createBlock(\`<span>cascade 0</span>\`);
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
const b2 = block2();
const b3 = ctx[zero];
const b1 = multi([b2, b3]);
ctx[zero] = b1;
const b3 = block3();
const b4 = ctx[zero];
const b2 = multi([b3, b4]);
ctx[zero] = b2;
return callTemplate_1.call(this, ctx, node, key + \`__1\`);
}
}"
@@ -230,15 +230,15 @@ exports[`t-call (template calling) cascading t-call t-out='0', without external
let { isBoundary, zero } = helpers;
const callTemplate_1 = app.getTemplate(\`finalTemplate\`);
let block2 = createBlock(\`<span>cascade 1</span>\`);
let block3 = createBlock(\`<span>cascade 1</span>\`);
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
const b2 = block2();
const b3 = ctx[zero];
const b1 = multi([b2, b3]);
ctx[zero] = b1;
const b3 = block3();
const b4 = ctx[zero];
const b2 = multi([b3, b4]);
ctx[zero] = b2;
return callTemplate_1.call(this, ctx, node, key + \`__1\`);
}
}"
@@ -342,15 +342,15 @@ exports[`t-call (template calling) nested t-calls with magic variable 0 1`] = `
const callTemplate_1 = app.getTemplate(\`grandchild\`);
const callTemplate_2 = app.getTemplate(\`child\`);
let block1 = createBlock(\`<p>Some content...</p>\`);
let block3 = createBlock(\`<p>Some content...</p>\`);
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
const b1 = block1();
ctx[zero] = b1;
const b3 = block3();
ctx[zero] = b3;
const b2 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
ctx = ctx.__proto__;
ctx[zero] = b2;
@@ -440,11 +440,11 @@ exports[`t-call (template calling) recursive template, part 2 2`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['node'].children||[]);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`subtree\`] = v_block2[i1];
ctx[\`subtree\`] = k_block2[i1];
ctx[\`subtree_first\`] = i1 === 0;
ctx[\`subtree_last\`] = i1 === v_block2.length - 1;
ctx[\`subtree_last\`] = i1 === k_block2.length - 1;
ctx[\`subtree_index\`] = i1;
ctx[\`subtree_value\`] = k_block2[i1];
ctx[\`subtree_value\`] = v_block2[i1];
const key1 = ctx['subtree_index'];
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
@@ -495,11 +495,11 @@ exports[`t-call (template calling) recursive template, part 3 2`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['node'].children||[]);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`subtree\`] = v_block2[i1];
ctx[\`subtree\`] = k_block2[i1];
ctx[\`subtree_first\`] = i1 === 0;
ctx[\`subtree_last\`] = i1 === v_block2.length - 1;
ctx[\`subtree_last\`] = i1 === k_block2.length - 1;
ctx[\`subtree_index\`] = i1;
ctx[\`subtree_value\`] = k_block2[i1];
ctx[\`subtree_value\`] = v_block2[i1];
const key1 = ctx['subtree_index'];
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
@@ -553,11 +553,11 @@ exports[`t-call (template calling) recursive template, part 4: with t-set recurs
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['node'].children||[]);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`subtree\`] = v_block2[i1];
ctx[\`subtree\`] = k_block2[i1];
ctx[\`subtree_first\`] = i1 === 0;
ctx[\`subtree_last\`] = i1 === v_block2.length - 1;
ctx[\`subtree_last\`] = i1 === k_block2.length - 1;
ctx[\`subtree_index\`] = i1;
ctx[\`subtree_value\`] = k_block2[i1];
ctx[\`subtree_value\`] = v_block2[i1];
const key1 = ctx['subtree_index'];
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
@@ -571,6 +571,134 @@ exports[`t-call (template calling) recursive template, part 4: with t-set recurs
}"
`;
exports[`t-call (template calling) root t-call with body: t-foreach 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { isBoundary, prepareList, withKey, zero } = helpers;
const callTemplate_1 = app.getTemplate(\`subTemplate\`);
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList([1]);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`i\`] = k_block2[i1];
const key1 = ctx['i'];
c_block2[i1] = withKey(text(\`1\`), key1);
}
ctx = ctx.__proto__;
const b2 = list(c_block2);
ctx[zero] = b2;
return callTemplate_1.call(this, ctx, node, key + \`__1\`);
}
}"
`;
exports[`t-call (template calling) root t-call with body: t-foreach 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(\`sub\`);
}
}"
`;
exports[`t-call (template calling) root t-call with body: t-if false 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { isBoundary, zero } = helpers;
const callTemplate_1 = app.getTemplate(\`subTemplate\`);
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
let b3;
if (false) {
b3 = text(\`zero\`);
}
const b2 = multi([b3]);
ctx[zero] = b2;
return callTemplate_1.call(this, ctx, node, key + \`__1\`);
}
}"
`;
exports[`t-call (template calling) root t-call with body: t-if false 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(\`sub\`);
}
}"
`;
exports[`t-call (template calling) root t-call with body: t-if true 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { isBoundary, zero } = helpers;
const callTemplate_1 = app.getTemplate(\`subTemplate\`);
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
let b3;
if (true) {
b3 = text(\`zero\`);
}
const b2 = multi([b3]);
ctx[zero] = b2;
return callTemplate_1.call(this, ctx, node, key + \`__1\`);
}
}"
`;
exports[`t-call (template calling) root t-call with body: t-if true 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(\`sub\`);
}
}"
`;
exports[`t-call (template calling) root t-call with body: t-out with default 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { isBoundary, safeOutput, zero } = helpers;
const callTemplate_1 = app.getTemplate(\`subTemplate\`);
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
const b2 = safeOutput(ctx['nothing']);
ctx[zero] = b2;
return callTemplate_1.call(this, ctx, node, key + \`__1\`);
}
}"
`;
exports[`t-call (template calling) root t-call with body: t-out with default 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(\`sub\`);
}
}"
`;
exports[`t-call (template calling) scoped parameters 1`] = `
"function anonymous(app, bdom, helpers
) {
@@ -705,13 +833,13 @@ exports[`t-call (template calling) t-call with body content as root of a templat
let { isBoundary, zero } = helpers;
const callTemplate_1 = app.getTemplate(\`antony\`);
let block1 = createBlock(\`<p>antony</p>\`);
let block2 = createBlock(\`<p>antony</p>\`);
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
const b1 = block1();
ctx[zero] = b1;
const b2 = block2();
ctx[zero] = b2;
return callTemplate_1.call(this, ctx, node, key + \`__1\`);
}
}"
@@ -813,11 +941,11 @@ exports[`t-call (template calling) t-call with t-set inside and outside 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['list']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`v\`] = v_block2[i1];
ctx[\`v\`] = k_block2[i1];
ctx[\`v_first\`] = i1 === 0;
ctx[\`v_last\`] = i1 === v_block2.length - 1;
ctx[\`v_last\`] = i1 === k_block2.length - 1;
ctx[\`v_index\`] = i1;
ctx[\`v_value\`] = k_block2[i1];
ctx[\`v_value\`] = v_block2[i1];
const key1 = ctx['v_index'];
setContextValue(ctx, \\"val\\", ctx['v'].val);
ctx = Object.create(ctx);
@@ -880,11 +1008,11 @@ exports[`t-call (template calling) t-call with t-set inside and outside. 2 2`] =
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['list']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`v\`] = v_block2[i1];
ctx[\`v\`] = k_block2[i1];
ctx[\`v_first\`] = i1 === 0;
ctx[\`v_last\`] = i1 === v_block2.length - 1;
ctx[\`v_last\`] = i1 === k_block2.length - 1;
ctx[\`v_index\`] = i1;
ctx[\`v_value\`] = k_block2[i1];
ctx[\`v_value\`] = v_block2[i1];
const key1 = ctx['v_index'];
setContextValue(ctx, \\"val\\", ctx['v'].val);
ctx = Object.create(ctx);
@@ -928,7 +1056,7 @@ exports[`t-call (template calling) t-call, conditional and t-set in t-call body
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1
let b2,b3;
let b2, b3;
setContextValue(ctx, \\"v1\\", 'elif');
if (ctx['v1']==='if') {
b2 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
@@ -1075,8 +1203,8 @@ exports[`t-call (template calling) with unused body 1`] = `
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
const b1 = text(\`WHEEE\`);
ctx[zero] = b1;
const b2 = text(\`WHEEE\`);
ctx[zero] = b2;
return callTemplate_1.call(this, ctx, node, key + \`__1\`);
}
}"
@@ -1136,8 +1264,8 @@ exports[`t-call (template calling) with used body 1`] = `
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
const b1 = text(\`ok\`);
ctx[zero] = b1;
const b2 = text(\`ok\`);
ctx[zero] = b2;
return callTemplate_1.call(this, ctx, node, key + \`__1\`);
}
}"
@@ -180,15 +180,15 @@ exports[`t-esc t-esc=0 is escaped 1`] = `
const callTemplate_1 = app.getTemplate(\`sub\`);
let block1 = createBlock(\`<div><block-child-0/></div>\`);
let block2 = createBlock(\`<p>escaped</p>\`);
let block3 = createBlock(\`<p>escaped</p>\`);
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
const b2 = block2();
ctx[zero] = b2;
const b3 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
return block1([], [b3]);
const b3 = block3();
ctx[zero] = b3;
const b2 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
return block1([], [b2]);
}
}"
`;
@@ -12,7 +12,7 @@ exports[`t-foreach does not pollute the rendering context 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList([1]);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`item\`] = v_block2[i1];
ctx[\`item\`] = k_block2[i1];
const key1 = ctx['item'];
c_block2[i1] = withKey(text(ctx['item']), key1);
}
@@ -35,7 +35,7 @@ exports[`t-foreach iterate on items (on a element node) 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList([1,2]);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`item\`] = v_block2[i1];
ctx[\`item\`] = k_block2[i1];
const key1 = ctx['item'];
let txt1 = ctx['item'];
c_block2[i1] = withKey(block3([txt1]), key1);
@@ -58,9 +58,9 @@ exports[`t-foreach iterate on items 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList([3,2,1]);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`item\`] = v_block2[i1];
ctx[\`item\`] = k_block2[i1];
ctx[\`item_index\`] = i1;
ctx[\`item_value\`] = k_block2[i1];
ctx[\`item_value\`] = v_block2[i1];
const key1 = ctx['item'];
const b4 = text(\` [\`);
const b5 = text(ctx['item_index']);
@@ -77,6 +77,62 @@ exports[`t-foreach iterate on items 1`] = `
}"
`;
exports[`t-foreach iterate, Map param 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { prepareList, withKey } = helpers;
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList(ctx['value']);;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`item\`] = k_block1[i1];
ctx[\`item_index\`] = i1;
ctx[\`item_value\`] = v_block1[i1];
const key1 = ctx['item_index'];
const b3 = text(\` [\`);
const b4 = text(ctx['item_index']);
const b5 = text(\`: \`);
const b6 = text(ctx['item']);
const b7 = text(\` \`);
const b8 = text(ctx['item_value']);
const b9 = text(\`] \`);
c_block1[i1] = withKey(multi([b3, b4, b5, b6, b7, b8, b9]), key1);
}
return list(c_block1);
}
}"
`;
exports[`t-foreach iterate, Set param 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { prepareList, withKey } = helpers;
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList(ctx['value']);;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`item\`] = k_block1[i1];
ctx[\`item_index\`] = i1;
ctx[\`item_value\`] = v_block1[i1];
const key1 = ctx['item_index'];
const b3 = text(\` [\`);
const b4 = text(ctx['item_index']);
const b5 = text(\`: \`);
const b6 = text(ctx['item']);
const b7 = text(\` \`);
const b8 = text(ctx['item_value']);
const b9 = text(\`] \`);
c_block1[i1] = withKey(multi([b3, b4, b5, b6, b7, b8, b9]), key1);
}
return list(c_block1);
}
}"
`;
exports[`t-foreach iterate, dict param 1`] = `
"function anonymous(app, bdom, helpers
) {
@@ -89,9 +145,9 @@ exports[`t-foreach iterate, dict param 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['value']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`item\`] = v_block2[i1];
ctx[\`item\`] = k_block2[i1];
ctx[\`item_index\`] = i1;
ctx[\`item_value\`] = k_block2[i1];
ctx[\`item_value\`] = v_block2[i1];
const key1 = ctx['item_index'];
const b4 = text(\` [\`);
const b5 = text(ctx['item_index']);
@@ -108,6 +164,62 @@ exports[`t-foreach iterate, dict param 1`] = `
}"
`;
exports[`t-foreach iterate, generator param 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { prepareList, withKey } = helpers;
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList(ctx['gen']());;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`item\`] = k_block1[i1];
ctx[\`item_index\`] = i1;
ctx[\`item_value\`] = v_block1[i1];
const key1 = ctx['item_index'];
const b3 = text(\` [\`);
const b4 = text(ctx['item_index']);
const b5 = text(\`: \`);
const b6 = text(ctx['item']);
const b7 = text(\` \`);
const b8 = text(ctx['item_value']);
const b9 = text(\`] \`);
c_block1[i1] = withKey(multi([b3, b4, b5, b6, b7, b8, b9]), key1);
}
return list(c_block1);
}
}"
`;
exports[`t-foreach iterate, iterable param 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { prepareList, withKey } = helpers;
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList(ctx['map'].values());;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`item\`] = k_block1[i1];
ctx[\`item_index\`] = i1;
ctx[\`item_value\`] = v_block1[i1];
const key1 = ctx['item_index'];
const b3 = text(\` [\`);
const b4 = text(ctx['item_index']);
const b5 = text(\`: \`);
const b6 = text(ctx['item']);
const b7 = text(\` \`);
const b8 = text(ctx['item_value']);
const b9 = text(\`] \`);
c_block1[i1] = withKey(multi([b3, b4, b5, b6, b7, b8, b9]), key1);
}
return list(c_block1);
}
}"
`;
exports[`t-foreach iterate, position 1`] = `
"function anonymous(app, bdom, helpers
) {
@@ -120,12 +232,12 @@ exports[`t-foreach iterate, position 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(Array(5));;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`elem\`] = v_block2[i1];
ctx[\`elem\`] = k_block2[i1];
ctx[\`elem_first\`] = i1 === 0;
ctx[\`elem_last\`] = i1 === v_block2.length - 1;
ctx[\`elem_last\`] = i1 === k_block2.length - 1;
ctx[\`elem_index\`] = i1;
const key1 = ctx['elem'];
let b4,b5,b6,b7,b8,b9;
let b4, b5, b6, b7, b8, b9;
b4 = text(\` -\`);
if (ctx['elem_first']) {
b5 = text(\` first\`);
@@ -144,6 +256,34 @@ exports[`t-foreach iterate, position 1`] = `
}"
`;
exports[`t-foreach iterate, string param 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { prepareList, withKey } = helpers;
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList('abc');;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`item\`] = k_block1[i1];
ctx[\`item_index\`] = i1;
ctx[\`item_value\`] = v_block1[i1];
const key1 = ctx['item_index'];
const b3 = text(\` [\`);
const b4 = text(ctx['item_index']);
const b5 = text(\`: \`);
const b6 = text(ctx['item']);
const b7 = text(\` \`);
const b8 = text(ctx['item_value']);
const b9 = text(\`] \`);
c_block1[i1] = withKey(multi([b3, b4, b5, b6, b7, b8, b9]), key1);
}
return list(c_block1);
}
}"
`;
exports[`t-foreach simple iteration (in a node) 1`] = `
"function anonymous(app, bdom, helpers
) {
@@ -156,7 +296,7 @@ exports[`t-foreach simple iteration (in a node) 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList([3,2,1]);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`item\`] = v_block2[i1];
ctx[\`item\`] = k_block2[i1];
const key1 = ctx['item'];
c_block2[i1] = withKey(text(ctx['item']), key1);
}
@@ -176,7 +316,7 @@ exports[`t-foreach simple iteration 1`] = `
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList([3,2,1]);;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`item\`] = v_block1[i1];
ctx[\`item\`] = k_block1[i1];
const key1 = ctx['item'];
c_block1[i1] = withKey(text(ctx['item']), key1);
}
@@ -198,7 +338,7 @@ exports[`t-foreach simple iteration with two nodes inside 1`] = `
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList([3,2,1]);;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`item\`] = v_block1[i1];
ctx[\`item\`] = k_block1[i1];
const key1 = ctx['item'];
let txt1 = ctx['item'];
const b3 = block3([txt1]);
@@ -227,20 +367,20 @@ exports[`t-foreach t-call with body in t-foreach in t-foreach 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['numbers']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`a\`] = v_block2[i1];
ctx[\`a\`] = k_block2[i1];
ctx[\`a_first\`] = i1 === 0;
ctx[\`a_last\`] = i1 === v_block2.length - 1;
ctx[\`a_last\`] = i1 === k_block2.length - 1;
ctx[\`a_index\`] = i1;
ctx[\`a_value\`] = k_block2[i1];
ctx[\`a_value\`] = v_block2[i1];
const key1 = ctx['a'];
ctx = Object.create(ctx);
const [k_block4, v_block4, l_block4, c_block4] = prepareList(ctx['letters']);;
for (let i2 = 0; i2 < l_block4; i2++) {
ctx[\`b\`] = v_block4[i2];
ctx[\`b\`] = k_block4[i2];
ctx[\`b_first\`] = i2 === 0;
ctx[\`b_last\`] = i2 === v_block4.length - 1;
ctx[\`b_last\`] = i2 === k_block4.length - 1;
ctx[\`b_index\`] = i2;
ctx[\`b_value\`] = k_block4[i2];
ctx[\`b_value\`] = v_block4[i2];
const key2 = ctx['b'];
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
@@ -296,20 +436,20 @@ exports[`t-foreach t-call without body in t-foreach in t-foreach 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['numbers']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`a\`] = v_block2[i1];
ctx[\`a\`] = k_block2[i1];
ctx[\`a_first\`] = i1 === 0;
ctx[\`a_last\`] = i1 === v_block2.length - 1;
ctx[\`a_last\`] = i1 === k_block2.length - 1;
ctx[\`a_index\`] = i1;
ctx[\`a_value\`] = k_block2[i1];
ctx[\`a_value\`] = v_block2[i1];
const key1 = ctx['a'];
ctx = Object.create(ctx);
const [k_block4, v_block4, l_block4, c_block4] = prepareList(ctx['letters']);;
for (let i2 = 0; i2 < l_block4; i2++) {
ctx[\`b\`] = v_block4[i2];
ctx[\`b\`] = k_block4[i2];
ctx[\`b_first\`] = i2 === 0;
ctx[\`b_last\`] = i2 === v_block4.length - 1;
ctx[\`b_last\`] = i2 === k_block4.length - 1;
ctx[\`b_index\`] = i2;
ctx[\`b_value\`] = k_block4[i2];
ctx[\`b_value\`] = v_block4[i2];
const key2 = ctx['b'];
c_block4[i2] = withKey(callTemplate_1.call(this, ctx, node, key + \`__1__\${key1}__\${key2}\`), key2);
}
@@ -363,12 +503,12 @@ exports[`t-foreach t-foreach in t-foreach 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['numbers']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`number\`] = v_block2[i1];
ctx[\`number\`] = k_block2[i1];
const key1 = ctx['number'];
ctx = Object.create(ctx);
const [k_block3, v_block3, l_block3, c_block3] = prepareList(ctx['letters']);;
for (let i2 = 0; i2 < l_block3; i2++) {
ctx[\`letter\`] = v_block3[i2];
ctx[\`letter\`] = k_block3[i2];
const key2 = ctx['letter'];
const b5 = text(\` [\`);
const b6 = text(ctx['number']);
@@ -397,7 +537,7 @@ exports[`t-foreach t-foreach with t-if inside (no external node) 1`] = `
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList(ctx['elems']);;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`elem\`] = v_block1[i1];
ctx[\`elem\`] = k_block1[i1];
const key1 = ctx['elem'].id;
let b3;
if (ctx['elem'].id<3) {
@@ -424,7 +564,7 @@ exports[`t-foreach t-foreach with t-if inside 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['elems']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`elem\`] = v_block2[i1];
ctx[\`elem\`] = k_block2[i1];
const key1 = ctx['elem'].id;
let b4;
if (ctx['elem'].id<3) {
@@ -452,7 +592,7 @@ exports[`t-foreach t-key on t-foreach 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['things']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`thing\`] = v_block2[i1];
ctx[\`thing\`] = k_block2[i1];
const key1 = ctx['thing'];
c_block2[i1] = withKey(block3(), key1);
}
@@ -475,7 +615,7 @@ exports[`t-foreach throws error if invalid loop expression 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['abc']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`item\`] = v_block2[i1];
ctx[\`item\`] = k_block2[i1];
ctx[\`item_index\`] = i1;
const key1 = ctx['item'];
const tKey_1 = ctx['item_index'];
@@ -502,7 +642,7 @@ exports[`t-foreach with t-memo 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['items']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`item\`] = v_block2[i1];
ctx[\`item\`] = k_block2[i1];
const key1 = ctx['item'].id;
const memo1 = [ctx['item'].x];
const vnode1 = cache[key1];;
+16 -16
View File
@@ -8,7 +8,7 @@ exports[`t-if a t-if next to a div 1`] = `
let block2 = createBlock(\`<div>foo</div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
b2 = block2();
if (ctx['cond']) {
b3 = text(\`1\`);
@@ -44,7 +44,7 @@ exports[`t-if boolean value condition elif (no outside node) 1`] = `
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
let b2,b3,b4,b5;
let b2, b3, b4, b5;
if (ctx['color']=='black') {
b2 = text(\`black pearl\`);
} else if (ctx['color']=='yellow') {
@@ -67,7 +67,7 @@ exports[`t-if boolean value condition elif 1`] = `
let block1 = createBlock(\`<div><block-child-0/><block-child-1/><block-child-2/><block-child-3/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3,b4,b5;
let b2, b3, b4, b5;
if (ctx['color']=='black') {
b2 = text(\`black pearl\`);
} else if (ctx['color']=='yellow') {
@@ -90,7 +90,7 @@ exports[`t-if boolean value condition else 1`] = `
let block1 = createBlock(\`<div><span>begin</span><block-child-0/><block-child-1/><span>end</span></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['condition']) {
b2 = text(\`ok\`);
} else {
@@ -109,7 +109,7 @@ exports[`t-if boolean value condition false else 1`] = `
let block1 = createBlock(\`<div><span>begin</span><block-child-0/><block-child-1/><span>end</span></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['condition']) {
b2 = text(\`fail\`);
} else {
@@ -145,7 +145,7 @@ exports[`t-if can use some boolean operators in expressions 1`] = `
let block1 = createBlock(\`<div><block-child-0/><block-child-1/><block-child-2/><block-child-3/><block-child-4/><block-child-5/><block-child-6/><block-child-7/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3,b4,b5,b6,b7,b8,b9;
let b2, b3, b4, b5, b6, b7, b8, b9;
if (ctx['cond1']&&ctx['cond2']) {
b2 = text(\`and\`);
}
@@ -239,7 +239,7 @@ exports[`t-if simple t-if/t-else 1`] = `
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['condition']) {
b2 = text(\`1\`);
} else {
@@ -258,7 +258,7 @@ exports[`t-if simple t-if/t-else in a div 1`] = `
let block1 = createBlock(\`<div><block-child-0/><block-child-1/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['condition']) {
b2 = text(\`1\`);
} else {
@@ -277,7 +277,7 @@ exports[`t-if t-esc with t-elif 1`] = `
let block1 = createBlock(\`<div><block-child-0/><block-child-1/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (false) {
b2 = text(\`abc\`);
} else {
@@ -314,7 +314,7 @@ exports[`t-if t-if and t-else with two nodes 1`] = `
let block5 = createBlock(\`<span>b</span>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['condition']) {
b2 = text(\`1\`);
} else {
@@ -372,7 +372,7 @@ exports[`t-if t-if with empty content 1`] = `
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
b2 = text(\`hello\`);
if (ctx['condition']) {
b3 = text(\`\`);
@@ -388,7 +388,7 @@ exports[`t-if t-if/t-else with more content 1`] = `
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['condition']) {
if (ctx['condition']) {
b2 = text(\`asf\`);
@@ -458,7 +458,7 @@ exports[`t-if t-set, then t-if, part 3 1`] = `
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1
let b2,b3;
let b2, b3;
setContextValue(ctx, \\"y\\", false);
setContextValue(ctx, \\"x\\", ctx['y']);
if (ctx['x']) {
@@ -477,7 +477,7 @@ exports[`t-if two consecutive t-if 1`] = `
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['cond1']) {
b2 = text(\`1\`);
}
@@ -497,7 +497,7 @@ exports[`t-if two consecutive t-if in a div 1`] = `
let block1 = createBlock(\`<div><block-child-0/><block-child-1/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['cond1']) {
b2 = text(\`1\`);
}
@@ -520,7 +520,7 @@ exports[`t-if two t-ifs next to each other 1`] = `
let block5 = createBlock(\`<p>2</p>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['condition']) {
let txt1 = ctx['text'];
b2 = block2([txt1]);
@@ -58,7 +58,7 @@ exports[`t-key t-key directive in a list 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['beers']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`beer\`] = v_block2[i1];
ctx[\`beer\`] = k_block2[i1];
const key1 = ctx['beer'].id;
let txt1 = ctx['beer'].name;
c_block2[i1] = withKey(block3([txt1]), key1);
@@ -79,7 +79,7 @@ exports[`t-key t-key on sub dom node pushes a child block in its parent 1`] = `
let block3 = createBlock(\`<div><h1/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['hasSpan']) {
b2 = block2();
}
+11 -11
View File
@@ -35,15 +35,15 @@ exports[`t-out multiple calls to t-out 1`] = `
const callTemplate_1 = app.getTemplate(\`sub\`);
let block1 = createBlock(\`<div><block-child-0/></div>\`);
let block2 = createBlock(\`<span>coucou</span>\`);
let block3 = createBlock(\`<span>coucou</span>\`);
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
const b2 = block2();
ctx[zero] = b2;
const b3 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
return block1([], [b3]);
const b3 = block3();
ctx[zero] = b3;
const b2 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
return block1([], [b2]);
}
}"
`;
@@ -102,15 +102,15 @@ exports[`t-out t-out 0 1`] = `
const callTemplate_1 = app.getTemplate(\`_basic-callee\`);
let block1 = createBlock(\`<div><block-child-0/></div>\`);
let block2 = createBlock(\`<div>zero</div>\`);
let block3 = createBlock(\`<div>zero</div>\`);
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
const b2 = block2();
ctx[zero] = b2;
const b3 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
return block1([], [b3]);
const b3 = block3();
ctx[zero] = b3;
const b2 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
return block1([], [b2]);
}
}"
`;
@@ -309,7 +309,7 @@ exports[`t-out t-out switch markup on bdom 1`] = `
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1
let b3,b5;
let b3, b5;
ctx[\`bdom\`] = new LazyValue(value1, ctx, this, node, key);
if (ctx['hasBdom']) {
const b4 = safeOutput(ctx['bdom']);
@@ -105,7 +105,7 @@ exports[`t-ref refs in a loop 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['items']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`item\`] = v_block2[i1];
ctx[\`item\`] = k_block2[i1];
const key1 = ctx['item'];
const tKey_1 = ctx['item'];
const v1 = ctx['item'];
@@ -94,7 +94,7 @@ exports[`t-set set from body literal (with t-if/t-else 1`] = `
let { isBoundary, withDefault, LazyValue } = helpers;
function value1(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['condition']) {
b2 = text(\`true\`);
} else {
@@ -351,7 +351,7 @@ exports[`t-set t-set outside modified in t-foreach 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(['a','b']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`val\`] = v_block2[i1];
ctx[\`val\`] = k_block2[i1];
const key1 = ctx['val'];
let txt1 = ctx['iter'];
c_block2[i1] = withKey(block3([txt1]), key1);
@@ -381,7 +381,7 @@ exports[`t-set t-set outside modified in t-foreach increment-after operator 1`]
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(['a','b']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`val\`] = v_block2[i1];
ctx[\`val\`] = k_block2[i1];
const key1 = ctx['val'];
let txt1 = ctx['iter'];
c_block2[i1] = withKey(block3([txt1]), key1);
@@ -411,7 +411,7 @@ exports[`t-set t-set outside modified in t-foreach increment-before operator 1`]
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(['a','b']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`val\`] = v_block2[i1];
ctx[\`val\`] = k_block2[i1];
const key1 = ctx['val'];
let txt1 = ctx['iter'];
c_block2[i1] = withKey(block3([txt1]), key1);
@@ -441,7 +441,7 @@ exports[`t-set t-set should reuse variable if possible 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['list']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`elem\`] = v_block2[i1];
ctx[\`elem\`] = k_block2[i1];
ctx[\`elem_index\`] = i1;
const key1 = ctx['elem_index'];
let txt1 = ctx['v'];
@@ -1,5 +1,79 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`translation support body of t-sets are translated 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { isBoundary, withDefault, setContextValue } = helpers;
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1
setContextValue(ctx, \\"label\\", \`translated\`);
return text(ctx['label']);
}
}"
`;
exports[`translation support body of t-sets inside translation=off are not translated 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { isBoundary, withDefault, setContextValue } = helpers;
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1
setContextValue(ctx, \\"label\\", \`untranslated\`);
return text(ctx['label']);
}
}"
`;
exports[`translation support body of t-sets with html content are translated 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { isBoundary, withDefault, LazyValue, safeOutput } = helpers;
let block1 = createBlock(\`<div>translated</div>\`);
function value1(ctx, node, key = \\"\\") {
return block1();
}
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1
ctx[\`label\`] = new LazyValue(value1, ctx, this, node, key);
return safeOutput(ctx['label']);
}
}"
`;
exports[`translation support body of t-sets with text and html content are translated 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { isBoundary, withDefault, LazyValue, safeOutput } = helpers;
let block3 = createBlock(\`<div>translated</div>\`);
function value1(ctx, node, key = \\"\\") {
const b2 = text(\` translated \`);
const b3 = block3();
return multi([b2, b3]);
}
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1
ctx[\`label\`] = new LazyValue(value1, ctx, this, node, key);
return safeOutput(ctx['label']);
}
}"
`;
exports[`translation support can set and remove translatable attributes 1`] = `
"function anonymous(app, bdom, helpers
) {
@@ -52,6 +126,21 @@ exports[`translation support some attributes are translated 1`] = `
}"
`;
exports[`translation support t-set and falsy t-value: t-body are translated 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { isBoundary, withDefault, setContextValue } = helpers;
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1
setContextValue(ctx, \\"label\\", withDefault(false, \`translated\`));
return text(ctx['label']);
}
}"
`;
exports[`translation support translation is done on the trimmed text, with extra spaces readded after 1`] = `
"function anonymous(app, bdom, helpers
) {
+29
View File
@@ -371,4 +371,33 @@ describe("attributes", () => {
// not sure about this. maybe we want to remove the attribute?
expect(fixture.innerHTML).toBe('<div class="hoy a b"></div>');
});
test("various combinations of class, t-att-class, and t-att", () => {
const template1 = `<div t-att="{ class: 'a' }" class="c">content</div>`;
expect(renderToString(template1)).toBe('<div class="c a">content</div>');
const template2 = `<div t-att="{ class: 'a' }" t-att-class="{'b': true}" class="c">content</div>`;
expect(renderToString(template2)).toBe('<div class="c a b">content</div>');
const template3 = `<div t-att="{ class: 'a' }" class="c" t-att-class="{'b': true}">content</div>`;
expect(renderToString(template3)).toBe('<div class="c a b">content</div>');
const template4 = `<div class="c" t-att="{ class: 'a' }" t-att-class="{'b': true}">content</div>`;
expect(renderToString(template4)).toBe('<div class="c a b">content</div>');
const template5 = `<div class="c" t-att-class="{'b': true}" t-att="{ class: 'a' }">content</div>`;
expect(renderToString(template5)).toBe('<div class="c b a">content</div>');
const template6 = `<div class="c" t-att-class="{'b': true}">content</div>`;
expect(renderToString(template6)).toBe('<div class="c b">content</div>');
const template7 = `<div class="c" t-attf-class="{{'b'}}">content</div>`;
expect(renderToString(template7)).toBe('<div class="c b">content</div>');
const template8 = `<div t-att="{ class: 'a' }" class="c" t-att-class="{'b': true}">content</div>`;
expect(renderToString(template8)).toBe('<div class="c a b">content</div>');
const template9 = `<div t-att="{ class: 'a' }" t-att-class="{'b': true}">content</div>`;
expect(renderToString(template9)).toBe('<div class="a b">content</div>');
});
});
+32 -2
View File
@@ -1147,6 +1147,24 @@ describe("qweb parser", () => {
});
});
test("t-onclick without dash", async () => {
expect(() => parse(`<button t-onclick="add">Click</button>`)).toThrowError(
"Unknown QWeb directive: 't-onclick'"
);
});
test("t-on without event", async () => {
expect(() => parse(`<button t-on="add">Click</button>`)).toThrowError(
"Missing event name with t-on directive"
);
});
test("t-on- without event", async () => {
expect(() => parse(`<button t-on-="add">Click</button>`)).toThrowError(
"Missing event name with t-on directive"
);
});
// ---------------------------------------------------------------------------
// t-model
// ---------------------------------------------------------------------------
@@ -1275,6 +1293,12 @@ describe("qweb parser", () => {
});
});
test("component with event handler", async () => {
expect(() => parse(`<MyComponent t-onclick="someMethod"/>`)).toThrowError(
"unsupported directive on Component: t-onclick"
);
});
test("component with t-ref", async () => {
expect(() => parse(`<MyComponent t-ref="something"/>`)).toThrow(
"t-ref is no longer supported on components. Consider exposing only the public part of the component's API through a callback prop."
@@ -1545,6 +1569,12 @@ describe("qweb parser", () => {
);
});
test("component with t-out", async () => {
expect(parse(`<MyComponent t-out="someValue"/>`)).toEqual(
parse(`<MyComponent><t t-out="someValue"/></MyComponent>`)
);
});
test("component with t-esc and content", async () => {
expect(() => parse(`<MyComponent t-esc="someValue">Some content</MyComponent>`)).toThrow(
"Cannot have t-esc on a component that already has content"
@@ -1967,8 +1997,8 @@ describe("qweb parser", () => {
baseExpr: "state",
expr: "'stuff'",
eventType: "click",
shouldNumberize: false,
shouldTrim: false,
shouldNumberize: true,
shouldTrim: true,
targetAttr: "value",
hasDynamicChildren: false,
specialInitTargetAttr: "checked",
+10 -5
View File
@@ -9,20 +9,20 @@ describe("properly support svg", () => {
test("add proper namespace to svg", () => {
const template = `<svg width="100px" height="90px"><circle cx="50" cy="50" r="4" stroke="green" stroke-width="1" fill="yellow"/> </svg>`;
expect(renderToString(template)).toBe(
`<svg width=\"100px\" height=\"90px\"><circle cx=\"50\" cy=\"50\" r=\"4\" stroke=\"green\" stroke-width=\"1\" fill=\"yellow\"></circle> </svg>`
`<svg xmlns="http://www.w3.org/2000/svg" width="100px" height="90px"><circle cx="50" cy="50" r="4" stroke="green" stroke-width="1" fill="yellow"></circle> </svg>`
);
});
test("add proper namespace to g tags", () => {
const template = `<g><circle cx="50" cy="50" r="4" stroke="green" stroke-width="1" fill="yellow"/> </g>`;
expect(renderToString(template)).toBe(
`<g><circle cx=\"50\" cy=\"50\" r=\"4\" stroke=\"green\" stroke-width=\"1\" fill=\"yellow\"></circle> </g>`
`<g xmlns="http://www.w3.org/2000/svg"><circle cx="50" cy="50" r="4" stroke="green" stroke-width="1" fill="yellow"></circle> </g>`
);
});
test("namespace to g tags not added if already in svg namespace", () => {
const template = `<svg><g/></svg>`;
expect(renderToString(template)).toBe(`<svg><g></g></svg>`);
expect(renderToString(template)).toBe(`<svg xmlns="http://www.w3.org/2000/svg"><g></g></svg>`);
});
test("namespace to svg tags added even if already in svg namespace", () => {
@@ -41,8 +41,13 @@ describe("properly support svg", () => {
test("svg namespace added to sub-blocks", () => {
const template = `<svg><path t-if="path"/></svg>`;
expect(renderToString(template, { path: false })).toBe(`<svg></svg>`);
expect(renderToString(template, { path: true })).toBe(`<svg><path></path></svg>`);
expect(renderToString(template, { path: false })).toBe(
`<svg xmlns="http://www.w3.org/2000/svg"></svg>`
);
// Because the path is its own block, it has its own xmlns attribute
expect(renderToString(template, { path: true })).toBe(
`<svg xmlns="http://www.w3.org/2000/svg"><path xmlns="http://www.w3.org/2000/svg"></path></svg>`
);
const bdom = renderToBdom(template, { path: true });
const fixture = makeTestFixture();
+42
View File
@@ -430,6 +430,48 @@ describe("t-call (template calling)", () => {
expect(context.renderToString("main")).toBe(expected);
});
test("root t-call with body: t-if true", () => {
const context = new TestContext();
const subTemplate = `sub`;
const main = `<t t-call="subTemplate"><t t-if="true">zero</t></t>`;
context.addTemplate("subTemplate", subTemplate);
context.addTemplate("main", main);
const expected = "sub";
expect(context.renderToString("main")).toBe(expected);
});
test("root t-call with body: t-if false", () => {
const context = new TestContext();
const subTemplate = `sub`;
const main = `<t t-call="subTemplate"><t t-if="false">zero</t></t>`;
context.addTemplate("subTemplate", subTemplate);
context.addTemplate("main", main);
const expected = "sub";
expect(context.renderToString("main")).toBe(expected);
});
test("root t-call with body: t-out with default", () => {
const context = new TestContext();
const subTemplate = `sub`;
const main = `<t t-call="subTemplate"><t t-out="nothing">default</t></t>`;
context.addTemplate("subTemplate", subTemplate);
context.addTemplate("main", main);
const expected = "sub";
expect(context.renderToString("main")).toBe(expected);
});
test("root t-call with body: t-foreach", () => {
const context = new TestContext();
const subTemplate = `sub`;
const main = `<t t-call="subTemplate">
<t t-foreach="[1]" t-as="i" t-key="i">1</t>
</t>`;
context.addTemplate("subTemplate", subTemplate);
context.addTemplate("main", main);
const expected = "sub";
expect(context.renderToString("main")).toBe(expected);
});
test("dynamic t-call", () => {
const context = new TestContext();
const foo = `<foo><t t-esc="val"/></foo>`;
+70 -1
View File
@@ -105,6 +105,73 @@ describe("t-foreach", () => {
expect(renderToString(template, context)).toBe(expected);
});
test("iterate, Map param", () => {
const template = `
<t t-foreach="value" t-as="item" t-key="item_index">
[<t t-esc="item_index"/>: <t t-esc="item"/> <t t-esc="item_value"/>]
</t>`;
const expected = ` [0: a 1] [1: b 2] [2: c 3] `;
const context = {
value: new Map([
["a", 1],
["b", 2],
["c", 3],
]),
};
expect(renderToString(template, context)).toBe(expected);
});
test("iterate, Set param", () => {
const template = `
<t t-foreach="value" t-as="item" t-key="item_index">
[<t t-esc="item_index"/>: <t t-esc="item"/> <t t-esc="item_value"/>]
</t>`;
const expected = ` [0: 1 1] [1: 2 2] [2: 3 3] `;
const context = { value: new Set([1, 2, 3]) };
expect(renderToString(template, context)).toBe(expected);
});
test("iterate, string param", () => {
const template = `
<t t-foreach="'abc'" t-as="item" t-key="item_index">
[<t t-esc="item_index"/>: <t t-esc="item"/> <t t-esc="item_value"/>]
</t>`;
const expected = ` [0: a a] [1: b b] [2: c c] `;
expect(renderToString(template)).toBe(expected);
});
test("iterate, iterable param", () => {
const template = `
<t t-foreach="map.values()" t-as="item" t-key="item_index">
[<t t-esc="item_index"/>: <t t-esc="item"/> <t t-esc="item_value"/>]
</t>`;
const expected = ` [0: 1 1] [1: 2 2] [2: 3 3] `;
const context = {
map: new Map([
["a", 1],
["b", 2],
["c", 3],
]),
};
expect(renderToString(template, context)).toBe(expected);
});
test("iterate, generator param", () => {
const template = `
<t t-foreach="gen()" t-as="item" t-key="item_index">
[<t t-esc="item_index"/>: <t t-esc="item"/> <t t-esc="item_value"/>]
</t>`;
const expected = ` [0: 1 1] [1: 2 2] [2: 3 3] `;
const context = {
*gen() {
yield 1;
yield 2;
yield 3;
},
};
expect(renderToString(template, context)).toBe(expected);
});
test("does not pollute the rendering context", () => {
const template = `
<div>
@@ -193,7 +260,9 @@ describe("t-foreach", () => {
test("throws error if invalid loop expression", () => {
const test = `<div><t t-foreach="abc" t-as="item" t-key="item"><span t-key="item_index"/></t></div>`;
expect(() => renderToString(test)).toThrow("Invalid loop expression");
expect(() => renderToString(test)).toThrow(
'Invalid loop expression: "undefined" is not iterable'
);
});
test("t-foreach with t-if inside", () => {
+70
View File
@@ -100,4 +100,74 @@ describe("translation support", () => {
expect(translateFn).toHaveBeenCalledWith("some word");
expect(fixture.innerHTML).toBe("<div>un mot</div>");
});
test("body of t-sets are translated", async () => {
class SomeComponent extends Component {
static template = xml`
<t t-set="label">untranslated</t>
<t t-esc="label"/>`;
}
const translateFn = () => "translated";
await mount(SomeComponent, fixture, { translateFn });
expect(fixture.innerHTML).toBe("translated");
});
test("body of t-sets inside translation=off are not translated", async () => {
class SomeComponent extends Component {
static template = xml`
<t t-translation="off">
<t t-set="label">untranslated</t>
<t t-esc="label"/>
</t>`;
}
const translateFn = () => "translated";
await mount(SomeComponent, fixture, { translateFn });
expect(fixture.innerHTML).toBe("untranslated");
});
test("body of t-sets with html content are translated", async () => {
class SomeComponent extends Component {
static template = xml`
<t t-set="label"><div>untranslated</div></t>
<t t-out="label"/>`;
}
const translateFn = () => "translated";
await mount(SomeComponent, fixture, { translateFn });
expect(fixture.innerHTML).toBe("<div>translated</div>");
});
test("body of t-sets with text and html content are translated", async () => {
class SomeComponent extends Component {
static template = xml`
<t t-set="label">
some text
<div>untranslated</div>
</t>
<t t-out="label"/>`;
}
const translateFn = () => "translated";
await mount(SomeComponent, fixture, { translateFn });
expect(fixture.innerHTML).toBe(" translated <div>translated</div>");
});
test("t-set and falsy t-value: t-body are translated", async () => {
class SomeComponent extends Component {
static template = xml`
<t t-set="label" t-value="false">untranslated</t>
<t t-esc="label"/>`;
}
const translateFn = () => "translated";
await mount(SomeComponent, fixture, { translateFn });
expect(fixture.innerHTML).toBe("translated");
});
});
+27 -2
View File
@@ -11,8 +11,8 @@ describe("basic validation", () => {
expect(() => context.getTemplate("invalidname")).toThrow("Missing template");
});
test("cannot add a different template with the same name", () => {
const context = new TemplateSet();
test("cannot add a different template with the same name in dev mode", () => {
const context = new TemplateSet({ dev: true });
context.addTemplate("test", `<t/>`);
// Same template with the same name is fine
expect(() => context.addTemplate("test", "<t/>")).not.toThrow();
@@ -20,6 +20,13 @@ describe("basic validation", () => {
expect(() => context.addTemplate("test", "<div/>")).toThrow("already defined");
});
test("adding different template with same name outside dev mode silently ignores it", () => {
const context = new TemplateSet({ dev: false });
context.addTemplate("test", `<t/>`);
expect(() => context.addTemplate("test", "<div/>")).not.toThrow();
expect(context.rawTemplates.test).toBe("<t/>");
});
test("invalid xml", () => {
const template = "<div>";
expect(() => snapshotTemplate(template)).toThrow("Invalid XML in template");
@@ -37,4 +44,22 @@ describe("basic validation", () => {
const template = `<div t-best-beer="rochefort 10">test</div>`;
expect(() => renderToString(template)).toThrow("Unknown QWeb directive: 't-best-beer'");
});
test("compilation error", () => {
const template = `<div t-att-class="a b">test</div>`;
expect(() => renderToString(template))
.toThrow(`Failed to compile anonymous template: Unexpected identifier
generated code:
function(app, bdom, helpers) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div block-attribute-0="class">test</div>\`);
return function template(ctx, node, key = "") {
let attr1 = ctx['a']ctx['b'];
return block1([attr1]);
}
}`);
});
});
@@ -440,7 +440,7 @@ exports[`basics higher order components parent and child 2`] = `
const comp2 = app.createComponent(\`ChildB\`, true, false, false, []);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['props'].child==='a') {
b2 = comp1({}, key + \`__1\`, node, this, null);
} else {
@@ -492,7 +492,7 @@ exports[`basics list of two sub components inside other nodes 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['state'].blips);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`blip\`] = v_block2[i1];
ctx[\`blip\`] = k_block2[i1];
const key1 = ctx['blip'].id;
const b4 = comp1({}, key + \`__1__\${key1}\`, node, this, null);
const b5 = comp2({}, key + \`__2__\${key1}\`, node, this, null);
@@ -738,7 +738,7 @@ exports[`basics sub components between t-ifs 1`] = `
let block5 = createBlock(\`<span>test</span>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3,b4,b5;
let b2, b3, b4, b5;
if (ctx['state'].flag) {
b2 = block2();
} else {
@@ -776,7 +776,7 @@ exports[`basics t-elif works with t-component 1`] = `
let block2 = createBlock(\`<div>somediv</div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['state'].flag) {
b2 = block2();
} else if (!ctx['state'].flag) {
@@ -810,7 +810,7 @@ exports[`basics t-else with empty string works with t-component 1`] = `
let block2 = createBlock(\`<div>somediv</div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['state'].flag) {
b2 = block2();
} else {
@@ -844,7 +844,7 @@ exports[`basics t-else works with t-component 1`] = `
let block2 = createBlock(\`<div>somediv</div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['state'].flag) {
b2 = block2();
} else {
@@ -909,7 +909,7 @@ exports[`basics t-key on a component with t-if, and a sibling component 1`] = `
let block1 = createBlock(\`<div><block-child-0/><block-child-0/><block-child-1/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (false) {
const tKey_1 = 'str';
b2 = toggler(tKey_1, comp1({}, tKey_1 + key + \`__1\`, node, this, null));
@@ -1084,7 +1084,7 @@ exports[`basics updating a component with t-foreach as root 1`] = `
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList(ctx['items']);;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`item\`] = v_block1[i1];
ctx[\`item\`] = k_block1[i1];
const key1 = ctx['item'];
c_block1[i1] = withKey(text(ctx['item']), key1);
}
@@ -1135,7 +1135,7 @@ exports[`basics widget after a t-foreach 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(Array(2));;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`elem\`] = v_block2[i1];
ctx[\`elem\`] = k_block2[i1];
ctx[\`elem_index\`] = i1;
const key1 = ctx['elem_index'];
c_block2[i1] = withKey(text(\`txt\`), key1);
@@ -1248,7 +1248,7 @@ exports[`support svg components add proper namespace to svg 1`] = `
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
const comp1 = app.createComponent(\`GComp\`, true, false, false, []);
let block1 = createBlock(\`<svg block-ns=\\"http://www.w3.org/2000/svg\\"><block-child-0/></svg>\`);
let block1 = createBlock(\`<svg xmlns=\\"http://www.w3.org/2000/svg\\"><block-child-0 xmlns=\\"\\"/></svg>\`);
return function template(ctx, node, key = \\"\\") {
const b2 = comp1({}, key + \`__1\`, node, this, null);
@@ -1262,7 +1262,7 @@ exports[`support svg components add proper namespace to svg 2`] = `
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<g block-ns=\\"http://www.w3.org/2000/svg\\"><circle cx=\\"50\\" cy=\\"50\\" r=\\"4\\" stroke=\\"green\\" stroke-width=\\"1\\" fill=\\"yellow\\"/></g>\`);
let block1 = createBlock(\`<g xmlns=\\"http://www.w3.org/2000/svg\\"><circle cx=\\"50\\" cy=\\"50\\" r=\\"4\\" stroke=\\"green\\" stroke-width=\\"1\\" fill=\\"yellow\\"/></g>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
@@ -1282,7 +1282,7 @@ exports[`t-out in components can render list of t-out 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['state'].items);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`item\`] = v_block2[i1];
ctx[\`item\`] = k_block2[i1];
const key1 = ctx['item'];
const b4 = text(ctx['item']);
const b5 = safeOutput(ctx['item']);
@@ -13,7 +13,7 @@ exports[`Cascading renders after microtaskTick 1`] = `
ctx = Object.create(ctx);
const [k_block4, v_block4, l_block4, c_block4] = prepareList(ctx['state']);;
for (let i1 = 0; i1 < l_block4; i1++) {
ctx[\`elem\`] = v_block4[i1];
ctx[\`elem\`] = k_block4[i1];
const key1 = ctx['elem'].id;
c_block4[i1] = withKey(text(ctx['elem'].id), key1);
}
@@ -34,7 +34,7 @@ exports[`Cascading renders after microtaskTick 2`] = `
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList(ctx['state']);;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`elem\`] = v_block1[i1];
ctx[\`elem\`] = k_block1[i1];
const key1 = ctx['elem'].id;
c_block1[i1] = withKey(comp1({id: ctx['elem'].id}, key + \`__1__\${key1}\`, node, this, null), key1);
}
@@ -61,7 +61,7 @@ exports[`another scenario with delayed rendering 1`] = `
const comp1 = app.createComponent(\`B\`, true, false, false, [\\"value\\"]);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
b2 = text(\`A\`);
if (ctx['state'].value<15) {
b3 = comp1({value: ctx['state'].value}, key + \`__1\`, node, this, null);
@@ -184,7 +184,7 @@ exports[`changing state before first render does not trigger a render (with pare
}"
`;
exports[`changing state before first render does not trigger a render (with parent) 2`] = `
exports[`changing state before first render does not trigger a render (with parent) 3`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
@@ -212,6 +212,73 @@ exports[`changing state before first render does not trigger a render 1`] = `
}"
`;
exports[`component destroyed just after render 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
const comp1 = app.createComponent(\`B\`, true, false, false, []);
return function template(ctx, node, key = \\"\\") {
return comp1({}, key + \`__1\`, node, this, null);
}
}"
`;
exports[`component destroyed just after render 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
const b2 = text(\`B\`);
const b3 = text(ctx['state'].value);
return multi([b2, b3]);
}
}"
`;
exports[`components are not destroyed between animation frame 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
const comp1 = app.createComponent(\`B\`, true, false, false, []);
return function template(ctx, node, key = \\"\\") {
let b2, b3;
b2 = text(\`A\`);
if (ctx['state'].flag) {
b3 = comp1({}, key + \`__1\`, node, this, null);
}
return multi([b2, b3]);
}
}"
`;
exports[`components are not destroyed between animation frame 3`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
const comp1 = app.createComponent(\`C\`, true, false, false, []);
return function template(ctx, node, key = \\"\\") {
const b2 = text(\`B\`);
const b3 = comp1({}, key + \`__1\`, node, this, null);
return multi([b2, b3]);
}
}"
`;
exports[`components are not destroyed between animation frame 5`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(\`C\`);
}
}"
`;
exports[`concurrent renderings scenario 1 1`] = `
"function anonymous(app, bdom, helpers
) {
@@ -681,7 +748,7 @@ exports[`concurrent renderings scenario 10 2`] = `
}"
`;
exports[`concurrent renderings scenario 10 3`] = `
exports[`concurrent renderings scenario 10 4`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
@@ -764,7 +831,7 @@ exports[`concurrent renderings scenario 13 1`] = `
let block1 = createBlock(\`<div><block-child-0/><block-child-1/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
b2 = comp1({}, key + \`__1\`, node, this, null);
if (ctx['state'].bool) {
b3 = comp2({}, key + \`__2\`, node, this, null);
@@ -911,7 +978,7 @@ exports[`concurrent renderings scenario 16 3`] = `
const comp1 = app.createComponent(\`D\`, true, false, false, []);
return function template(ctx, node, key = \\"\\") {
let b2,b3,b4,b5,b6,b7,b8;
let b2, b3, b4, b5, b6, b7, b8;
b2 = text(ctx['props'].fromA);
b3 = text(\`:\`);
b4 = text(ctx['props'].fromB);
@@ -926,7 +993,7 @@ exports[`concurrent renderings scenario 16 3`] = `
}"
`;
exports[`concurrent renderings scenario 16 4`] = `
exports[`concurrent renderings scenario 16 6`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
@@ -945,7 +1012,7 @@ exports[`creating two async components, scenario 1 1`] = `
const comp2 = app.createComponent(\`ChildB\`, true, false, false, []);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['state'].flagA) {
b2 = comp1({}, key + \`__1\`, node, this, null);
}
@@ -957,7 +1024,7 @@ exports[`creating two async components, scenario 1 1`] = `
}"
`;
exports[`creating two async components, scenario 1 2`] = `
exports[`creating two async components, scenario 1 3`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
@@ -971,7 +1038,7 @@ exports[`creating two async components, scenario 1 2`] = `
}"
`;
exports[`creating two async components, scenario 1 3`] = `
exports[`creating two async components, scenario 1 5`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
@@ -994,7 +1061,7 @@ exports[`creating two async components, scenario 2 1`] = `
let block1 = createBlock(\`<div><block-child-0/><block-child-1/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
b2 = comp1({val: ctx['state'].valA}, key + \`__1\`, node, this, null);
if (ctx['state'].flagB) {
b3 = comp2({val: ctx['state'].valB}, key + \`__2\`, node, this, null);
@@ -1018,7 +1085,7 @@ exports[`creating two async components, scenario 2 2`] = `
}"
`;
exports[`creating two async components, scenario 2 3`] = `
exports[`creating two async components, scenario 2 5`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
@@ -1042,7 +1109,7 @@ exports[`creating two async components, scenario 3 (patching in the same frame)
let block1 = createBlock(\`<div><block-child-0/><block-child-1/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
b2 = comp1({val: ctx['state'].valA}, key + \`__1\`, node, this, null);
if (ctx['state'].flagB) {
b3 = comp2({val: ctx['state'].valB}, key + \`__2\`, node, this, null);
@@ -1066,7 +1133,7 @@ exports[`creating two async components, scenario 3 (patching in the same frame)
}"
`;
exports[`creating two async components, scenario 3 (patching in the same frame) 3`] = `
exports[`creating two async components, scenario 3 (patching in the same frame) 5`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
@@ -1241,7 +1308,7 @@ exports[`delayed render does not go through when t-component value changed 2`] =
}"
`;
exports[`delayed render does not go through when t-component value changed 3`] = `
exports[`delayed render does not go through when t-component value changed 4`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
@@ -1354,7 +1421,7 @@ exports[`delayed rendering, destruction, stuff happens 2`] = `
const comp1 = app.createComponent(\`C\`, true, false, false, [\\"value\\"]);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
b2 = text(\`B\`);
if (ctx['state'].hasChild) {
b3 = comp1({value: ctx['state'].someValue+ctx['props'].value}, key + \`__1\`, node, this, null);
@@ -1447,7 +1514,7 @@ exports[`delayed rendering, reusing fiber then component is destroyed and stuff
const comp1 = app.createComponent(\`B\`, true, false, false, [\\"value\\"]);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
b2 = text(\`A\`);
if (ctx['state'].value<15) {
b3 = comp1({value: ctx['state'].value}, key + \`__1\`, node, this, null);
@@ -1505,7 +1572,7 @@ exports[`delayed rendering, then component is destroyed and stuff 2`] = `
const comp1 = app.createComponent(\`C\`, true, false, false, []);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
b2 = text(ctx['props'].value);
if (ctx['props'].value<10) {
b3 = comp1({}, key + \`__1\`, node, this, null);
@@ -1538,7 +1605,7 @@ exports[`destroyed component causes other soon to be destroyed component to rere
const comp2 = app.createComponent(\`C\`, true, false, false, [\\"value\\"]);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
b2 = text(\` A \`);
if (ctx['state'].flag) {
const b4 = comp1({value: ctx['state'].valueB}, key + \`__1\`, node, this, null);
@@ -1550,7 +1617,7 @@ exports[`destroyed component causes other soon to be destroyed component to rere
}"
`;
exports[`destroyed component causes other soon to be destroyed component to rerender, weird stuff happens 2`] = `
exports[`destroyed component causes other soon to be destroyed component to rerender, weird stuff happens 3`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
@@ -1561,7 +1628,7 @@ exports[`destroyed component causes other soon to be destroyed component to rere
}"
`;
exports[`destroyed component causes other soon to be destroyed component to rerender, weird stuff happens 3`] = `
exports[`destroyed component causes other soon to be destroyed component to rerender, weird stuff happens 4`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
@@ -1579,7 +1646,7 @@ exports[`destroying/recreating a subcomponent, other scenario 1`] = `
const comp1 = app.createComponent(\`Child\`, true, false, false, []);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
b2 = text(\`parent\`);
if (ctx['state'].hasChild) {
b3 = comp1({}, key + \`__1\`, node, this, null);
@@ -1589,7 +1656,7 @@ exports[`destroying/recreating a subcomponent, other scenario 1`] = `
}"
`;
exports[`destroying/recreating a subcomponent, other scenario 2`] = `
exports[`destroying/recreating a subcomponent, other scenario 3`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
@@ -1618,7 +1685,7 @@ exports[`destroying/recreating a subwidget with different props (if start is not
}"
`;
exports[`destroying/recreating a subwidget with different props (if start is not over) 2`] = `
exports[`destroying/recreating a subwidget with different props (if start is not over) 3`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
@@ -1720,7 +1787,7 @@ exports[`rendering component again in next microtick 1`] = `
}"
`;
exports[`rendering component again in next microtick 2`] = `
exports[`rendering component again in next microtick 3`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
@@ -1779,7 +1846,7 @@ exports[`renderings, destruction, patch, stuff, ... yet another variation 2`] =
const comp1 = app.createComponent(\`C\`, true, false, false, []);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
b2 = text(\`B\`);
if (ctx['props'].value===33) {
b3 = comp1({}, key + \`__1\`, node, this, null);
@@ -1834,7 +1901,7 @@ exports[`t-foreach with dynamic async component 1`] = `
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList(ctx['list']);;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`arr\`] = v_block1[i1];
ctx[\`arr\`] = k_block1[i1];
ctx[\`arr_index\`] = i1;
const key1 = ctx['arr_index'];
let b3;
@@ -12,6 +12,18 @@ exports[`basics display a nice error if a component is not a component 1`] = `
}"
`;
exports[`basics display a nice error if a non-root component template fails to compile 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
const comp1 = app.createComponent(\`Child\`, true, false, false, []);
return function template(ctx, node, key = \\"\\") {
return comp1({}, key + \`__1\`, node, this, null);
}
}"
`;
exports[`basics display a nice error if it cannot find component (in dev mode) 1`] = `
"function anonymous(app, bdom, helpers
) {
@@ -91,7 +103,7 @@ exports[`basics simple catchError 1`] = `
let block1 = createBlock(\`<div><block-child-0/><block-child-1/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['error']) {
b2 = text(\`Error\`);
} else {
@@ -189,7 +201,7 @@ exports[`can catch errors an error in onWillDestroy 1`] = `
const comp1 = app.createComponent(\`Child\`, true, false, false, []);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
b2 = text(ctx['state'].value);
if (ctx['state'].hasChild) {
b3 = comp1({}, key + \`__1\`, node, this, null);
@@ -219,7 +231,7 @@ exports[`can catch errors an error in onWillDestroy, variation 1`] = `
const comp1 = app.createComponent(\`Child\`, true, false, false, []);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
b2 = text(ctx['state'].value);
if (ctx['state'].hasChild) {
b3 = comp1({}, key + \`__1\`, node, this, null);
@@ -229,7 +241,7 @@ exports[`can catch errors an error in onWillDestroy, variation 1`] = `
}"
`;
exports[`can catch errors an error in onWillDestroy, variation 2`] = `
exports[`can catch errors an error in onWillDestroy, variation 3`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
@@ -283,7 +295,7 @@ exports[`can catch errors can catch an error in a component render function 2`]
let block1 = createBlock(\`<div><block-child-0/><block-child-1/><block-child-1/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['state'].error) {
b2 = text(\`Error handled\`);
} else {
@@ -338,7 +350,7 @@ exports[`can catch errors can catch an error in the constructor call of a compon
let block1 = createBlock(\`<div><block-child-0/><block-child-1/><block-child-1/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['state'].error) {
b2 = text(\`Error handled\`);
} else {
@@ -382,7 +394,7 @@ exports[`can catch errors can catch an error in the constructor call of a compon
let block1 = createBlock(\`<div><block-child-0/><block-child-1/><block-child-1/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['state'].error) {
b2 = text(\`Error handled\`);
} else {
@@ -462,7 +474,7 @@ exports[`can catch errors can catch an error in the initial call of a component
let block1 = createBlock(\`<div><block-child-0/><block-child-1/><block-child-1/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['state'].error) {
b2 = text(\`Error handled\`);
} else {
@@ -520,7 +532,7 @@ exports[`can catch errors can catch an error in the initial call of a component
let block1 = createBlock(\`<div><block-child-0/><block-child-1/><block-child-1/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['state'].error) {
b2 = text(\`Error handled\`);
} else {
@@ -581,7 +593,7 @@ exports[`can catch errors can catch an error in the mounted call (in child of ch
let block1 = createBlock(\`<div><block-child-0/><block-child-1/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['state'].error) {
b2 = text(\`Error handled\`);
} else {
@@ -614,7 +626,7 @@ exports[`can catch errors can catch an error in the mounted call (in root compon
let block1 = createBlock(\`<div><block-child-0/><block-child-1/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['state'].error) {
b2 = text(\`Error handled\`);
} else {
@@ -668,7 +680,7 @@ exports[`can catch errors can catch an error in the mounted call 2`] = `
let block1 = createBlock(\`<div><block-child-0/><block-child-1/><block-child-1/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['state'].error) {
b2 = text(\`Error handled\`);
} else {
@@ -723,7 +735,7 @@ exports[`can catch errors can catch an error in the willPatch call 2`] = `
let block1 = createBlock(\`<div><block-child-0/><block-child-1/><block-child-1/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['state'].error) {
b2 = text(\`Error handled\`);
} else {
@@ -778,7 +790,7 @@ exports[`can catch errors can catch an error in the willStart call 2`] = `
let block1 = createBlock(\`<div><block-child-0/><block-child-1/><block-child-1/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['state'].error) {
b2 = text(\`Error handled\`);
} else {
@@ -835,7 +847,7 @@ exports[`can catch errors can catch an error origination from a child's willStar
let block1 = createBlock(\`<div><block-child-0/><block-child-1/><block-child-1/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['state'].error) {
b2 = text(\`Error handled\`);
} else {
@@ -881,7 +893,7 @@ exports[`can catch errors catchError in catchError 1`] = `
let block1 = createBlock(\`<div><block-child-0/><block-child-1/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['error']) {
b2 = text(\`Error\`);
} else {
@@ -938,7 +950,7 @@ exports[`can catch errors catching error, rethrow, render parent -- a main comp
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList(Object.values(ctx['state'].cps));;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`cp\`] = v_block1[i1];
ctx[\`cp\`] = k_block1[i1];
const key1 = ctx['cp'].id;
const v1 = ctx['this'];
const v2 = ctx['cp'];
@@ -1017,7 +1029,7 @@ exports[`can catch errors catching in child makes parent render 1`] = `
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList(Object.entries(ctx['this'].elements));;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`elem\`] = v_block1[i1];
ctx[\`elem\`] = k_block1[i1];
const key1 = ctx['elem'][0];
const v1 = ctx['this'];
const v2 = ctx['elem'];
@@ -1111,7 +1123,7 @@ exports[`can catch errors error in mounted on a component with a sibling (proper
let block1 = createBlock(\`<div><block-child-0/><block-child-1/><block-child-1/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['state'].error) {
b2 = text(\`Error handled\`);
} else {
@@ -1155,7 +1167,7 @@ exports[`can catch errors onError in class inheritance is called if rethrown 2`]
let block1 = createBlock(\`<div><block-child-0/><block-child-1/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (!ctx['state'].error) {
b2 = text(ctx['this'].will.crash);
} else {
@@ -1186,7 +1198,7 @@ exports[`can catch errors onError in class inheritance is not called if no rethr
let block1 = createBlock(\`<div><block-child-0/><block-child-1/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (!ctx['state'].error) {
b2 = text(ctx['this'].will.crash);
} else {
@@ -117,7 +117,7 @@ exports[`event handling objects from scope are properly captured by t-on 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['items']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`item\`] = v_block2[i1];
ctx[\`item\`] = k_block2[i1];
const key1 = ctx['item'];
const v1 = ctx['onClick'];
const v2 = ctx['item'];
@@ -158,7 +158,7 @@ exports[`event handling t-on with handler bound to dynamic argument on a t-forea
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['items']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`item\`] = v_block2[i1];
ctx[\`item\`] = k_block2[i1];
const key1 = ctx['item'];
const v1 = ctx['onClick'];
const v2 = ctx['item'];
@@ -34,7 +34,7 @@ exports[`basics can select a sub widget 1`] = `
const comp2 = app.createComponent(\`OtherChild\`, true, false, false, []);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['env'].options.flag) {
b2 = comp1({}, key + \`__1\`, node, this, null);
}
@@ -80,7 +80,7 @@ exports[`basics can select a sub widget, part 2 1`] = `
const comp2 = app.createComponent(\`OtherChild\`, true, false, false, []);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['state'].flag) {
b2 = comp1({}, key + \`__1\`, node, this, null);
}
@@ -54,7 +54,7 @@ exports[`lifecycle hooks component semantics 3`] = `
let block1 = createBlock(\`<div>C<block-child-0/><block-child-1/><block-child-2/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3,b4;
let b2, b3, b4;
b2 = comp1({}, key + \`__1\`, node, this, null);
if (ctx['state'].flag) {
b3 = comp2({}, key + \`__2\`, node, this, null);
@@ -92,7 +92,7 @@ exports[`lifecycle hooks component semantics 5`] = `
}"
`;
exports[`lifecycle hooks component semantics 6`] = `
exports[`lifecycle hooks component semantics 7`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
@@ -174,7 +174,7 @@ exports[`lifecycle hooks destroy new children before being mountged 1`] = `
const comp1 = app.createComponent(\`Child\`, true, false, false, []);
return function template(ctx, node, key = \\"\\") {
let b2,b3,b4;
let b2, b3, b4;
b2 = text(\`before\`);
if (ctx['state'].flag) {
b3 = comp1({}, key + \`__1\`, node, this, null);
@@ -185,7 +185,7 @@ exports[`lifecycle hooks destroy new children before being mountged 1`] = `
}"
`;
exports[`lifecycle hooks destroy new children before being mountged 2`] = `
exports[`lifecycle hooks destroy new children before being mountged 3`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
@@ -291,7 +291,7 @@ exports[`lifecycle hooks lifecycle semantics, part 2 1`] = `
}"
`;
exports[`lifecycle hooks lifecycle semantics, part 2 2`] = `
exports[`lifecycle hooks lifecycle semantics, part 2 3`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
@@ -303,7 +303,7 @@ exports[`lifecycle hooks lifecycle semantics, part 2 2`] = `
}"
`;
exports[`lifecycle hooks lifecycle semantics, part 2 3`] = `
exports[`lifecycle hooks lifecycle semantics, part 2 4`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
@@ -348,7 +348,7 @@ exports[`lifecycle hooks lifecycle semantics, part 4 1`] = `
}"
`;
exports[`lifecycle hooks lifecycle semantics, part 4 2`] = `
exports[`lifecycle hooks lifecycle semantics, part 4 3`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
@@ -360,7 +360,7 @@ exports[`lifecycle hooks lifecycle semantics, part 4 2`] = `
}"
`;
exports[`lifecycle hooks lifecycle semantics, part 4 3`] = `
exports[`lifecycle hooks lifecycle semantics, part 4 4`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
@@ -826,7 +826,7 @@ exports[`lifecycle hooks willStart, mounted on subwidget rendered after main is
let block3 = createBlock(\`<div/>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['state'].ok) {
b2 = comp1({}, key + \`__1\`, node, this, null);
} else {
@@ -11,7 +11,7 @@ exports[`.alike suffix in a list 1`] = `
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList(ctx['state'].elems);;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`elem\`] = v_block1[i1];
ctx[\`elem\`] = k_block1[i1];
const key1 = ctx['elem'].id;
const v1 = ctx['this'];
const v2 = ctx['elem'];
@@ -106,7 +106,7 @@ exports[`basics arrow functions as prop correctly capture their scope 1`] = `
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList(ctx['items']);;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`item\`] = v_block1[i1];
ctx[\`item\`] = k_block1[i1];
const key1 = ctx['item'].val;
const v1 = ctx['onClick'];
const v2 = ctx['item'];
@@ -39,7 +39,7 @@ exports[`default props can set default boolean values 2`] = `
let block1 = createBlock(\`<span><block-child-0/><block-child-1/></span>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['props'].p) {
b2 = text(\`hey\`);
}
@@ -23,7 +23,7 @@ exports[`refs can use 2 refs with same name in a t-if/t-else situation 1`] = `
let block3 = createBlock(\`<span block-ref=\\"0\\"/>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['state'].value) {
let ref1 = (el) => this.__owl__.setRef((\`coucou\`), el);
b2 = block2([ref1]);
@@ -509,7 +509,7 @@ exports[`slots default slot with slot scope: shorthand syntax 1`] = `
const comp1 = app.createComponent(\`Child\`, true, true, false, []);
function slot1(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['slotScope'].bool) {
b2 = text(\`some text\`);
} else {
@@ -633,7 +633,7 @@ exports[`slots dynamic slot in multiple locations 2`] = `
let block2 = createBlock(\`<p><block-child-0/></p>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b4;
let b2, b4;
if (ctx['props'].location===1) {
const slot1 = ('coffee');
const b3 = toggler(slot1, callSlot(ctx, node, key + \`__1\`, slot1, true, {}));
@@ -1066,6 +1066,45 @@ exports[`slots multiple slots containing components 3`] = `
}"
`;
exports[`slots named slot inside named slot in t-component 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { capture, markRaw } = helpers;
const comp1 = app.createComponent(null, false, true, false, []);
const comp2 = app.createComponent(\`Child\`, true, true, false, []);
function slot1(ctx, node, key = \\"\\") {
const b2 = text(\` outer \`);
const ctx2 = capture(ctx);
const Comp1 = ctx['Child'];
const b4 = toggler(Comp1, comp1({slots: markRaw({'brol': {__render: slot2.bind(this), __ctx: ctx2}})}, (Comp1).name + key + \`__1\`, node, this, Comp1));
return multi([b2, b4]);
}
function slot2(ctx, node, key = \\"\\") {
return text(ctx['value']);
}
return function template(ctx, node, key = \\"\\") {
const ctx1 = capture(ctx);
return comp2({slots: markRaw({'brol': {__render: slot1.bind(this), __ctx: ctx1}})}, key + \`__2\`, node, this, null);
}
}"
`;
exports[`slots named slot inside named slot in t-component 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { callSlot } = helpers;
return function template(ctx, node, key = \\"\\") {
return callSlot(ctx, node, key, 'brol', false, {});
}
}"
`;
exports[`slots named slot inside slot 1`] = `
"function anonymous(app, bdom, helpers
) {
@@ -1462,7 +1501,7 @@ exports[`slots simple default slot with params 1`] = `
const comp1 = app.createComponent(\`Child\`, true, true, false, []);
function slot1(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['slotScope'].bool) {
b2 = text(\`some text\`);
} else {
@@ -1558,7 +1597,7 @@ exports[`slots simple dynamic slot with slot scope 1`] = `
const comp1 = app.createComponent(\`Child\`, true, true, false, []);
function slot1(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['slotScope'].bool) {
b2 = text(\`some text\`);
} else {
@@ -1665,7 +1704,7 @@ exports[`slots simple slot with slot scope 1`] = `
const comp1 = app.createComponent(\`Child\`, true, true, false, []);
function slot1(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['slotScope'].bool) {
b2 = text(\`some text\`);
} else {
@@ -2082,7 +2121,7 @@ exports[`slots slot in multiple locations 2`] = `
let block2 = createBlock(\`<p><block-child-0/></p>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b4;
let b2, b4;
if (ctx['props'].location===1) {
const b3 = callSlot(ctx, node, key, 'default', false, {});
b2 = block2([], [b3]);
@@ -2140,7 +2179,7 @@ exports[`slots slot in t-foreach locations 2`] = `
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList(ctx['props'].list);;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`elem\`] = v_block1[i1];
ctx[\`elem\`] = k_block1[i1];
ctx[\`elem_index\`] = i1;
const key1 = ctx['elem_index'];
let txt1 = ctx['elem'];
@@ -2430,7 +2469,7 @@ exports[`slots slots are rendered with proper context, part 2 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['state'].users);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`user\`] = v_block2[i1];
ctx[\`user\`] = k_block2[i1];
const key1 = ctx['user'].id;
const ctx1 = capture(ctx);
const b7 = comp1({to: '/user/'+ctx['user'].id,slots: markRaw({'default': {__render: slot1.bind(this), __ctx: ctx1}})}, key + \`__1__\${key1}\`, node, this, null);
@@ -2478,7 +2517,7 @@ exports[`slots slots are rendered with proper context, part 3 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['state'].users);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`user\`] = v_block2[i1];
ctx[\`user\`] = k_block2[i1];
const key1 = ctx['user'].id;
setContextValue(ctx, \\"userdescr\\", 'User '+ctx['user'].name);
const ctx1 = capture(ctx);
@@ -2625,7 +2664,7 @@ exports[`slots slots in t-foreach and re-rendering 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(Array(2));;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`n\`] = v_block2[i1];
ctx[\`n\`] = k_block2[i1];
ctx[\`n_index\`] = i1;
const key1 = ctx['n_index'];
const ctx1 = capture(ctx);
@@ -2674,14 +2713,14 @@ exports[`slots slots in t-foreach in t-foreach 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['tree']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`node1\`] = v_block2[i1];
ctx[\`node1\`] = k_block2[i1];
const key1 = ctx['node1'].key;
let txt1 = ctx['node1'].value;
const b4 = block4([txt1]);
ctx = Object.create(ctx);
const [k_block6, v_block6, l_block6, c_block6] = prepareList(ctx['node1'].nodes);;
for (let i2 = 0; i2 < l_block6; i2++) {
ctx[\`node2\`] = v_block6[i2];
ctx[\`node2\`] = k_block6[i2];
const key2 = ctx['node2'].key;
const ctx1 = capture(ctx);
c_block6[i2] = withKey(comp1({slots: markRaw({'default': {__render: slot1.bind(this), __ctx: ctx1}})}, key + \`__1__\${key1}__\${key2}\`, node, this, null), key2);
@@ -2731,7 +2770,7 @@ exports[`slots slots in t-foreach with t-set and re-rendering 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(Array(2));;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`n\`] = v_block2[i1];
ctx[\`n\`] = k_block2[i1];
ctx[\`n_index\`] = i1;
const key1 = ctx['n_index'];
setContextValue(ctx, \\"dummy\\", ctx['n_index']);
@@ -2881,13 +2920,13 @@ exports[`slots t-slot in recursive templates 1`] = `
ctx = Object.create(ctx);
const [k_block3, v_block3, l_block3, c_block3] = prepareList(ctx['items']);;
for (let i1 = 0; i1 < l_block3; i1++) {
ctx[\`item\`] = v_block3[i1];
ctx[\`item\`] = k_block3[i1];
ctx[\`item_first\`] = i1 === 0;
ctx[\`item_last\`] = i1 === v_block3.length - 1;
ctx[\`item_last\`] = i1 === k_block3.length - 1;
ctx[\`item_index\`] = i1;
ctx[\`item_value\`] = k_block3[i1];
ctx[\`item_value\`] = v_block3[i1];
const key1 = ctx['item'].name;
let b5,b6;
let b5, b6;
if (!ctx['item'].children.length) {
b5 = text(ctx['item'].name);
} else {
@@ -166,7 +166,7 @@ exports[`style and class handling class on sub component, which is switched to a
const comp2 = app.createComponent(\`ChildB\`, true, false, false, [\\"class\\"]);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['props'].child==='a') {
b2 = comp1({class: ctx['props'].class}, key + \`__1\`, node, this, null);
} else {
@@ -10,8 +10,8 @@ exports[`t-call dynamic t-call 1`] = `
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
const b1 = text(\` owl \`);
ctx[zero] = b1;
const b2 = text(\` owl \`);
ctx[zero] = b2;
const template1 = (ctx['current'].template);
return call(this, template1, ctx, node, key + \`__1\`);
}
@@ -364,7 +364,7 @@ exports[`t-call sub components in two t-calls 1`] = `
let block3 = createBlock(\`<div><block-child-0/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['state'].val===1) {
b2 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
} else {
@@ -415,11 +415,11 @@ exports[`t-call t-call in t-foreach and children component 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(['a','b','c']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`val\`] = v_block2[i1];
ctx[\`val\`] = k_block2[i1];
ctx[\`val_first\`] = i1 === 0;
ctx[\`val_last\`] = i1 === v_block2.length - 1;
ctx[\`val_last\`] = i1 === k_block2.length - 1;
ctx[\`val_index\`] = i1;
ctx[\`val_value\`] = k_block2[i1];
ctx[\`val_value\`] = v_block2[i1];
const key1 = ctx['val'];
c_block2[i1] = withKey(callTemplate_1.call(this, ctx, node, key + \`__1__\${key1}\`), key1);
}
@@ -180,7 +180,7 @@ exports[`t-component switching dynamic component 2`] = `
}"
`;
exports[`t-component switching dynamic component 3`] = `
exports[`t-component switching dynamic component 4`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
@@ -14,7 +14,7 @@ exports[`list of components components in a node in a t-foreach 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['items']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`item\`] = v_block2[i1];
ctx[\`item\`] = k_block2[i1];
const key1 = 'li_'+ctx['item'];
const b4 = comp1({item: ctx['item']}, key + \`__1__\${key1}\`, node, this, null);
c_block2[i1] = withKey(block3([], [b4]), key1);
@@ -51,7 +51,7 @@ exports[`list of components crash on duplicate key in dev mode 1`] = `
const [k_block1, v_block1, l_block1, c_block1] = prepareList([1,2]);;
const keys1 = new Set();
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`item\`] = v_block1[i1];
ctx[\`item\`] = k_block1[i1];
const key1 = 'child';
if (keys1.has(String(key1))) { throw new OwlError(\`Got duplicate key in t-foreach: \${key1}\`)}
keys1.add(String(key1));
@@ -87,7 +87,7 @@ exports[`list of components crash when using object as keys that serialize to th
const [k_block1, v_block1, l_block1, c_block1] = prepareList([{},{}]);;
const keys1 = new Set();
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`item\`] = v_block1[i1];
ctx[\`item\`] = k_block1[i1];
const key1 = ctx['item'];
if (keys1.has(String(key1))) { throw new OwlError(\`Got duplicate key in t-foreach: \${key1}\`)}
keys1.add(String(key1));
@@ -125,7 +125,7 @@ exports[`list of components list of sub components inside other nodes 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['state'].blips);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`blip\`] = v_block2[i1];
ctx[\`blip\`] = k_block2[i1];
const key1 = ctx['blip'].id;
const b4 = comp1({}, key + \`__1__\${key1}\`, node, this, null);
c_block2[i1] = withKey(block3([], [b4]), key1);
@@ -191,7 +191,7 @@ exports[`list of components order is correct when slots are not of same type 2`]
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList(ctx['slotNames']);;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`slotName\`] = v_block1[i1];
ctx[\`slotName\`] = k_block1[i1];
const key1 = ctx['slotName'];
const slot1 = (ctx['slotName']);
c_block1[i1] = withKey(toggler(slot1, callSlot(ctx, node, key1 + \`__1__\${key1}\`, slot1, true, {})), key1);
@@ -214,13 +214,13 @@ exports[`list of components reconciliation alg works for t-foreach in t-foreach
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['state'].s);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`section\`] = v_block2[i1];
ctx[\`section\`] = k_block2[i1];
ctx[\`section_index\`] = i1;
const key1 = ctx['section_index'];
ctx = Object.create(ctx);
const [k_block3, v_block3, l_block3, c_block3] = prepareList(ctx['section'].blips);;
for (let i2 = 0; i2 < l_block3; i2++) {
ctx[\`blip\`] = v_block3[i2];
ctx[\`blip\`] = k_block3[i2];
ctx[\`blip_index\`] = i2;
const key2 = ctx['blip_index'];
c_block3[i2] = withKey(comp1({blip: ctx['blip']}, key + \`__1__\${key1}__\${key2}\`, node, this, null), key2);
@@ -263,12 +263,12 @@ exports[`list of components reconciliation alg works for t-foreach in t-foreach,
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['state'].rows);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`row\`] = v_block2[i1];
ctx[\`row\`] = k_block2[i1];
const key1 = ctx['row'];
ctx = Object.create(ctx);
const [k_block4, v_block4, l_block4, c_block4] = prepareList(ctx['state'].cols);;
for (let i2 = 0; i2 < l_block4; i2++) {
ctx[\`col\`] = v_block4[i2];
ctx[\`col\`] = k_block4[i2];
const key2 = ctx['col'];
const b6 = comp1({row: ctx['row'],col: ctx['col']}, key + \`__1__\${key1}__\${key2}\`, node, this, null);
c_block4[i2] = withKey(block5([], [b6]), key2);
@@ -308,7 +308,7 @@ exports[`list of components simple list 1`] = `
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList(ctx['state'].elems);;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`elem\`] = v_block1[i1];
ctx[\`elem\`] = k_block1[i1];
const key1 = ctx['elem'].id;
c_block1[i1] = withKey(comp1({value: ctx['elem'].value}, key + \`__1__\${key1}\`, node, this, null), key1);
}
@@ -344,7 +344,7 @@ exports[`list of components sub components rendered in a loop 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['state'].numbers);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`number\`] = v_block2[i1];
ctx[\`number\`] = k_block2[i1];
const key1 = ctx['number'];
c_block2[i1] = withKey(comp1({n: ctx['number']}, key + \`__1__\${key1}\`, node, this, null), key1);
}
@@ -381,7 +381,7 @@ exports[`list of components sub components with some state rendered in a loop 1`
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['state'].numbers);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`number\`] = v_block2[i1];
ctx[\`number\`] = k_block2[i1];
const key1 = ctx['number'];
c_block2[i1] = withKey(comp1({}, key + \`__1__\${key1}\`, node, this, null), key1);
}
@@ -418,7 +418,7 @@ exports[`list of components switch component position 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['clist']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`c\`] = v_block2[i1];
ctx[\`c\`] = k_block2[i1];
const key1 = ctx['c'];
c_block2[i1] = withKey(comp1({key: ctx['c']}, key + \`__1__\${key1}\`, node, this, null), key1);
}
@@ -455,7 +455,7 @@ exports[`list of components t-foreach with t-component, and update 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(Array(2));;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`n\`] = v_block2[i1];
ctx[\`n\`] = k_block2[i1];
ctx[\`n_index\`] = i1;
const key1 = ctx['n_index'];
c_block2[i1] = withKey(comp1({val: ctx['n_index']}, key + \`__1__\${key1}\`, node, this, null), key1);
@@ -13,7 +13,7 @@ exports[`t-key t-foreach with t-key switch component position 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['clist']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`c\`] = v_block2[i1];
ctx[\`c\`] = k_block2[i1];
const key1 = ctx['c'];
const tKey_1 = ctx['key1'];
c_block2[i1] = withKey(comp1({key: ctx['c']+ctx['key1']}, tKey_1 + key + \`__1__\${key1}\`, node, this, null), tKey_1 + key1);
@@ -196,7 +196,7 @@ exports[`t-model directive in a t-foreach 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['state']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`thing\`] = v_block2[i1];
ctx[\`thing\`] = k_block2[i1];
const key1 = ctx['thing'].id;
const bExpr1 = ctx['thing'];
const expr1 = 'f';
@@ -223,7 +223,7 @@ exports[`t-model directive in a t-foreach, part 2 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['state']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`thing\`] = v_block2[i1];
ctx[\`thing\`] = k_block2[i1];
ctx[\`thing_index\`] = i1;
const key1 = ctx['thing_index'];
const bExpr1 = ctx['state'];
@@ -251,7 +251,7 @@ exports[`t-model directive in a t-foreach, part 3 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['names']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`name\`] = v_block2[i1];
ctx[\`name\`] = k_block2[i1];
ctx[\`name_index\`] = i1;
const key1 = ctx['name_index'];
const bExpr1 = ctx['state'].values;
@@ -376,7 +376,7 @@ exports[`t-model directive on an input, type=checkbox 1`] = `
let block1 = createBlock(\`<div><input type=\\"checkbox\\" block-property-0=\\"checked\\" block-handler-1=\\"input\\"/><span><block-child-0/><block-child-1/></span></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
const bExpr1 = ctx['state'];
const expr1 = 'flag';
let prop1 = bExpr1[expr1];
@@ -468,6 +468,36 @@ exports[`t-model directive t-model on select with static options 1`] = `
}"
`;
exports[`t-model directive t-model with dynamic number values on select options in foreach 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { toNumber, prepareList, withKey } = helpers;
let block1 = createBlock(\`<select block-handler-0=\\"change\\"><block-child-0/></select>\`);
let block3 = createBlock(\`<option block-attribute-0=\\"value\\" block-attribute-1=\\"selected\\"><block-text-2/></option>\`);
return function template(ctx, node, key = \\"\\") {
const bExpr1 = ctx['state'];
const expr1 = 'value';
const bValue1 = bExpr1[expr1];
let hdlr1 = [(ev) => { bExpr1[expr1] = toNumber(ev.target.value); }];
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['state'].options);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`o\`] = k_block2[i1];
const key1 = ctx['o'].value;
let attr1 = ctx['o'].value;
let attr2 = bValue1 === ctx['o'].value;
let txt1 = ctx['o'].value;
c_block2[i1] = withKey(block3([attr1, attr2, txt1]), key1);
}
const b2 = list(c_block2);
return block1([hdlr1], [b2]);
}
}"
`;
exports[`t-model directive t-model with dynamic values on select options -- 2 1`] = `
"function anonymous(app, bdom, helpers
) {
@@ -556,7 +586,7 @@ exports[`t-model directive t-model with dynamic values on select options in fore
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['options']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`v\`] = v_block2[i1];
ctx[\`v\`] = k_block2[i1];
const key1 = ctx['v'];
let attr1 = ctx['v'];
let attr2 = bValue1 === ctx['v'];
@@ -583,7 +613,7 @@ exports[`t-model directive t-model with radio button group in t-foreach 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['options']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`opt\`] = v_block2[i1];
ctx[\`opt\`] = k_block2[i1];
const key1 = ctx['opt'];
let prop1 = new String((ctx['opt']) === 0 ? 0 : ((ctx['opt']) || \\"\\"));
let attr1 = ctx['opt'];
@@ -610,7 +640,7 @@ exports[`t-model directive two inputs in a div alternating with a t-if 1`] = `
let block3 = createBlock(\`<input class=\\"b\\" block-property-0=\\"value\\" block-handler-1=\\"input\\"/>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['state'].flag) {
const bExpr1 = ctx['state'];
const expr1 = 'text1';
@@ -16,7 +16,7 @@ exports[`t-on t-on expression captured in t-foreach 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['arr']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`val\`] = v_block2[i1];
ctx[\`val\`] = k_block2[i1];
const key1 = ctx['val'];
const v1 = ctx['otherState'];
const v2 = ctx['iter'];
@@ -43,7 +43,7 @@ exports[`t-on t-on expression in t-foreach 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['state'].values);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`val\`] = v_block2[i1];
ctx[\`val\`] = k_block2[i1];
ctx[\`val_index\`] = i1;
const key1 = ctx['val'];
let txt1 = ctx['val_index'];
@@ -75,7 +75,7 @@ exports[`t-on t-on expression in t-foreach with t-set 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['state'].values);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`val\`] = v_block2[i1];
ctx[\`val\`] = k_block2[i1];
ctx[\`val_index\`] = i1;
const key1 = ctx['val'];
setContextValue(ctx, \\"bossa\\", ctx['bossa']+'_'+ctx['val_index']);
@@ -106,7 +106,7 @@ exports[`t-on t-on method call in t-foreach 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['state'].values);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`val\`] = v_block2[i1];
ctx[\`val\`] = k_block2[i1];
ctx[\`val_index\`] = i1;
const key1 = ctx['val'];
let txt1 = ctx['val_index'];
@@ -196,7 +196,7 @@ exports[`t-on t-on on components and t-foreach 1`] = `
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList(['John','Raoul','Gérald']);;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`name\`] = v_block1[i1];
ctx[\`name\`] = k_block1[i1];
const key1 = ctx['name'];
const v1 = ctx['this'];
const v2 = ctx['name'];
@@ -493,7 +493,7 @@ exports[`t-on t-on when first component child is an empty component 2`] = `
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList(ctx['props'].list);;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`c\`] = v_block1[i1];
ctx[\`c\`] = k_block1[i1];
ctx[\`c_index\`] = i1;
const key1 = ctx['c_index'];
let txt1 = ctx['c'];
@@ -17,7 +17,7 @@ exports[`components in t-out simple list 1`] = `
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList([1,2]);;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`n\`] = v_block1[i1];
ctx[\`n\`] = k_block1[i1];
const key1 = ctx['n'];
ctx[\`blabla\`] = new LazyValue(value1, ctx, this, node, key1);
c_block1[i1] = withKey(safeOutput(ctx['blabla']), key1);
+52 -33
View File
@@ -5,6 +5,7 @@ import {
nextAppError,
nextTick,
snapshotEverything,
steps,
useLogLifecycle,
} from "../helpers";
import { markup } from "../../src/runtime/utils";
@@ -868,19 +869,26 @@ describe("basics", () => {
const parent = await mount(Parent, fixture);
expect(Object.keys(parent.__owl__.children).length).toStrictEqual(1);
expect([
"Child:setup",
"Child:willStart",
"Child:willRender",
"Child:rendered",
"Child:mounted",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Child:setup",
"Child:willStart",
"Child:willRender",
"Child:rendered",
"Child:mounted",
]
`);
parent.ifVar = false;
parent.render();
await nextTick();
expect(Object.keys(parent.__owl__.children).length).toStrictEqual(0);
expect(["Child:willUnmount", "Child:willDestroy"]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Child:willUnmount",
"Child:willDestroy",
]
`);
});
test("component children doesn't leak (t-key case)", async () => {
@@ -899,27 +907,31 @@ describe("basics", () => {
const parent = await mount(Parent, fixture);
expect(Object.keys(parent.__owl__.children).length).toStrictEqual(1);
expect([
"Child:setup",
"Child:willStart",
"Child:willRender",
"Child:rendered",
"Child:mounted",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Child:setup",
"Child:willStart",
"Child:willRender",
"Child:rendered",
"Child:mounted",
]
`);
parent.keyVar = 2;
parent.render();
await nextTick();
expect(Object.keys(parent.__owl__.children).length).toStrictEqual(1);
expect([
"Child:setup",
"Child:willStart",
"Child:willRender",
"Child:rendered",
"Child:willUnmount",
"Child:willDestroy",
"Child:mounted",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Child:setup",
"Child:willStart",
"Child:willRender",
"Child:rendered",
"Child:willUnmount",
"Child:willDestroy",
"Child:mounted",
]
`);
});
test("GrandChild display is controlled by its GrandParent", async () => {
@@ -943,20 +955,27 @@ describe("basics", () => {
const parent = await mount(Parent, fixture);
expect(fixture.innerHTML).toBe("<div></div>");
expect([
"GrandChild:setup",
"GrandChild:willStart",
"GrandChild:willRender",
"GrandChild:rendered",
"GrandChild:mounted",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"GrandChild:setup",
"GrandChild:willStart",
"GrandChild:willRender",
"GrandChild:rendered",
"GrandChild:mounted",
]
`);
parent.displayGrandChild = false;
parent.render();
await nextTick();
expect(fixture.innerHTML).toBe("");
expect(["GrandChild:willUnmount", "GrandChild:willDestroy"]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"GrandChild:willUnmount",
"GrandChild:willDestroy",
]
`);
});
});
@@ -1024,7 +1043,7 @@ describe("support svg components", () => {
await mount(Svg, fixture);
expect(fixture.innerHTML).toBe(
'<svg><g><circle cx="50" cy="50" r="4" stroke="green" stroke-width="1" fill="yellow"></circle></g></svg>'
'<svg xmlns="http://www.w3.org/2000/svg"><g xmlns="http://www.w3.org/2000/svg"><circle cx="50" cy="50" r="4" stroke="green" stroke-width="1" fill="yellow"></circle></g></svg>'
);
});
});
File diff suppressed because it is too large Load Diff
+219 -131
View File
@@ -19,8 +19,9 @@ import {
snapshotEverything,
useLogLifecycle,
nextAppError,
steps,
} from "../helpers";
import { OwlError } from "../../src/runtime/error_handling";
import { OwlError } from "../../src/common/owl_error";
let fixture: HTMLElement;
@@ -143,6 +144,66 @@ describe("basics", () => {
);
});
test("display a nice error if the root component template fails to compile", async () => {
// This is a special case: mount throws synchronously and we don't have any
// node which can handle the error, hence the different structure of this test
class Comp extends Component {
static template = xml`<div t-att-class="a b">test</div>`;
}
const app = new App(Comp);
let error: Error;
try {
await app.mount(fixture);
} catch (e) {
error = e as Error;
}
const expectedErrorMessage = `Failed to compile anonymous template: Unexpected identifier
generated code:
function(app, bdom, helpers) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div block-attribute-0="class">test</div>\`);
return function template(ctx, node, key = "") {
let attr1 = ctx['a']ctx['b'];
return block1([attr1]);
}
}`;
expect(error!).toBeDefined();
expect(error!.message).toBe(expectedErrorMessage);
});
test("display a nice error if a non-root component template fails to compile", async () => {
class Child extends Component {
static template = xml`<div t-att-class="a b">test</div>`;
}
class Parent extends Component {
static components = { Child };
static template = xml`<Child/>`;
}
const expectedErrorMessage = `Failed to compile anonymous template: Unexpected identifier
generated code:
function(app, bdom, helpers) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div block-attribute-0="class">test</div>\`);
return function template(ctx, node, key = "") {
let attr1 = ctx['a']ctx['b'];
return block1([attr1]);
}
}`;
const app = new App(Parent as typeof Component);
let error: Error;
const mountProm = app.mount(fixture).catch((e: Error) => (error = e));
await expect(nextAppError(app)).resolves.toThrow(expectedErrorMessage);
await mountProm;
expect(error!).toBeDefined();
expect(error!.message).toBe(expectedErrorMessage);
});
test("simple catchError", async () => {
class Boom extends Component {
static template = xml`<div t-esc="a.b.c"/>`;
@@ -888,26 +949,28 @@ describe("can catch errors", () => {
}
await mount(Root, fixture);
expect(fixture.innerHTML).toBe("<div><div>Error handled</div></div>");
expect([
"Root:setup",
"Root:willStart",
"Root:willRender",
"ErrorBoundary:setup",
"ErrorBoundary:willStart",
"Root:rendered",
"ErrorBoundary:willRender",
"ErrorComponent:setup",
"ErrorComponent:willStart",
"ErrorBoundary:rendered",
"ErrorComponent:willRender",
"ErrorComponent:rendered",
"ErrorComponent:mounted",
"boom",
"ErrorBoundary:willRender",
"ErrorBoundary:rendered",
"ErrorBoundary:mounted",
"Root:mounted",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Root:setup",
"Root:willStart",
"Root:willRender",
"ErrorBoundary:setup",
"ErrorBoundary:willStart",
"Root:rendered",
"ErrorBoundary:willRender",
"ErrorComponent:setup",
"ErrorComponent:willStart",
"ErrorBoundary:rendered",
"ErrorComponent:willRender",
"ErrorComponent:rendered",
"ErrorComponent:mounted",
"boom",
"ErrorBoundary:willRender",
"ErrorBoundary:rendered",
"ErrorBoundary:mounted",
"Root:mounted",
]
`);
expect(mockConsoleError).toBeCalledTimes(0);
expect(mockConsoleWarn).toBeCalledTimes(0);
});
@@ -938,21 +1001,23 @@ describe("can catch errors", () => {
}
await mount(Root, fixture);
expect(fixture.innerHTML).toBe("<div>Error handled</div>");
expect([
"Root:setup",
"Root:willStart",
"Root:willRender",
"ErrorComponent:setup",
"ErrorComponent:willStart",
"Root:rendered",
"ErrorComponent:willRender",
"ErrorComponent:rendered",
"ErrorComponent:mounted",
"boom",
"Root:willRender",
"Root:rendered",
"Root:mounted",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Root:setup",
"Root:willStart",
"Root:willRender",
"ErrorComponent:setup",
"ErrorComponent:willStart",
"Root:rendered",
"ErrorComponent:willRender",
"ErrorComponent:rendered",
"ErrorComponent:mounted",
"boom",
"Root:willRender",
"Root:rendered",
"Root:mounted",
]
`);
expect(mockConsoleError).toBeCalledTimes(0);
expect(mockConsoleWarn).toBeCalledTimes(0);
});
@@ -999,31 +1064,33 @@ describe("can catch errors", () => {
}
await mount(A, fixture);
expect(fixture.innerHTML).toBe("<div><div>Error handled</div></div>");
expect([
"A:setup",
"A:willStart",
"A:willRender",
"B:setup",
"B:willStart",
"A:rendered",
"B:willRender",
"C:setup",
"C:willStart",
"B:rendered",
"C:willRender",
"Boom:setup",
"Boom:willStart",
"C:rendered",
"Boom:willRender",
"Boom:rendered",
"Boom:mounted",
"boom",
"C:willRender",
"C:rendered",
"C:mounted",
"B:mounted",
"A:mounted",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"A:setup",
"A:willStart",
"A:willRender",
"B:setup",
"B:willStart",
"A:rendered",
"B:willRender",
"C:setup",
"C:willStart",
"B:rendered",
"C:willRender",
"Boom:setup",
"Boom:willStart",
"C:rendered",
"Boom:willRender",
"Boom:rendered",
"Boom:mounted",
"boom",
"C:willRender",
"C:rendered",
"C:mounted",
"B:mounted",
"A:mounted",
]
`);
expect(mockConsoleError).toBeCalledTimes(0);
expect(mockConsoleWarn).toBeCalledTimes(0);
});
@@ -1070,31 +1137,33 @@ describe("can catch errors", () => {
}
await mount(Root, fixture);
expect(fixture.innerHTML).toBe("<div>OK<div>Error handled</div></div>");
expect([
"Root:setup",
"Root:willStart",
"Root:willRender",
"OK:setup",
"OK:willStart",
"ErrorBoundary:setup",
"ErrorBoundary:willStart",
"Root:rendered",
"OK:willRender",
"OK:rendered",
"ErrorBoundary:willRender",
"ErrorComponent:setup",
"ErrorComponent:willStart",
"ErrorBoundary:rendered",
"ErrorComponent:willRender",
"ErrorComponent:rendered",
"ErrorComponent:mounted",
"boom",
"ErrorBoundary:willRender",
"ErrorBoundary:rendered",
"ErrorBoundary:mounted",
"OK:mounted",
"Root:mounted",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Root:setup",
"Root:willStart",
"Root:willRender",
"OK:setup",
"OK:willStart",
"ErrorBoundary:setup",
"ErrorBoundary:willStart",
"Root:rendered",
"OK:willRender",
"OK:rendered",
"ErrorBoundary:willRender",
"ErrorComponent:setup",
"ErrorComponent:willStart",
"ErrorBoundary:rendered",
"ErrorComponent:willRender",
"ErrorComponent:rendered",
"ErrorComponent:mounted",
"boom",
"ErrorBoundary:willRender",
"ErrorBoundary:rendered",
"ErrorBoundary:mounted",
"OK:mounted",
"Root:mounted",
]
`);
expect(mockConsoleError).toBeCalledTimes(0);
expect(mockConsoleWarn).toBeCalledTimes(0);
});
@@ -1421,34 +1490,39 @@ describe("can catch errors", () => {
const parent = await mount(Parent, fixture);
expect(fixture.innerHTML).toBe("1<div>abc</div>");
expect([
"Parent:setup",
"Parent:willStart",
"Parent:willRender",
"Child:setup",
"Child:willStart",
"Parent:rendered",
"Child:willRender",
"Child:rendered",
"Child:mounted",
"Parent:mounted",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:setup",
"Parent:willStart",
"Parent:willRender",
"Child:setup",
"Child:willStart",
"Parent:rendered",
"Child:willRender",
"Child:rendered",
"Child:mounted",
"Parent:mounted",
]
`);
parent.state.hasChild = false;
await nextTick();
await nextTick();
await nextTick();
await nextTick();
expect([
"Parent:willRender",
"Parent:rendered",
"Parent:willPatch",
"Child:willUnmount",
"Child:willDestroy",
"Parent:willRender",
"Parent:rendered",
"Parent:willPatch",
"Parent:patched",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:willRender",
"Parent:rendered",
"Parent:willPatch",
"Child:willUnmount",
"Child:willDestroy",
"Parent:patched",
"Parent:willRender",
"Parent:rendered",
"Parent:willPatch",
"Parent:patched",
]
`);
expect(fixture.innerHTML).toBe("2");
});
@@ -1481,13 +1555,15 @@ describe("can catch errors", () => {
const parent = await mount(Parent, fixture);
expect(fixture.innerHTML).toBe("1");
expect([
"Parent:setup",
"Parent:willStart",
"Parent:willRender",
"Parent:rendered",
"Parent:mounted",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:setup",
"Parent:willStart",
"Parent:willRender",
"Parent:rendered",
"Parent:mounted",
]
`);
parent.state.hasChild = true;
await nextMicroTick();
@@ -1495,23 +1571,35 @@ describe("can catch errors", () => {
await nextMicroTick();
await nextMicroTick();
await nextMicroTick();
expect([
"Parent:willRender",
"Child:setup",
"Child:willStart",
"Parent:rendered",
"Child:willRender",
"Child:rendered",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:willRender",
"Child:setup",
"Child:willStart",
"Parent:rendered",
"Child:willRender",
"Child:rendered",
]
`);
parent.state.hasChild = false;
await nextTick();
expect([
"Child:willDestroy",
"Parent:willRender",
"Parent:rendered",
"Parent:willPatch",
"Parent:patched",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:willRender",
"Parent:rendered",
"Child:willDestroy",
"Parent:willRender",
"Parent:rendered",
]
`);
expect(fixture.innerHTML).toBe("1");
await nextTick();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:willPatch",
"Parent:patched",
]
`);
expect(fixture.innerHTML).toBe("2");
});
});
+52
View File
@@ -641,6 +641,56 @@ describe("hooks", () => {
]);
});
test("effect types are inferred from dependencies", async () => {
// @ts-ignore (declared but never used)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
class MyComponent extends Component {
static template = xml`<div/>`;
setup() {
useEffect(
(a, b) => {
expectType<number>(a);
expectType<string>(b);
},
() => [3, "hello"]
);
}
}
});
test("effect type allows an effect with partial dependencies parameters", async () => {
// @ts-ignore (declared but never used)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
class MyComponent extends Component {
static template = xml`<div/>`;
setup() {
useEffect(
(a) => {
expectType<number>(a);
},
() => [3, "hello"]
);
}
}
});
test("effect type allows an effect with no dependency parameter", async () => {
// @ts-ignore (declared but never used)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
class MyComponent extends Component {
static template = xml`<div/>`;
setup() {
useEffect(
() => {},
() => [3, "hello"]
);
}
}
});
test("properly behaves when the effect function throws", async () => {
let originalconsoleError = console.error;
let originalconsoleWarn = console.warn;
@@ -673,3 +723,5 @@ describe("hooks", () => {
});
});
});
function expectType<T>(t: T) {}
+430 -337
View File
@@ -17,6 +17,7 @@ import {
nextMicroTick,
nextTick,
snapshotEverything,
steps,
useLogLifecycle,
} from "../helpers";
@@ -455,45 +456,51 @@ describe("lifecycle hooks", () => {
const parent = await mount(Parent, fixture);
expect(fixture.innerHTML).toBe("<div><span>0</span></div>");
expect([
"Parent:setup",
"Parent:willStart",
"Parent:willRender",
"Child:setup",
"Child:willStart",
"Parent:rendered",
"Child:willRender",
"Child:rendered",
"Child:mounted",
"Parent:mounted",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:setup",
"Parent:willStart",
"Parent:willRender",
"Child:setup",
"Child:willStart",
"Parent:rendered",
"Child:willRender",
"Child:rendered",
"Child:mounted",
"Parent:mounted",
]
`);
parent.increment();
await nextTick();
expect(fixture.innerHTML).toBe("<div><span>1</span></div>");
expect([
"Parent:willRender",
"Child:willUpdateProps",
"Parent:rendered",
"Child:willRender",
"Child:rendered",
"Parent:willPatch",
"Child:willPatch",
"Child:patched",
"Parent:patched",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:willRender",
"Child:willUpdateProps",
"Parent:rendered",
"Child:willRender",
"Child:rendered",
"Parent:willPatch",
"Child:willPatch",
"Child:patched",
"Parent:patched",
]
`);
parent.toggleSubWidget();
await nextTick();
expect(fixture.innerHTML).toBe("");
expect([
"Parent:willRender",
"Parent:rendered",
"Parent:willPatch",
"Child:willUnmount",
"Child:willDestroy",
"Parent:patched",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:willRender",
"Parent:rendered",
"Parent:willPatch",
"Child:willUnmount",
"Child:willDestroy",
"Parent:patched",
]
`);
});
test("hooks are called in proper order in widget creation/destruction", async () => {
@@ -514,26 +521,30 @@ describe("lifecycle hooks", () => {
const app = new App(Parent);
await app.mount(fixture);
expect([
"Parent:setup",
"Parent:willStart",
"Parent:willRender",
"Child:setup",
"Child:willStart",
"Parent:rendered",
"Child:willRender",
"Child:rendered",
"Child:mounted",
"Parent:mounted",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:setup",
"Parent:willStart",
"Parent:willRender",
"Child:setup",
"Child:willStart",
"Parent:rendered",
"Child:willRender",
"Child:rendered",
"Child:mounted",
"Parent:mounted",
]
`);
app.destroy();
expect([
"Parent:willUnmount",
"Child:willUnmount",
"Child:willDestroy",
"Parent:willDestroy",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:willUnmount",
"Child:willUnmount",
"Child:willDestroy",
"Parent:willDestroy",
]
`);
});
test("willUpdateProps hook is called", async () => {
@@ -632,26 +643,30 @@ describe("lifecycle hooks", () => {
const app = new App(Parent);
await app.mount(fixture);
expect([
"Parent:setup",
"Parent:willStart",
"Parent:willRender",
"Child:setup",
"Child:willStart",
"Parent:rendered",
"Child:willRender",
"Child:rendered",
"Child:mounted",
"Parent:mounted",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:setup",
"Parent:willStart",
"Parent:willRender",
"Child:setup",
"Child:willStart",
"Parent:rendered",
"Child:willRender",
"Child:rendered",
"Child:mounted",
"Parent:mounted",
]
`);
app.destroy();
expect([
"Parent:willUnmount",
"Child:willUnmount",
"Child:willDestroy",
"Parent:willDestroy",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:willUnmount",
"Child:willUnmount",
"Child:willDestroy",
"Parent:willDestroy",
]
`);
});
test("lifecycle semantics, part 2", async () => {
@@ -680,42 +695,48 @@ describe("lifecycle hooks", () => {
const app = new App(Parent);
const parent = await app.mount(fixture);
expect([
"Parent:setup",
"Parent:willStart",
"Parent:willRender",
"Parent:rendered",
"Parent:mounted",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:setup",
"Parent:willStart",
"Parent:willRender",
"Parent:rendered",
"Parent:mounted",
]
`);
parent.state.hasChild = true;
await nextTick();
expect([
"Parent:willRender",
"Child:setup",
"Child:willStart",
"Parent:rendered",
"Child:willRender",
"GrandChild:setup",
"GrandChild:willStart",
"Child:rendered",
"GrandChild:willRender",
"GrandChild:rendered",
"Parent:willPatch",
"GrandChild:mounted",
"Child:mounted",
"Parent:patched",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:willRender",
"Child:setup",
"Child:willStart",
"Parent:rendered",
"Child:willRender",
"GrandChild:setup",
"GrandChild:willStart",
"Child:rendered",
"GrandChild:willRender",
"GrandChild:rendered",
"Parent:willPatch",
"GrandChild:mounted",
"Child:mounted",
"Parent:patched",
]
`);
app.destroy();
expect([
"Parent:willUnmount",
"Child:willUnmount",
"GrandChild:willUnmount",
"GrandChild:willDestroy",
"Child:willDestroy",
"Parent:willDestroy",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:willUnmount",
"Child:willUnmount",
"GrandChild:willUnmount",
"GrandChild:willDestroy",
"Child:willDestroy",
"Parent:willDestroy",
]
`);
});
test("lifecycle semantics, part 3", async () => {
@@ -744,19 +765,26 @@ describe("lifecycle hooks", () => {
const app = new App(Parent);
const parent = await app.mount(fixture);
expect([
"Parent:setup",
"Parent:willStart",
"Parent:willRender",
"Parent:rendered",
"Parent:mounted",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:setup",
"Parent:willStart",
"Parent:willRender",
"Parent:rendered",
"Parent:mounted",
]
`);
parent.state.hasChild = true;
// immediately destroy everything
app.destroy();
await nextTick();
expect(["Parent:willUnmount", "Parent:willDestroy"]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:willUnmount",
"Parent:willDestroy",
]
`);
});
test("lifecycle semantics, part 4", async () => {
@@ -789,34 +817,40 @@ describe("lifecycle hooks", () => {
const app = new App(Parent);
const parent = await app.mount(fixture);
expect([
"Parent:setup",
"Parent:willStart",
"Parent:willRender",
"Parent:rendered",
"Parent:mounted",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:setup",
"Parent:willStart",
"Parent:willRender",
"Parent:rendered",
"Parent:mounted",
]
`);
parent.state.hasChild = true;
await nextTick();
expect([
"Parent:willRender",
"Child:setup",
"Child:willStart",
"Parent:rendered",
"Child:willRender",
"GrandChild:setup",
"GrandChild:willStart",
"Child:rendered",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:willRender",
"Child:setup",
"Child:willStart",
"Parent:rendered",
"Child:willRender",
"GrandChild:setup",
"GrandChild:willStart",
"Child:rendered",
]
`);
app.destroy();
expect([
"Parent:willUnmount",
"GrandChild:willDestroy",
"Child:willDestroy",
"Parent:willDestroy",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:willUnmount",
"GrandChild:willDestroy",
"Child:willDestroy",
"Parent:willDestroy",
]
`);
});
test("lifecycle semantics, part 5", async () => {
@@ -837,29 +871,33 @@ describe("lifecycle hooks", () => {
}
const parent = await mount(Parent, fixture);
expect([
"Parent:setup",
"Parent:willStart",
"Parent:willRender",
"Child:setup",
"Child:willStart",
"Parent:rendered",
"Child:willRender",
"Child:rendered",
"Child:mounted",
"Parent:mounted",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:setup",
"Parent:willStart",
"Parent:willRender",
"Child:setup",
"Child:willStart",
"Parent:rendered",
"Child:willRender",
"Child:rendered",
"Child:mounted",
"Parent:mounted",
]
`);
parent.state.hasChild = false;
await nextTick();
expect([
"Parent:willRender",
"Parent:rendered",
"Parent:willPatch",
"Child:willUnmount",
"Child:willDestroy",
"Parent:patched",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:willRender",
"Parent:rendered",
"Parent:willPatch",
"Child:willUnmount",
"Child:willDestroy",
"Parent:patched",
]
`);
});
test("lifecycle semantics, part 6", async () => {
@@ -880,32 +918,36 @@ describe("lifecycle hooks", () => {
}
const parent = await mount(Parent, fixture);
expect([
"Parent:setup",
"Parent:willStart",
"Parent:willRender",
"Child:setup",
"Child:willStart",
"Parent:rendered",
"Child:willRender",
"Child:rendered",
"Child:mounted",
"Parent:mounted",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:setup",
"Parent:willStart",
"Parent:willRender",
"Child:setup",
"Child:willStart",
"Parent:rendered",
"Child:willRender",
"Child:rendered",
"Child:mounted",
"Parent:mounted",
]
`);
parent.state.value = 2;
await nextTick();
expect([
"Parent:willRender",
"Child:willUpdateProps",
"Parent:rendered",
"Child:willRender",
"Child:rendered",
"Parent:willPatch",
"Child:willPatch",
"Child:patched",
"Parent:patched",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:willRender",
"Child:willUpdateProps",
"Parent:rendered",
"Child:willRender",
"Child:rendered",
"Parent:willPatch",
"Child:willPatch",
"Child:patched",
"Parent:patched",
]
`);
});
test("onWillRender", async () => {
@@ -937,43 +979,53 @@ describe("lifecycle hooks", () => {
const parent = await mount(Parent, fixture);
expect(fixture.innerHTML).toBe("<button>1</button>");
expect([
"Parent:setup",
"Parent:willStart",
"Parent:willRender",
"Child:setup",
"Child:willStart",
"Parent:rendered",
"Child:willRender",
"Child:rendered",
"Child:mounted",
"Parent:mounted",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:setup",
"Parent:willStart",
"Parent:willRender",
"Child:setup",
"Child:willStart",
"Parent:rendered",
"Child:willRender",
"Child:rendered",
"Child:mounted",
"Parent:mounted",
]
`);
parent.state.value++; // to block child render
await nextTick();
expect(["Parent:willRender", "Child:willUpdateProps", "Parent:rendered"]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:willRender",
"Child:willUpdateProps",
"Parent:rendered",
]
`);
fixture.querySelector("button")!.click();
await nextTick();
expect([]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`Array []`);
fixture.querySelector("button")!.click();
await nextTick();
expect([]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`Array []`);
expect(fixture.innerHTML).toBe("<button>1</button>");
def.resolve();
await nextTick();
expect(fixture.innerHTML).toBe("<button>3</button>");
expect([
"Child:willRender",
"Child:rendered",
"Parent:willPatch",
"Child:willPatch",
"Child:patched",
"Parent:patched",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Child:willRender",
"Child:rendered",
"Parent:willPatch",
"Child:willPatch",
"Child:patched",
"Parent:patched",
]
`);
});
// TODO: rename (remove? seems covered by lifecycle semantics)
@@ -1054,50 +1106,54 @@ describe("lifecycle hooks", () => {
await mount(A, fixture);
expect(fixture.innerHTML).toBe(`<div>A<div>B</div><div>C<div>D</div><div>E</div></div></div>`);
expect([
"A:setup",
"A:willStart",
"A:willRender",
"B:setup",
"B:willStart",
"C:setup",
"C:willStart",
"A:rendered",
"B:willRender",
"B:rendered",
"C:willRender",
"D:setup",
"D:willStart",
"E:setup",
"E:willStart",
"C:rendered",
"D:willRender",
"D:rendered",
"E:willRender",
"E:rendered",
"E:mounted",
"D:mounted",
"C:mounted",
"B:mounted",
"A:mounted",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"A:setup",
"A:willStart",
"A:willRender",
"B:setup",
"B:willStart",
"C:setup",
"C:willStart",
"A:rendered",
"B:willRender",
"B:rendered",
"C:willRender",
"D:setup",
"D:willStart",
"E:setup",
"E:willStart",
"C:rendered",
"D:willRender",
"D:rendered",
"E:willRender",
"E:rendered",
"E:mounted",
"D:mounted",
"C:mounted",
"B:mounted",
"A:mounted",
]
`);
// update
c!.state.flag = false;
await nextTick();
expect([
"C:willRender",
"F:setup",
"F:willStart",
"C:rendered",
"F:willRender",
"F:rendered",
"C:willPatch",
"E:willUnmount",
"E:willDestroy",
"F:mounted",
"C:patched",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"C:willRender",
"F:setup",
"F:willStart",
"C:rendered",
"F:willRender",
"F:rendered",
"C:willPatch",
"E:willUnmount",
"E:willDestroy",
"F:mounted",
"C:patched",
]
`);
});
test("mounted hook is called on every mount, not just the first one", async () => {
@@ -1118,43 +1174,49 @@ describe("lifecycle hooks", () => {
}
const parent = await mount(Parent, fixture);
expect([
"Parent:setup",
"Parent:willStart",
"Parent:willRender",
"Child:setup",
"Child:willStart",
"Parent:rendered",
"Child:willRender",
"Child:rendered",
"Child:mounted",
"Parent:mounted",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:setup",
"Parent:willStart",
"Parent:willRender",
"Child:setup",
"Child:willStart",
"Parent:rendered",
"Child:willRender",
"Child:rendered",
"Child:mounted",
"Parent:mounted",
]
`);
parent.state.hasChild = false;
await nextTick();
expect([
"Parent:willRender",
"Parent:rendered",
"Parent:willPatch",
"Child:willUnmount",
"Child:willDestroy",
"Parent:patched",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:willRender",
"Parent:rendered",
"Parent:willPatch",
"Child:willUnmount",
"Child:willDestroy",
"Parent:patched",
]
`);
parent.state.hasChild = true;
await nextTick();
expect([
"Parent:willRender",
"Child:setup",
"Child:willStart",
"Parent:rendered",
"Child:willRender",
"Child:rendered",
"Parent:willPatch",
"Child:mounted",
"Parent:patched",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:willRender",
"Child:setup",
"Child:willStart",
"Parent:rendered",
"Child:willRender",
"Child:rendered",
"Parent:willPatch",
"Child:mounted",
"Parent:patched",
]
`);
});
test("render in mounted", async () => {
@@ -1172,19 +1234,26 @@ describe("lifecycle hooks", () => {
await mount(Parent, fixture);
expect(fixture.innerHTML).toBe("<span></span>");
expect([
"Parent:setup",
"Parent:willStart",
"Parent:willRender",
"Parent:rendered",
"Parent:mounted",
"Parent:willRender",
"Parent:rendered",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:setup",
"Parent:willStart",
"Parent:willRender",
"Parent:rendered",
"Parent:mounted",
"Parent:willRender",
"Parent:rendered",
]
`);
await nextTick();
expect(fixture.innerHTML).toBe("<span>Patched</span>");
expect(["Parent:willPatch", "Parent:patched"]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:willPatch",
"Parent:patched",
]
`);
});
test("render in patched", async () => {
@@ -1205,29 +1274,38 @@ describe("lifecycle hooks", () => {
const parent = await mount(Parent, fixture);
expect(fixture.innerHTML).toBe("<span></span>");
expect([
"Parent:setup",
"Parent:willStart",
"Parent:willRender",
"Parent:rendered",
"Parent:mounted",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:setup",
"Parent:willStart",
"Parent:willRender",
"Parent:rendered",
"Parent:mounted",
]
`);
parent.render();
await nextTick();
expect(fixture.innerHTML).toBe("<span></span>");
expect([
"Parent:willRender",
"Parent:rendered",
"Parent:willPatch",
"Parent:patched",
"Parent:willRender",
"Parent:rendered",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:willRender",
"Parent:rendered",
"Parent:willPatch",
"Parent:patched",
"Parent:willRender",
"Parent:rendered",
]
`);
await nextTick();
expect(fixture.innerHTML).toBe("<span>Patched</span>");
expect(["Parent:willPatch", "Parent:patched"]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:willPatch",
"Parent:patched",
]
`);
});
test("render in willPatch", async () => {
@@ -1248,29 +1326,38 @@ describe("lifecycle hooks", () => {
const parent = await mount(Parent, fixture);
expect(fixture.innerHTML).toBe("<span></span>");
expect([
"Parent:setup",
"Parent:willStart",
"Parent:willRender",
"Parent:rendered",
"Parent:mounted",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:setup",
"Parent:willStart",
"Parent:willRender",
"Parent:rendered",
"Parent:mounted",
]
`);
parent.render();
await nextTick();
expect(fixture.innerHTML).toBe("<span></span>");
expect([
"Parent:willRender",
"Parent:rendered",
"Parent:willPatch",
"Parent:patched",
"Parent:willRender",
"Parent:rendered",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:willRender",
"Parent:rendered",
"Parent:willPatch",
"Parent:patched",
"Parent:willRender",
"Parent:rendered",
]
`);
await nextTick();
expect(["Parent:willPatch", "Parent:patched"]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:willPatch",
"Parent:patched",
]
`);
expect(fixture.innerHTML).toBe("<span>Patched</span>");
});
@@ -1313,19 +1400,21 @@ describe("lifecycle hooks", () => {
await nextTick();
app.destroy();
expect([
"onWillStart",
"onWillRender",
"onRendered",
"onMounted",
"onWillUpdateProps",
"onWillRender",
"onRendered",
"onWillPatch",
"onPatched",
"onWillUnmount",
"onWillDestroy",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"onWillStart",
"onWillRender",
"onRendered",
"onMounted",
"onWillUpdateProps",
"onWillRender",
"onRendered",
"onWillPatch",
"onPatched",
"onWillUnmount",
"onWillDestroy",
]
`);
});
test("destroy new children before being mountged", async () => {
@@ -1357,26 +1446,30 @@ describe("lifecycle hooks", () => {
const app = new App(Parent);
const parent = await app.mount(fixture);
expect(fixture.innerHTML).toBe("beforeafter");
expect([
"Parent:setup",
"Parent:willStart",
"Parent:willRender",
"Parent:rendered",
"Parent:mounted",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:setup",
"Parent:willStart",
"Parent:willRender",
"Parent:rendered",
"Parent:mounted",
]
`);
parent.state.flag = true;
await nextTick();
expect(fixture.innerHTML).toBe("");
expect([
"Parent:willRender",
"Child:setup",
"Child:willStart",
"Parent:rendered",
"Parent:willUnmount",
"Child:willDestroy",
"Parent:willDestroy",
]).toBeLogged();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"Parent:willRender",
"Child:setup",
"Child:willStart",
"Parent:rendered",
"Parent:willUnmount",
"Child:willDestroy",
"Parent:willDestroy",
]
`);
});
});

Some files were not shown because too many files have changed in this diff Show More