Compare commits

...

1359 Commits

Author SHA1 Message Date
Samuel Degueldre 61fc3f4fdc [REL] v2.2.8
# v2.2.8

 - [IMP] template set config: getTemplate function
 - [IMP] parser: .trim modifier implies .lazy modifier
 - [REF] parser, template_set: factor out parseXML function
2024-01-12 11:03:03 +01:00
Mathieu Duckerts-Antoine 7b454dae66 [IMP] template set config: getTemplate function
A template set can now obtain a template by calling the function
getTemplate (if any) received in the initial config.
The returned value can be an Element instance, a template string, a
function (i.e. a compiled template), or null. In the last case, owl will
look into the template set rawTemplates object.
2024-01-12 10:56:02 +01:00
FrancoisGe 70101e4c66 [IMP] parser: .trim modifier implies .lazy modifier
Before to this commit, the .trim modifier did not work correctly. The value
in the model is always trim at each input event but not the visual value
in the input. This difference between the visual and the model value cause
few strange bug.

After reflection, we think that we always want to be in .lazy when we use .trim.
Because we want to trim the final value during the onchange event and not
at each input event. If we do it at each input event, we can't write more then
one word easily.

So this commit change the behavior of the .trim modifier to always be in .lazy
2024-01-04 11:07:37 +01:00
Samuel Degueldre 5ef405293a [REF] parser, template_set: factor out parseXML function
For some reason the code of parseXML was duplicated, despite being
exactly the same except for some whitespace. Move it out into a common
utils file.

closes #1569
2023-12-22 11:01:19 +01:00
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
Géry Debongnie ba20267151 [REL] v2.1.3
# 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-04-29 09:46:05 +02:00
Géry Debongnie aabb7559b8 [FIX] components: properly differentiate t-call subcomponents
Before this commit, when using a dynamic t-call, it was possible to have
a collision between subcomponent keys. This would cause hard to
understand owl crash, because owl would incorrectly use the same
component instance for two different template location. From
owl point of view, one of these component has to be destroyed and the
other one should be mounted, so a crash would occur.

The fix is to simply properly key sub components.
2023-04-28 14:31:34 +02:00
Julien Carion (juca) 606d14a399 [REF] devtools: Better messages forwarding
This commit improves how messages are relayed from the page to the
devtools by using a specific port for each instance of the owl devtools
panel and refreshing it through the heartbeat message. This allows
to prevent sending messages to every devtools instances and sorting
the messages inside.
2023-04-25 09:31:53 +02:00
Julien Carion (juca) c049022798 [FIX] devtools: Fix app methods patching
This commit fixes how the apps methods are patched by decoupling
the patching of the destroy method from the rest because we need
to have a valid reference to a component node to do so (the root
node in this case). The previous behavior was to only patch methods
when an app with a root node is added but this was not working
when the app has no root node initially and gets one dynamically.
There is now a listener to patch the destroy method as soon as a
root node is set on any of the apps if it is not already the case.
2023-04-25 09:28:57 +02:00
myearn4 cae32c5bd4 [DOC] Fix a code bug in the example of slots
The value of activeTab should be tab_index rather than tab.
2023-04-25 09:24:31 +02:00
Géry Debongnie 63128b7d29 [REL] v2.1.2
# v2.1.2

 - [FIX] t-out: does not crash when outputting null
 - [FIX] playground: fix name of playground component
 - [FIX] playground: use ES owl version instead of iife
 - [IMP] playground: give a name so it is more explicit in devtools
 - [REF] github page: move page to docs folder on master branch
 - [IMP/FIX] playground: fix and improve various things
2023-04-24 16:29:43 +02:00
Géry Debongnie f9d810a42f [FIX] t-out: does not crash when outputting null
Before this commit, doing `t-out="null"` would crash, since the
safeOutput function would assume that it is a block, thanks to the fact
that `typeof null === 'object'`.

We handle here the null value just as if it was undefined: it outputs an
empty string.
2023-04-24 16:23:27 +02:00
Samuel Degueldre 1784a98b2c [FIX] playground: fix name of playground component 2023-04-24 15:53:09 +02:00
Géry Debongnie 52be5ae85f [FIX] playground: use ES owl version instead of iife
Otherwise, it will try to import owl from the iife build, which will not
work
2023-04-24 15:44:41 +02:00
Géry Debongnie 0765b19367 [IMP] playground: give a name so it is more explicit in devtools 2023-04-24 15:44:41 +02:00
Samuel Degueldre b8b5190bc6 [REF] github page: move page to docs folder on master branch
Currently, some of the things on the playground must be changed directly
on the master branch while other things require checking out the
gh-pages branch and making the modifications there. Even when changes
need to be made on the master branch, all changes that are not direcly
in owl itself need to be copied by hand to the gh-pages branch.

This commit moves all files that exist on the gh-pages branch to the
master branch in the docs folder, this change will require configuring
the github page to use the docs folder instead of a separate branch, but
will make maintenance of the github page and playground easier going
forward.
2023-04-24 15:32:51 +02:00
Samuel Degueldre 9475de4d18 [IMP/FIX] playground: fix and improve various things
The playground hasn't been touched for a while and a few things were
broken before this commit:
- Exporting as a standalone web application was broken because it still
attempted to load the templates like it was done in owl 1
- Resizing the editor tabs still tried to use `this.trigger`

While fixing the export feature, the files needed by the app were
factored out of hardcoded strings and into real files, as this makes it
easier to maintain, since these files get syntax highlighting.

The samples received the same treatment: there is now a `samples` folder
containing all the samples, it also contains a jsconfig, giving
autocompletion on owl functions while editing the files, and allowing
the owl import to look how it would when using owl as a node_module.
In the browser, this import is translated to the relative path of the
owl module using an import map.
2023-04-24 15:32:51 +02:00
Géry Debongnie 4b9e6bad0b [REL] v2.1.1
# v2.1.1

 - [FIX] components: solve missing update (concurrency issue)
 - [DOC] remove old references to comp for useRef hook
 - [FIX] devtools: Fix build commands for windows users
 - [FIX] devtools: Fix devtools in detached window
 - [IMP] devtools: Add a button to navigate to the doc
 - [IMP] devtools: Add devtools documentation
 - [IMP] Allow app to be mounted in shadow DOM
 - [IMP] playground: allow sharing playground links
 - [IMP] runtime: allow validating object values using a type description
 - [FIX] devtools: Increase vertical padding of the search bar
 - [FIX] devtools: Hide the collapse all button
 - [FIX] devtools: Fix bad computation of highlight boxes on the page
 - [FIX] package: Auto-update package-lock.json
2023-04-17 11:08:57 +02:00
Géry Debongnie 9a5ff7a619 [FIX] components: solve missing update (concurrency issue)
Before this commit, in some specific situations, owl could skip updating
the DOM, even though it should. Here is what could happen:

- we have a parent component (A) and a child component (B)
- B depends on some reactive props from A
- we update some state that results in A being rendered, and B updated
- before this render is applied to the dom, we update some state again,
which causes A to be rendered again
- however, this new render is such that the B props are now identical,
so it will skip rendering B
- it will then apply the result of the render to the DOM => only A is
updated but B should also be updated!

The problem comes from the fact that Owl committed the props to the
component right after the rendering, to the new props were used in the
props comparison method to decide if B should be updated. This is
incorrect, we should always use the current props to decide what to do,
and only commit them to the component after it has been patched.
2023-04-17 11:06:31 +02:00
Géry Debongnie 5d40cc112d [DOC] remove old references to comp for useRef hook
Going from owl 1.0 to 2.0, we removed the possibility of having a
reference to a component. However, the documentation was not properly
updated to reflect that.
2023-04-13 10:39:20 +02:00
Julien Carion (juca) aa19897031 [FIX] devtools: Fix build commands for windows users
This commit adapts the commands used and the rollup file to be
compatible with windows console commands syntax.
2023-04-13 10:17:59 +02:00
Julien Carion (juca) afd7f957df [FIX] devtools: Fix devtools in detached window
This commit fixes the issues that were happening when using the
devtools in a detached window
2023-04-13 09:30:44 +02:00
Julien Carion (juca) cca4b4bb8e [IMP] devtools: Add a button to navigate to the doc
This commit adds a button to the devtools navbar which links
to the documentation.
2023-04-12 17:11:45 +02:00
Julien Carion (juca) b848a83777 [IMP] devtools: Add devtools documentation
This commit adds the documentation for the devtools extension.
2023-04-11 11:01:07 +02:00
tsm-odoo c0c40c0387 [IMP] Allow app to be mounted in shadow DOM
This commit allow owl Apps to be mounted into a shadow DOM.
2023-04-11 08:43:42 +02:00
Samuel Degueldre 606421776b [IMP] playground: allow sharing playground links
This is useful to share editable snippets of owl code, which can be used
to paste a reproduction for a given issue or give someone an interactive
example of some feature.
2023-04-06 11:48:36 +02:00
Samuel Degueldre 47009912df [IMP] runtime: allow validating object values using a type description
In JS, objects are often used as a mapping that gives fast lookup on the
keys, in those cases, the keys themselves are not known in advance, but
the values may have a shape that they're expected to follow. This commit
adds support for a `values` key in schema for objects, which will be
checked against all values in the object during validation.
2023-04-06 08:58:58 +02:00
Julien Carion (juca) fea8fcaf61 [FIX] devtools: Increase vertical padding of the search bar
This commit increases the vertical padding of the search bar in
order to be easier to click on.
2023-04-06 08:58:30 +02:00
Julien Carion (juca) e562f6a24f [FIX] devtools: Hide the collapse all button
This commit hides the collapse all button when the profiler is in
Events log mode since it doesn't do anything in this case
2023-04-06 08:58:30 +02:00
Julien Carion (juca) 23acf203e9 [FIX] devtools: Fix bad computation of highlight boxes on the page
This commit adds box-sizing: border-box to the highlight elements
created by the devtools on the page. This was making some of the
boxes overflow on some pages (like on POS sessions) because
the border-box box-sizing was not the default behavior on these
pages.
2023-04-06 08:58:30 +02:00
Julien Carion (juca) 94ae940e82 [FIX] package: Auto-update package-lock.json
This commit updates the version in package-lock.json and make it so
it is automatically and correctly updated at each new release.
2023-03-31 13:39:30 +02:00
Géry Debongnie 64de716b91 [REL] v2.1.0 2023-03-30 13:05:25 +02:00
Julien Carion (juca) 1b1597c49e [IMP] tools: Include the devtools into the release system
This commit adds the devtools as a zip file containing both chrome
and firefox versions of the extension in the release and also updates
the doc to install it easily.
2023-03-30 13:03:00 +02:00
Julien Carion ef5e4a0637 [ADD] tools: create owl-devtools extension
This commit adds the code of the owl devtools extension.
This extension can be added on chrome or on firefox for
developpers to be able to inspect the contents of all owl
applications that are present on any web page, see all the
components, interract with them and their content to some
extend and perform a bit of profiling with their renders.
2023-03-30 12:57:28 +02:00
Lucas Lefèvre a9323c3fcd [REF] hooks: avoid confusion for sync hooks
`onWillPatch`, `onWillUnmount`, `onWillDestroy` are synchronous hooks.
Owl will not wait any promise return by the callback.
Yet, the callback return type includes `Promise<void>`,
which is confusing as one might think it means the hooks is async.
2023-03-24 10:32:47 +01:00
Louis Wicket ce61e90135 [FIX] doc: add missing brackets 2023-03-22 15:19:00 +01:00
Géry Debongnie 8893e026d3 [REL] v2.0.9
# v2.0.9

 - [FIX] components: do not crash when binding anonymous function
2023-03-13 10:55:05 +01:00
Géry Debongnie 0024f33fa1 [FIX] components: do not crash when binding anonymous function
It is not really useful, but it is possible to bind an anonymous
function prop. However, with the recent change on how the bind feature
works, it now crashes.

This commit makes sure that we properly apply the `bind` operation to
the function, and not to the last term of the function.
2023-03-09 15:35:13 +01:00
Géry Debongnie 532ab7fae0 [REL] v2.0.8
# v2.0.8

 - [IMP] implement .alike suffix on props
 - [IMP] release: add version number on App
 - [IMP] app: add name as a config option
 - [FIX] runtime, compiler: fix refs getting set or unset incorrectly
 - [FIX] compiler: call translate function with correct string
 - [FIX] compiler: properly handle readonly attribute/readOnly property
 - [REF] blockdom,compiler: implement properties
 - [REF] tests: move properties tests in own file
 - [FIX] compiler: dynamic value on inputs doesn't turn 0 into empty string
2023-03-09 13:11:21 +01:00
Géry Debongnie a51b286671 [IMP] implement .alike suffix on props
It is common in Owl components to have anonymous function as props.
However, since each rendering create a different (but equivalent)
closure, Owl will consider the props different, so will update the child
component, but this is (often) not necessary.

This commit will help reduce the problem by introducing a new `.alike`
prop suffix, that will let Owl know that each version of that specific
prop should be considered the same, so, will be ignored by the props
comparison code.

closes #1360
2023-03-09 11:14:00 +01:00
Géry Debongnie aadc9eafa3 [IMP] release: add version number on App
Before this commit, the version number was added by the rollup
configuration script. It worked, but it meant that there was no robust
way to access the version number in many case. For example, what if I
have a page with two different version of owl? Or what if one of them
uses the ESM module system, and does not export owl as a global object?

This is not really a big deal, but accessing the version number is
useful for tooling purpose, so this commit makes it possible to read the
version number on each individual App, as a static property.
2023-03-08 10:18:35 +01:00
Géry Debongnie 1f60bc79c5 [IMP] app: add name as a config option
Useful for tooling purpose

closes #1342
2023-03-08 10:16:25 +01:00
Samuel Degueldre 975ed32f0b [FIX] runtime, compiler: fix refs getting set or unset incorrectly
Previously, refs could get set to null incorrectly, or could stay set
when they shouldn't. This was caused by the fact that singleRefSetter
and multiRefSetters are created on every render, meaning that any render
that did not affect the status of the ref (mounted or not), would
overwrite the previous ref setter, including its closure, causing the
captured `_el` or `count` to be lost. This means that on a subsequent
render that did affect the status of the ref, the singleRefSetter would
consider that it did not set the ref, and so shouldn't unset it, causing
it to incorrectly stay keep the element, while in multiRefSetter, the
opposite problem occured: the count would be 0 on removal, causing it to
believe that it was the first call in the corresponding patch that
affected the ref, when in fact, the closure is already stale, because it
was created from the previous render, and the fresh multiRefSetter from
the latest render may already have been called by an element with that
ref that came earlier in the template.

This commit changes the ref setting strategy to work around the issue of
stale closures: we define a setRef method on ComponentNode that is
always called, this method ignores calls with `null`, meaning that the
refs object on the ComponentNode never reverts to a null value for any
key. Instead, the useRef hook will check whether the element that the
ref points to is still mounted, and return null if not.
2023-03-06 15:17:14 +01:00
Géry Debongnie 7ac81ed5fe [FIX] compiler: call translate function with correct string
Before this commit, the parser would remove all consecutive white spaces
for text nodes. After that, the code generator would call the translate
function with the resulting string, which then is different than what we
would expect.

With this commit, we make sure we apply the translation before removing
the additional whitespace. To do that, we have to move the code
processing the string from the parser into the code generator, which
actually makes sense, as the parser should only collect all useful
information without applying too much logic.

closes #1351
2023-03-06 14:52:25 +01:00
Géry Debongnie cdad48d3a6 [FIX] compiler: properly handle readonly attribute/readOnly property
Before this commit, Owl template compiler would handle readonly
attribute as readonly properties. But this is incorrect, since the
property is actually named readOnly.

With this commit, we make sure that readonly AND readOnly are both
interpreted as the `readOnly` property. This is due to the fact that
QWeb does not discriminate between attribute and properties, so we have
to infer which is which.

closes #1362
2023-03-01 12:53:37 +01:00
Géry Debongnie f892929c80 [REF] blockdom,compiler: implement properties
Before this commit, properties were just handled as a special case of
attributes. But it does not make that much sense, since they are
different. For example, the `readOnly` property does not have the same
name as the `readonly` attribute.  The confusion probably comes from the
fact that QWeb does not distinguish between property and attributes, so
Owl has to infer which one is which.

With this commit, we introduce a `block-property` directive in blockdom,
and change the compiler to use it in emitted code. It has the additional
benefits of slightly shrinking the runtime code, since the `isProp`
function can now be located in the compiler.
2023-03-01 12:53:37 +01:00
Géry Debongnie f0fb3ab64e [REF] tests: move properties tests in own file 2023-03-01 12:53:37 +01:00
Samuel Degueldre a35b9814c0 [FIX] compiler: dynamic value on inputs doesn't turn 0 into empty string
In #1161, we fixed blockdom treating 0 as falsy when patching a value,
which would result in an empty attribute. It turns out that there is
another place where we had the same fallback, which is when we compute a
dynamic attribute value, so while blockdom had the ability to set the
value to 0, when using a dynamic attribute value we would never give it
0 as a value. This commit changes the fallback strategy for dynamic
attribute values to be the same as the one in blockdom.

closes #1358
2023-02-24 16:22:24 +01:00
Géry Debongnie 276c8a0295 [REL] v2.0.7
# v2.0.7

 - [FIX] compiler: t-key and t-ref together
2023-02-20 09:44:36 +01:00
Lucas Perais 0717fe241d [FIX] compiler: t-key and t-ref together
Have a t-ref on a DOM node with a t-key.
Change the t-key.

Before this commit, the old block removed its element from the component's refs *after*
the new block had been mounted, meaning that in effect, the resulting
ref at the end of the whole patch was null.

After this commit, we only remove an element from the component's ref if that very same
element was indeed the ref. (otherwise it means someone else has changed the ref.)
2023-02-20 09:42:16 +01:00
Géry Debongnie 1291f1f175 [REL] v2.0.6
# v2.0.6

 - [IMP] devtools: provide access to Fiber and RootFiber
 - Bump shelljs and git-rev-sync
 - [FIX] props validation: do not subscribe to props keys
 - [FIX] reactivity: only show key in subscription if observed by callback
 - [FIX] components: stop rendering stale t-component when delayed
2023-02-17 14:31:18 +01:00
Géry Debongnie 6c0a3525c8 [IMP] devtools: provide access to Fiber and RootFiber
The devtools extension needs to hook itself into some internal functions of
owl, and to do that, it needs a reference to Fiber and RootFiber
classes.
2023-02-17 14:20:03 +01:00
dependabot[bot] 13241422e9 Bump shelljs and git-rev-sync
Bumps [shelljs](https://github.com/shelljs/shelljs) to 0.8.5 and updates ancestor dependency [git-rev-sync](https://github.com/kurttheviking/git-rev-sync-js). These dependencies need to be updated together.


Updates `shelljs` from 0.7.7 to 0.8.5
- [Release notes](https://github.com/shelljs/shelljs/releases)
- [Changelog](https://github.com/shelljs/shelljs/blob/master/CHANGELOG.md)
- [Commits](https://github.com/shelljs/shelljs/compare/v0.7.7...v0.8.5)

Updates `git-rev-sync` from 1.12.0 to 3.0.2
- [Release notes](https://github.com/kurttheviking/git-rev-sync-js/releases)
- [Commits](https://github.com/kurttheviking/git-rev-sync-js/compare/v1.12.0...v3.0.2)

---
updated-dependencies:
- dependency-name: shelljs
  dependency-type: indirect
- dependency-name: git-rev-sync
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-02-17 11:42:38 +01:00
Géry Debongnie 8f2c7f24d7 [FIX] props validation: do not subscribe to props keys
In dev mode, owl inserts an additional props validation step. Before
this commit, the validation would iterate on all key/value pairs of each
props. If the props is reactive, this has the unfortunate side effect of
subscribing the component to each of the keys, even though it should not
be.

This commit avoids the issue by only validating the raw object.
2023-02-09 13:34:07 +01:00
Samuel Degueldre fed9cc467f [FIX] reactivity: only show key in subscription if observed by callback
Previously, the getSubscriptions debugging utility returned all observed
keys for a given target, instead of only the keys observed by the
callback it received as argument. This commit fixes that issues.
2023-02-09 10:13:41 +01:00
Samuel Degueldre 33174b301b [FIX] components: stop rendering stale t-component when delayed
Previously, if the value of a t-component directive changed, but there
was already a scheduled render for the component before that change, the
rendering of the existing component would get delayed (as it should),
but after the parent's rendering was complete, the old component which
will be destroyed during the patch would still get rendered, despite
being stale. This can cause crashes if that component relies on state
that no longer exists.

This was caused by the fact that when rendering, we check the parent
chain for an active render, and also check that the component still
exists in the parent's fiber childrenMap (ie, we know that the upcoming
patch is not about to destroy the component). To do this, we use the
component's parentKey, but in the case of t-component, the parentKey for
both possible components is the same, causing the stale component to
incorrectly believe that it's not about to be destroyed, by finding the
next component in the childrenMap under the same key.

This commit fixes that by prepending the component's name to the
parentKey, meaning that if the value of the t-component changes, so will
the key, and the render will be further delayed until the new state is
patched, at which point the stale component will be destroyed and the
following attempt to render will be cancelled as expected.

The choice to use the component's name is to simplify the
implementation, this means that if using t-component and switching
between components that have the same class name, this protection will
not work. The alternative would be to generate a unique id for the
component class, eg with a WeakMap, but this both complicates the
implementation and adds runtime overhead, for a case that is likely
extremely rare. We are open to refine the implementation should this
problem occur in practice.
2023-02-06 11:11:42 +01:00
Samuel Degueldre ea5d2be502 [REL] v2.0.5
# v2.0.5

 - [FIX] reactivity: improve performance for long-lived reactives
2023-01-27 15:29:07 +01:00
Samuel Degueldre 4a761a7403 [FIX] reactivity: improve performance for long-lived reactives
Previously, when having a long lived reactive object and writing a lot
of keys to it, clearing the reactive subscriptions on that object would
slow down as time went on. This is because when clearing a target's
subsctiptions for a callback, we look at all the keys that are observed, and for all
the observed keys, we remove the callback from the set of callbacks
observing that key. The problem arises from the fact that after doing
that, even if the set of callbacks observing that key is now empty, we
don't remove the key from the observed keys, meaning that any further
clearing of subscriptions will have to iterate over that key to attempt
to clear the callbacks even if there are none.

This commit fixes this problem by simply removing the key from the
observedKeys if there are no longer any callbacks observing it.

This commit also improves performance for bare reactives (reactives
created with no callback). The initial implementation simply creates a
default empty callback when creating a reactive, and treats it like any
other, meaning it can observe keys and be notified of changes even
though we know in advance that it does nothing. This can compound with
the previous issue when you're doing a lot of manipulations on a bare
reactive internally for the sole purpose of notifying outside observers,
as this creates a lot of useless work in the reactivity system.
2023-01-27 09:34:55 +01:00
Lucas Lefèvre 8702db03fb [FIX] tools: allow to pre-compile templates with - in their name
Compiling a template with a dash ("-") in its name generates an
invalid function name in the compiled code.

A template named `"my-component"` leads to the function
`function my-component(app, bdom, helpers) { ... }` which has an
invalid name.

closes #1333
2023-01-25 07:56:30 +01:00
Samuel Degueldre b2685b6709 [IMP] tools: pull playground before trying to publish
Previously, if you were not the last person to publish to the
playground, your playground branch would be behind the remote and trying
to push to it would fail.

This commit attempts to pull the changes before updating owl so that
even if you were not the last person to push to the playground, as long
as the pull is a fast-forward, publishing to the playground won't fail.

This commit also adapts some of the status number manipulation to use
bitwise or instead of addition, since return status code can be both
positive or negative and may cancel one another. Using bitwise or
ensures than any non-zero code will make the status non-zero and stay
that way.
2023-01-23 12:39:50 +01:00
Samuel Degueldre c30678f3ea [REL] v2.0.4
# v2.0.4

 - [IMP] app: expose live apps for the devtools
 - [FIX] compiler: support t-model radio group in t-foreach
 - [IMP] runtime: improve useExternalListener typing
2023-01-23 12:21:13 +01:00
Samuel Degueldre 6ca6717965 [IMP] tools: release scripts creates a template for release notes
This template contains the release version as a markdown title followed
by a markdown list with all the commit titles since the previous
release.
2023-01-23 12:19:14 +01:00
Julien Carion ad4adb930e [IMP] app: expose live apps for the devtools
This commit exposes owl apps in a global variable so that the owl
devtools can hook themselves on these apps. While the devtools are not
yet ready to be merged, exposing the apps will allow us to test the
devtools in production scenarios while polishing the development of
them.
2023-01-23 11:40:02 +01:00
Lucas Perais cea82e945d [FIX] compiler: t-model supports radio group in t-foreach
Have a radio group defined inside a t-foreach:
```xml
  <t t-foreach="values" t-as="val" t-key="val">
    <input name="radiogroup" t-att-value="val" t-model="state.radioGroup" />
  </t>
```

Before this commit the algorithm that set the "checked" attribute on the current active
radio button according to the state did not support having a dynamic value (`t-att-value`)

After this commit, this use case works as we go look in the dynamic attributes too.
2023-01-20 09:26:54 +01:00
Samuel Degueldre a69f8a39e7 [IMP] runtime: improve useExternalListener typing
Previously the type of the target for useExternalListener was
HTMLElement or Window, this makes document an invalid target. Here there
is no reason to use the EventTarget interface instead, as
useExternalListener only uses methods from that interface and should
work with any event target.

Closes odoo/owl#1323
2023-01-18 13:03:23 +01:00
Géry Debongnie 316eb06279 [REL] v2.0.3
# v2.0.2

Some small bug fixes

- fix: compiler: correctly escape backslashes when emitting block string
- fix: reactivity: don't subscribe to keys when making reactive
- fix: t-call-context: fix capture making component available in ctx
- fix: t-call-context: make `this` unavailable in rendering context
2023-01-12 16:29:11 +01:00
Samuel Degueldre df59ec49ae [FIX] t-call-context: make this unavailable in rendering context
t-call-context is a feature that's supposed to mask the rendering
context completely, but currently the component remains available
through `this`.

This commit stops treating `this` as a reserved word, so that it's
compiled to a lookup in the rendering context, and adds `this` to the
rendering context when binding the component's rendering function. With
these changes, `this` behaves the same as before when outside a
t-call-context, but when the rendering context is overriden, the
template can no longer access `this`. `this` still represents the
instance of the component inside of the rendering function since it's
needed by owl internally.

A side-effect of this change is that now the rendering context is no
longer the instance of the component by default, but is always an object
with the component in its prototype chain. This was already the case
before in some contexts (eg inside t-foreach, or inside components with
a t-set/t-call anywhere in its template). This can cause issues in rare
cases when a component method was called directly on the rendering
context, as before this change, the method's bound this would be the
component instance (except in a t-foreach, component with a
t-set/t-call, etc), while after this change it is now never the
component instance. When the method only reads on `this` there is no
issue as all the components properties are available on the rendering
contexts, but setting a value on `this` will write on the rendering
context and not the component which is likely a mistake.

While this is a breaking change, simply adding a t-set/t-call to any
template would break components that would be broken by this change,
with this in mind we decided to make this change anyway so that
developers get the error as early as possible in the development cycle
rather than having a seemingly inocuous change break code under them.
2023-01-12 09:38:22 +01:00
Samuel Degueldre 2a008a8679 [IMP] tooling: add eslint ci step to avoid stray .only and debugger 2023-01-11 15:47:09 +01:00
Samuel Degueldre 3d40533de1 [FIX] t-call-context: fix capture making component available in ctx
Previously, when using a component with a slot within a t-call with
t-call-context, the component would become available again inside the
slot despite the t-call-context. This was caused by the fact that the
capture helper function creates an object with the component as its
prototype which is incorrect. It should just use the previous context as
its prototype.
2023-01-09 09:28:10 +01:00
Samuel Degueldre 39329f80b2 [FIX] reactivity: don't subscribe to keys when making reactive
When attempting to create a reactive object, we first check if the
target can be made reactive, this is done with Object.toString, which
internally reads the Symbol.toStringTag on the underlying object. When
trying to make a reactive object from another, for example when
reobserving a reactive or when reading a reactive object from the
context of another, this would read the subscribe the original object to
the Symbol.toStringTag property.

This commit fixes that by calling Object.toString on the underlying
target object where applicable.
2022-12-08 14:22:39 +01:00
aab-odoo 203ac7ac66 [IMP] doc: avoid future tense 2022-12-05 11:28:54 +01:00
Samuel Degueldre 530c2f9e4c [FIX] compiler: correctly escape backslashes when emitting block string
Previously, when a template contained backslashes, they were not escaped
when creating the blockstring, meaning they would be interpreted as an
escape sequence within the JS string. This means that backslashes
preceding most characters were completely ignored and didn't end up in
the final block, double backslashes were collapsed to a single one, and
backslashes that constituted valid escape sequences in JS would be
treated as those (eg, \n would be a newline).

When creating a JS string expression from a string value, all characters
with special meaning in JS should be escaped, we were correctly escaping
backticks as these would unexpectedly close the string if not escaped,
but forgot to escape backslashes. This commit fixes that.

closes #1300
2022-12-05 11:06:06 +01:00
Bruno Boi ef8baa23d7 [REL] v2.0.2
# v2.0.2

- fix: compiler: do not look up ComponentNode in the context
- fix: t-model takes precedence over t-on-input
- fix: reactivity: fix issues with reactive objects in proto chain
2022-11-29 15:10:51 +01:00
poma-odoo acfcc5677a [FIX] documentation, incorrect example of toRaw 2022-11-29 15:02:09 +01:00
Samuel Degueldre f6e8aff725 [FIX] reactivity: fix issues with reactive objects in proto chain
Previously, when there was a reactive object in the prototype chain of a
different object, it would get notified of the first write to a property
that existed on the reactive object but did not yet exist on the other
object, despite the value of that property not actually getting written
to the reactive and hence the value not getting changed.

This was caused by the fact that we assumed that Reflect.set would set
the value on the target, when in fact, the value is set on the object
that underlies the `receiver`. When a reactive object is part of the
prototype chain, the first write on a key triggers the set trap but the
receiver is not the reactive object, and so Reflect.set doesn't modify
the target, but adds the new key to the object that's lower in the
prototype chain.

This commit fixes that by actually reading the value from the target
instead of assuming that it was changed by Reflect.set

This commit also removes the special symbols SKIP and TARGET, as there
is no reliable way to check whether these keys are present on the object
itself or on its prototype chain, which can cause issue when trying to
create reactive objects from objects with other reactive objects in
their prototype chain, or to create reactive objects from objects with
non-reactive objects in their prototype chain. To solve this problem, we
simply use a WeakMap that maps reactives to their targets, and a WeakSet
that contains all skipped objects.
2022-11-29 14:59:05 +01:00
Géry Debongnie 4a5316ced5 [FIX] t-model takes precedence over t-on-input
With this commit, we make sure that the code for t-model is run before
t-on-input event handler.  This is useful to make sure that the state
reflected by t-model is up-to-date.

closes #1295
2022-11-22 12:57:36 +01:00
Samuel Degueldre 9a5edb4590 [FIX] compiler: do not look up ComponentNode in the context
With the introduction of t-call-context, there is now no guarantee that
the ComponentNode can be found in the rendering context, any attempt to
do so can crash when combined with t-call-context. This commit fixes
that by using `this` instead, which in compiled templates refers to the
component that is being rendered.
2022-11-22 09:53:40 +01:00
tom hunkapiller 3d49daedcd [IMP] app: throw error when static components key is missing in parent
This commit improves the error message that's thrown when a static
component definition is missing, as outlined in issue #1286.
2022-11-10 11:59:34 +01:00
Samuel Degueldre 620e41daa1 [IMP] doc: improve reactivity documentation 2022-11-02 11:17:04 +01:00
Ronald Portier de84075c11 [DOC] Add a notice to step 9
There are two deleteTask functions in step 9. This will make sure the developer/student
does not miss one of those.
2022-10-31 10:01:39 +01:00
Bruno Boi 9fe8e93980 [REL] v2.0.1
# v2.0.1

- fix: runtime: correctly throw an error for duplicate object keys
- fix: parser: give t-set-slot="default" priority over the content
- fix: blockdom: correctly reorder children in heterogeneous t-foreach
- fix: portal: correctly move portal content when target is after it
- fix: blockdom: fix event_catcher traceback when a parent component has an empty child
2022-10-21 10:00:06 +02:00
Bruno Boi bd199971bd [FIX] blockdom: fix event_catcher traceback
When a parent component has an empty child with a t-on
and an event is triggered inside the parent, blockdom
checks if there is an event_catcher to call.
Doing so, an empty child would cause an error.

This commit fixes that.
2022-10-21 09:50:10 +02:00
Samuel Degueldre 6f23b18cab [FIX] portal: correctly move portal content when target is after it
Previously, when trying to mount a portal into a target that would be
mounted in the same render as the portal itself, the portal content
could not be mounted correctly. In a previous attempt to fix it, a
mistake was made while writing the test causing us to incorrectly
believe in now worked, when in fact, it would just move the portal
content to the end of its parent but without changing it.

This commit fixes the issue by making the `moveBeforeDOMNode` method of
VNodes accept a second optional parameter which is the parent in which
the element should be moved, defaulting to the current parent. This
results in identical behaviour when a parent is not specified, but when
it is, the VNode is "reparented" to the passed parent, which is what is
now done by the Portal
2022-10-20 09:24:08 +02:00
Samuel Degueldre 2c244aa31a [FIX] blockdom: correctly reorder children in heterogeneous t-foreach
Currently, the `moveBefore` method on VNodes assumes that the `other`
VNode it receives is of the same type, and that the entire VNode tree
below that other VNode has the exact same structure. While this is
correct in most cases, it breaks down when there is a VToggler somewhere
in the VNode tree, as the structure below a VToggler can be very
different from the structure below another VToggler that was created
from the same compiled code. For example, two iterations of a t-foreach
that contains a <t t-component="..."/> may spawn different components,
and different components obviously have different structures.

One way to fix this is to remove the assumption that the structure of
the `this` block tree in moveBefore is the same as the structure
of the `other` block tree, and instead, always give the concrete DOM
node before which we want to move the current VNode instead of giving it
a VNode and an afterNode as a fallback. One problem with this solution
is that it degrades performance in the "standard" case, where a
t-foreach contains no VToggler anywhere in its block tree, as retrieving
the first concrete DOM node requires calling firstNode() which
recursively traverses the entire tree.

To avoid this performance penalty in the standard case, we opt to only
go down this route whenever we encounter a VToggler when calling
`moveBefore`. This requires that we maintain two separate methods, one
to move a VNode before another VNode of assumed similar structure, which
is basically the current implementation of `moveBefore` for all VNode
types except VToggler, and one implementation that moves a VNode before
a concrete DOM node. This method needs to be implemented for all VNode
types, as all VNode types can be descendants of a VToggler. This method
will only be called from one place: the `moveBeforeVNode` method of the
toggler, which is the point where we realize that the assumption of
identical structure breaks down.

Co-authored-by: Bruno Boi <boi@odoo.com>
2022-10-19 13:13:49 +02:00
Samuel Degueldre ba1a270c93 [FIX] parser: give t-set-slot="default" priority over the content
Currently, if a component has a default slot defined with t-set-slot,
and also content that compiles to something (eg, text or even a comment
node), the content takes priority over the t-set-slot. As t-set-slot is
more explicity, it should have priority.
2022-10-10 20:33:18 +02:00
Samuel Degueldre d546244fc3 [FIX] runtime: correctly throw an error for duplicate object keys
Currently when checking for duplicate keys, we insert the value of the
key as is in a set then check for unicity against those. When the key is
an object, we check for duplicates based on object identity, whereas the
keys are used by owl as strings, and so using objects can cause
duplicate key errors that do not throw correctly but crash in the owl
internals.

This commit fixes that by making the duplicate checking code serialize
the key to string before insertion and when comparing against existing
keys.
2022-10-10 13:53:11 +02:00
Géry Debongnie a1f22829c1 [REL] v2.0.0
# v2.0.0

Finally the official v2.0.0 release is ready. There are no feature nor fixes since
last beta release, because it is stable.

Thank you to everyone who contributed.

## Changelog

Owl 2.0 is a large improvement over 1.0. It brings a lot of new features, improvements,
and better APIs.  The most important changes are:

- a completely overhauled slot API (in particular slot scopes, ...)
- a new reactivity system, similar to Vue. In particular, if props are equals, then
  a sub component is not updated.
- new rendering engine, based on blockdom. This makes Owl much faster
- support for fragments: a template can have an arbitrary number of roots

A detailed changelog can be found [here](CHANGELOG.md).
2022-10-07 15:27:58 +02:00
Géry Debongnie 64bad25762 [REL] v2.0.0-beta-22
# v2.0.0-beta-22

- fix: t-call: nested t-call with magic variable 0
- fix: prevent crash in case with t-foreach, t-out and components
2022-09-29 09:17:06 +02:00
Géry Debongnie 7ab34c5ca5 [FIX] prevent crash in case with t-foreach and t-out with components
The t-out directive is compiled internally into a LazyValue, which
represents a value that may or may not be created sometimes in the
future.  It can also be reused more than once, and this is where there
may be an issue: if a component is contained in the lazyvalue, it needs
a unique key (coming from the t-foreach) to be properly indexed in the
parent children map.  However, the LazyValue does not keep the key
information, so it is not able to provide it to its content.

The fix is then quite clear: the LazyValue class should store the key
information, and provides it to its content.  This allows the LazyValue
to be used multiple times, in any place in a template.

closes #1270
2022-09-29 08:28:38 +02:00
Géry Debongnie 669fd622ec [FIX] t-call: nested t-call with magic variable 0
Before this commit, the template compiler would guess the next block id
that will be generated when compiling the body of a tcall.  This is
correct IF there are not nested t-call, but otherwise wrong, because the
next block id could be mixed up: the first t-call would save the next
block id (let's say n), then the inner t-call would also save the same
block id (so, n), will then generate its own block (n+1), then the outer
t-call would use the block n index instead of n+1

The best fix, in my opinion, is to make sure we get the next block var
name, so we do not have to guess. To do that, each compile block type
function needs to properly return the information.

closes #1267
2022-09-28 09:31:41 +02:00
Géry Debongnie ab72cdddde [REL] v2.0.0-beta-21
# v2.0.0-beta-21

- fix: prevent side effects at template compilation
- fix: props validation: does not crash with t-call-context
- fix: make t-portal work in all cases
- fix: make props validation work through slots
2022-09-26 15:44:11 +02:00
Géry Debongnie 17fb33475c [FIX] props validation: make it work through slots
A recent commit fixes the props validation code to make it work
regardless of the rendering context (important with the recent
t-call-context directive). Unfortunately, it then breaks props
validation through slots, because it assumed that the parent node in the
virtual node was the parent of the component, but it is not necessarily
true.

To fix this, we can use a simple property of the template functions:
they are bound to the current instance of the component, so we can
simply use "this"
2022-09-26 15:17:58 +02:00
Géry Debongnie ab29b896eb [FIX] portal: make it work in all cases
Before this commit, the portal wouldn't work when its target is created
after the portal content, since it wouldn't be able to mount the dom at
the correct location.

With this commit, we work around the issue by mounting the portal
content at the portal location, then when the Portal component is
mounted, moving it to its correct location.

The big downside with that approach is that the portal content is
(sometimes) rendered and mounted at a location, THEN mounted in another
location. I think that it is most of the time not an issue, but one
could argue that it is inconsistent: some specific code could work at
one point, then fail in a different very similar situation (for example,
iframes don't support very well being moved around).  On the flip side,
having the portal work as expected is very useful, and may be worth the
tradeoff.

closes #1250
2022-09-26 12:01:12 +02:00
Géry Debongnie d5ed25cd19 [FIX] props validation: does not crash with t-call-context
The code for props validation assumed that the rendering context was a
component.  This was actually true when it was written, but is no longer
true since t-call-context was introduced.

Because of that, it would crash when trying to access the internals of
the component, such as the static components object.

The fix is simple: instead of passing the context to the props
validation code, which can now be anything, we pass the component node,
which is guaranteed to give a reference to the component (and also to
the app).  This also make the code slightly simpler.

closes #1261
2022-09-24 08:34:22 +02:00
Géry Debongnie c4f0f17b9b [FIX] blockdom: prevent side effects at block compilation
When creating the template node for a block, we create htmlelements and
set their (static) attributes.  But this can have side effects. For
example, setting the src attribute for an img element will trigger a
request to fetch the image.

We avoid that issue by simply setting the html element template node
inside a <template/> element.

Note that I don't really see how to test this fix in jest: we don't have
a real browser, and no real way to check for this side effect.

closes #1257
2022-09-21 13:59:13 +02:00
Florent Dardenne - dafl@odoo d27455e9f2 [IMP] doc: explicit useEffect first parameter
The `useEffect` has two parameters:
* The `effect` function
* The `computeDependencies` function

The `effect` function always take as parameters the result
 of the `computeDependencies` function.

Expliciting this allows to better understand the `useEffect`
behaviour and the following example in the doc:

```
useEffect(
    (el) => el && el.focus(),
    () => [ref.el]
  );
```
2022-09-09 20:24:56 +02:00
Géry Debongnie 6ef38676c4 [DOC] doc: fix broken link and update roadmap 2022-09-09 09:45:05 +02:00
Géry Debongnie b51756f356 [REL] v2.0.0-beta-20
# v2.0.0-beta-20

- app: properly rethrow unhandled errors
2022-09-09 09:26:12 +02:00
Samuel Degueldre cfdf7caa50 [IMP] app: rethrow errors that were not handled
This commit makes it so that when an error occurs in an owl app and none
of the registered error handlers are able to handle it, we rethrow the
error instead of just logging it to the console and swallowing it. This
allows users of owl to handle errors that happen in owl applications by
using event listeners for error and unhandledrejection events on the
window.
2022-09-09 09:23:32 +02:00
Florent Dardenne - dafl@odoo a5a6a592c1 [FIX] tutorial_todoapp: fix the final code mount issue
In app.js, `mount(Root, document.body, { dev: true, env });`  crash because `body` is not available yet.
Therefore, moving the script into the body fix the issue.
2022-09-08 13:30:38 +02:00
Géry Debongnie d0d7482b0f [REL] v2.0.0-beta-19
# v2.0.0-beta-19

- fix: events: correctly call handlers in iframes
2022-09-06 12:13:25 +02:00
Samuel Degueldre 8fe4c0c76e [FIX] events: correctly call handlers in iframes
Previously, event handlers would not work when an app was mounted in an
iframe, this is caused by a guard in the event handler that checks that
the target element is still in the document, but it doesn't check
against the correct document in the case of an iframe.

This commit changes the check to check against the target's
ownerDocument.
2022-09-06 12:06:59 +02:00
Géry Debongnie c1afaeb92a [REL] v2.0.0-beta-18
# v2.0.0-beta-18

- fix: allow multiple occurrences of same slot in different locations
2022-09-02 14:57:18 +02:00
Géry Debongnie 3883cec079 [FIX] slots: prevent crash when using same slot in different locations
Before this commit, a crash could occur when a component with no props
is defined in a slot, and that slot is conditionally displayed in
multiple locations.

The reason for that is that the key provided to the callSlot function
was identical, so from the perspective of the component function, it was
not possible to make the difference between a component located in
either places.  With this commit, we make sure that a unique key is used
when a slot is reused in a template (or if it is dynamic, because in
that case, we have no idea at compile time if it will be unique or not)

closes #1246
2022-09-02 12:12:00 +02:00
Géry Debongnie 9cb74d619b [REL] v2.0.0-beta-17
# v2.0.0-beta-17

- imp: types: expose ComponentConstructor for typing purpose
- fix: compiler: fix falsy values for properties not keeping input empty
- fix: app: allow mounting owl apps in iframe
2022-09-01 15:41:33 +02:00
Samuel Degueldre a93f015795 [FIX] app: allow mounting owl apps in iframe
Previously, attempting to mount an app in an iframe would crash, saying
that the target is not a valid DOM element, this is because instanceof
checks do not work cross-frame as global objects do not have the same
identity in frames as with the main window. This commit fixes that by
making sure the target is an instance of HTMLElement of the
corresponding window, and checks that the corresponding document body
contains it.
2022-08-17 10:05:46 +02:00
Samuel Degueldre 02a187d80b [FIX] compiler: fix falsy values for properties not keeping input empty
Recently, we made it so that when a component is rendered, it always
updates the property values for computed properties. This was done by
wrapping the value in a String or Boolean object. One issue with this is
that wrapping a falsy value in a String doesn't yield an empty string,
but a string containing the value as text (eg new String(undefined) ->
"undefined"), which causes the value to not remain empty as per the
spec. This commit fixes that by adding a fallback to the empty string
for falsy values before converting to a String object.

closes: #1236
2022-08-05 09:50:38 +02:00
Rémi Rahir d3b0d1971e [IMP] types: expose ComponentConstructor for typing purpose
We have been using this type in o-spreadsheet since https://github.com/odoo/o-spreadsheet/pull/1187
but the new typing file (https://github.com/odoo/owl/pull/1207) does not include it.
It would be useful to allow us to bump or version of owl witouht having to resort
to long aboslute paths (i.e. import from `@odoo/owl`and not
`@odoo/owl/dist/types/runtime/component@ everywhere).
2022-07-25 14:34:14 +02:00
Géry Debongnie b90aa0e23a [REL] v2.0.0-beta-16
# v2.0.0-beta-16

Notes

- fix: components: fix cause left unset when thrown object is not Error
2022-07-22 09:43:43 +02:00
Samuel Degueldre 163366997c [FIX] components: fix cause left unset when thrown object is not Error
Previously, when wrapping errors in wrapError, if the error was not an
actual error object, we wouldn't set the cause property on the wrapping
error correctly. The "instanceof Error" check is simply there so that we
can know whether we can add the original errors message to the wrapping
error, but the line that sets the error's cause was mistakenly moved
into that condition.

This commit also fixes the wrapping error's message in the case of
non-Error objects, to avoid having "the following error occurred in
hookname:" with nothing after the colon which is confusing/misleading.
2022-07-22 09:21:19 +02:00
Géry Debongnie 588b655c11 [REL] v2.0.0-beta-15
# v2.0.0-beta-15

Notes

- fix: lifecyle_hooks: correctly wrap errors in async code
- imp: use a custom error class for all errors thrown by owl
- fix: package.json: remove browser value
- ref: component_node: slightly simplify code
2022-07-20 10:02:24 +02:00
Géry Debongnie f5d5273c25 [REF] component_node: slightly simplify code 2022-07-20 09:57:27 +02:00
Géry Debongnie 9fd662fdce [FIX] package.json: remove browser value
As far as I can tell, the browser value overrides the main value in many
cases.  But then, we don't want to use the iife format, since it don't
work well with bundlers. This commit fixes the issue by simply removing
the key, so the main entry will be used instead.

maybe fixes #1181
2022-07-20 09:56:39 +02:00
Samuel Degueldre 7786077921 [IMP] *: use a custom error class for all errors thrown by owl
This commit makes all errors thrown in owl use a custom error class. The
main point of this is to always wrap user-code errors that happen during
the owl lifecycle so that they can be treated uniformly in onError by
checking the cause property, and also allows user code to differenciate
owl errors from non-owl errors reliably at runtime.
2022-07-18 15:40:14 +02:00
Aaron Bohy 30bc605c84 [FIX] lifecyle_hooks: correctly wrap errors in async code
Before this commit, wrapping an error occurring in async code
would result in an unhandledpromise exception, because we created
another promise, that would be rejected and that we didn't catch.
2022-07-18 15:40:14 +02:00
Géry Debongnie d1118455aa [REL] v2.0.0-beta-14
# v2.0.0-beta-14

Yes, there is no beta-13 release...

## Fixes:

- [FIX] compiler: better handle update of properties with same value
2022-07-08 16:11:45 +02:00
Géry Debongnie f8073cb153 [FIX] compiler: better handle update of properties with same value
Before this commit, owl would incorrectly skip patching html properties
when the new value is the same as the value used in the previous render.
However, this is incorrect, since the user may have changed the value by
clicking on a checkbox, or changing some text in an input.

So, to be more correct, owl has to force the update whenever it
encounters a prop.  This is however hard to do without impacting the
main update loop, so we kind of work around the problem by using String
and Boolean instance, instead of primitive values.
2022-07-08 15:58:49 +02:00
Géry Debongnie 6c72e0a143 [REL] v2.0.0-beta-12
# v2.0.0-beta-12

- fix: compiler: properly handle t-set in t-if with no content
2022-06-29 11:12:59 +02:00
Géry Debongnie 382e3e4010 [FIX] compiler: properly handle t-set in t-if with no content
Before this commit, whenever Owl encounter a t-if, it generates an
anchor (a "hole") in the current block being compiled. However, in some
cases, the content of the t-if may not have any content at all, and the
anchor is then useless. Worse, the code generating the anchor generates
an index based on the number of sub blocks, but if there is no content,
the next anchor being created will have the same index, which then may
cause weird bugs.

A possible way to fix this could be to make sure we increment properly
the anchor index, but we could even do better: not having an anchor at
all.
2022-06-29 11:08:14 +02:00
Géry Debongnie 76c389a7a8 [REL] v2.0.0-beta-11
# v2.0.0-beta-11

Yet another release with some small fixes.

[FIX] fix some issues with t-out with falsy values, and with default values
[REF] app: slightly simplify the create component path
[IMP] compiler: add support for binary operators
[IMP] add support for t-call-context directive
[FIX] properly get component reference instead of context
[FIX] blockdom: fix crash when class object key has leading spaces
2022-06-28 15:28:12 +02:00
Géry Debongnie b9ba0abf41 [FIX] test: run prettier 2022-06-28 15:26:55 +02:00
Géry Debongnie 4ca37be7f3 [FIX] tests: update wrong snapshot
oups
2022-06-28 15:20:53 +02:00
Géry Debongnie d6667ddf2e [FIX] fix some issues with t-out with falsy values, and with default value 2022-06-28 15:10:11 +02:00
Géry Debongnie 6f86beeaf3 [REF] app: slightly simplify the create component path 2022-06-28 13:11:57 +02:00
Géry Debongnie 7f580a4e1d [IMP] compiler: add support for binary operators 2022-06-24 15:39:55 +02:00
Géry Debongnie c7459ef87b [IMP] add support for t-call-context directive 2022-06-22 16:15:54 +02:00
Géry Debongnie 5772b4e9e4 [FIX] properly get component reference instead of context
Before this commit, the generated code for the component directive was
using the current context as the place to look for static informations
(such as the sub components). However, it is not entirely correct, since
the current context may be different than the current component (which
is easily accessed by using the this variable).

Also, while doing this, we fix some issues in the t-set directive, which
as calling lazy values with the wrong this.
2022-06-22 16:15:54 +02:00
Samuel Degueldre e57e2ee378 [FIX] blockdom: fix crash when class object key has leading spaces
Previously, having a leading or trailing space caused
HTMLElement.classList.add to be called with an empty string (because we
are splitting on whitespace), which is not allowed and caused a crash.
This commit fixes that by trimming the keys of the class object in the
same way that we already do it for class strings.
2022-06-22 15:48:45 +02:00
Géry Debongnie 2e03332acd [REL] v2.0.0-beta-10
# v2.0.0-beta-10

- ref: compiler: remove useless ; in compiled output
- ref: move some code around
- imp: app: small scale perf improvement
- imp: app: add fast path for when component has no prop
- imp: validation: add support for value types
- fix: compiler: escape backticks in attributes
2022-06-22 10:33:12 +02:00
Aaron Bohy c16d7d52b1 [FIX] compiler: escape backticks in attributes
Before this commit, the generated code crashed if an attribute in
the template contained backticks. The compiler output something
like

```js
   let block1 = createBlock(`<div foo="`bar`"/>`);
```

The backticks are now properly escaped.
2022-06-22 10:22:31 +02:00
Géry Debongnie 9c4c3e3b83 [IMP] validation: add support for value types
This commit add supports for value types in prop validation. To describe
a value V type, one has to simply write {value: V}.

Note that this commit also improves the validation typing.

closes #1198
closes #910
2022-06-15 08:56:44 +02:00
Géry Debongnie 55ac43c1db [IMP] app: add fast path for when component has no prop 2022-06-13 09:51:31 +02:00
Géry Debongnie d046913a01 [IMP] app: small scale perf improvement 2022-06-13 09:51:31 +02:00
Géry Debongnie 0e6059467f [REF] move component function to app, improve some code 2022-06-13 09:51:31 +02:00
Géry Debongnie 51538c2fea [IMP] compiler: remove useless ; in compiled output 2022-06-13 09:51:31 +02:00
Géry Debongnie 83d4471048 [REL] v2.0.0-beta-9
# v2.0.0-beta-9

Fixes

- event: no crash when using t-on + modifier on slots/components
- component: fix props comparison code
- component: fix wrong behaviour when using t-on on t-component
- component: props values are own property of props object
- t-out: allow expressions evaluating as number
- compiler: add support for #{...} in string interpolation

Improvements

- slots: add support for t-props on slots props
- tooling: add another d.ts file
2022-06-09 14:32:13 +02:00
Simon Genin (ges) 8a967e5b2d [IMP] tooling: add another d.ts file 2022-06-09 14:21:34 +02:00
Géry Debongnie 385e118e58 [FIX] compiler: add support for #{...} in string interpolation 2022-06-08 10:54:30 +02:00
Géry Debongnie a3111eb9ca [FIX] t-out: allow expressions evaluating as number 2022-06-07 13:23:29 +02:00
Géry Debongnie 1fc88f626f [IMP] slots: add support for t-props on slots props 2022-06-07 09:30:45 +02:00
Géry Debongnie 5d5a530505 [FIX] component: props values are own property of props object 2022-06-03 16:41:31 +02:00
Géry Debongnie c7bd0ab85c [FIX] component: fix wrong behaviour when using t-on on t-component
Before this commit, using t-on on t-component was not correctly
implemented by owl: when more than one component shared the same
parentelement and have an handler with the same name, the second handler
would override the first (using an internal key). With this commit, we
simply recreate event handler for each instance of a catcher block. Note
that it means that using t-on on components is slightly slower now.

Also, this commit fixes an additional issue that was noticed: the
catcher block would not update its internal handler properly, so it
would not behave properly after being patched.

closes #1199
2022-06-03 16:12:56 +02:00
Géry Debongnie 31b57cbb40 [FIX] component: fix props comparison code
Before this commit, Owl had a bad interaction with the static
defaultProps code. The props comparison would be done with the new props
object (unmodified) and the current props object (with default props
applied), so the comparison would always return false, which in turn,
causes additional useless renderings.

This commit modifies component node to keep a reference to the
(unmodified) props object so we can compare it as expected.
2022-06-03 15:51:58 +02:00
Géry Debongnie 31fce0926c [FIX] event: no crash when using t-on + modifier on slots/components
closes #1185
2022-06-01 09:58:49 +02:00
Géry Debongnie b56a9c24cf [REL] v2.0.0-beta-8
# v2.0.0-beta-8

Fixes

- portal: allow use of expression to describe portal target
- compiler: fix issue with identifiers with same name
- reactivity: fix memory leak
- app: validate props for root component in dev mode

Improvements

- component: display nice error for wrong child component
- props_validation: have clearer error messages
- component: only useState on props that are already reactive
- compiler: add better support for "in" and "new" operators in templates
- misc: export the validate function
- app: add setting to warn if no static props object
- add static App.registerTemplate and update Portal to use it
- add basic infrastructure to buid owl-runtime without compiler
2022-05-31 14:25:06 +02:00
Géry Debongnie 6dcdb77eab [DOC] add informations on how to compile templates ahead of time
This may help people stuck on issue #1195. Note that the tooling is
still quite rough.
2022-05-31 14:00:01 +02:00
Géry Debongnie a7daef380a [REF] runtime: rename handler.ts -> event_handling.ts 2022-05-31 14:00:01 +02:00
Géry Debongnie 22a79cdedd [REF] reorganize file structure
in order to separate compiler/ and runtime/ code
2022-05-31 14:00:01 +02:00
Géry Debongnie e4b810c027 [ADD] add basic infrastructure to buid owl-runtime without compiler 2022-05-31 14:00:01 +02:00
Géry Debongnie b10a700381 [REF] add static App.registerTemplate and update Portal to use it
The goal is to get closer to the possibility of using Owl without the
compiler. This commit removes Portal dependency on the compiler, and
opens the way to register pre-compiled template functions.
2022-05-31 14:00:01 +02:00
Géry Debongnie 2b4d8874c7 [REF] simplify template definition 2022-05-31 14:00:01 +02:00
Géry Debongnie 98b58b505b [IMP] app: add setting to warn if no static props object
This can be helpful to track components that miss a static prop
description.

closes #1191
2022-05-24 13:52:42 +02:00
Géry Debongnie 586033fd95 [FIX] app: validate props for root component in dev mode
Before this commit, only sub components were validated.
2022-05-24 13:52:42 +02:00
Géry Debongnie 1fe0bf08b1 [IMP] misc: export the validate function
The props validation code is actually quite difficult to get right.
Also, it is sometimes useful to be able to validate an object against a
specified schema. Therefore, this commit exports the standalone validate
function as an utility function.
2022-05-24 13:52:42 +02:00
Géry Debongnie 4779707923 [IMP] component: rewrite props validation code
This commit reworks the props validation code in order to extract a
generic validate utility function. The validation should be more robust,
with better error messages, and at the same time, it supports `*` in a
shape object.

And as a bonus, it is now typesafe, and the static props object is now
typed.

closes #1190
2022-05-24 13:52:42 +02:00
Samuel Degueldre d917af4614 [IMP] compiler: add better support for "in" and "new" operators
Previously, the support for the "in" operator was iffy, and "new" was
not supported at all, "in" would fail when checking if a nested property
was in something else, as the leading space would be stripped, and "new"
would fail because the following space would be stripped.

This commit fixes that by preserving the significant whitespace where
necessary.
2022-05-19 10:08:48 +02:00
Samuel Degueldre 4c77132ae2 [IMP] component: only useState on props that are already reactive
Previously, components would automatically call useState on their props,
so that changes deeply within props would automatically cause the
component to be rendered. This can be useful when passing a piece of
state to children or descendants.

One problem with this is that all props implicitly become reactive, even
if the object that was passed as a props was not. The problem with that
being that since the original object is not reactive, any change made by
the parent will not go through the reactivity system and the children
won't be notified of the change, in essence, this reactive object is
essentially useless, while having a real cost: traversing reactive
objects creates more reactive objects, and those objects are all
proxies. This is expensive for basically no benefit, while also making
it more difficult to debug code that involves those objects.

This commit fixes that by only calling useState on objects that are
already reactive, allowing the usecase described in the first paragraph
without the drawbacks described in the second.
2022-05-18 08:46:27 +02:00
Géry Debongnie 114f21586e [DOC] doc: remove obsolete documentation on context
The Context api was retired in owl 2.0, but a documentation file was
kept alive. This commit removes it, to prevent confusion in the future.

Thanks zerone40 for the issue

closes #1180
2022-05-17 09:59:49 +02:00
Paul Morelle 32d8b23b9d [IMP] props_validation: have clearer error messages
With this commit, props validation error messages will include a more
developer-friendly error message, avoiding the need to investigate in
the Developer Tools why a complex props structure is invalid.
2022-05-17 09:35:15 +02:00
Samuel Degueldre a83731007a [FIX] reactivity: fix memory leak
The reactive cache should be a WeakMap from targets to another WeakMap
that associates callbacks to target. The second WeakMap was in fact a
map, and typescript did not complain because Map has compatible typing
with WeakMap. This commit fixes that.
2022-05-13 11:19:48 +02:00
Lucas Lefèvre 5c71744e19 [IMP] component: display nice error for wrong child component
If you declare a child component which is not actually a Component,
the error message is not very friendly and not very helpfull to find
what happens and which child component is wrong.

```
const ChildComponent = "not a component constructor";

class MyComponent extends Component {
    static components = { ChildComponent };
}
```

This commit improves the type declaration for those working with Typescript
and adds a runtime check for javascript codebases
2022-05-06 17:09:30 +02:00
Géry Debongnie d09771b04b [FIX] compiler: fix issue with identifiers with same name
Before this commit, there were 2 different ways of generating variable
identifiers. And it was possible to have a situation with two different
variable in a template with the same identifier, which caused a crash.

This commit ensures that we go through a unique helper method, so this
cannot occur anymore. Also, the code is slightly simpler.
2022-05-04 14:19:42 +02:00
Géry Debongnie 7137130c38 [FIX] portal: allow use of expression to describe portal target
Before this commit, the value of the `t-portal` directive was inserted
in the compiled template without being processed.
2022-05-04 09:07:58 +02:00
Samuel Degueldre 0cd66c8518 [REL] v2.0.0-beta-7
# 2.0.0-beta-7

- fix: concurrency: do not render delayed fibers when cancelled
- imp: allow duplicate templates if and only if they are the same
2022-04-27 11:08:25 +02:00
Samuel Degueldre 5d9cff0331 [IMP] app: allow duplicate templates iff they are the same
Previously, we used an option to allow duplicate templates, if that
option was passed, we would always replace the existing template with
the new template, and if it wasn't, we would always throw an error even
if the template's content was the same.

Allowing to replace a template with a different one is problematic, as
it may or may not have already been compiled, which may cause various
problems. On the other hand, if the template is the same, there is no
point in throwing an error, as we can just silently ignore the second
addition.
2022-04-27 10:40:19 +02:00
Samuel Degueldre 41f1262eb7 [FIX] concurrency: do not render delayed fibers when cancelled
Previously, if a fiber was delayed because one of its ancestors was
rendering, and that fiber was not a root fiber, it would be rendered
after all its ancestors had finished rendering even if one of those
ancestor renderings cancelled it.

This commit fixes that by simply checking that a delayed fiber is still
its component node's current fiber before rendering it.
2022-04-19 12:07:35 +02:00
Géry Debongnie 41344ef4ec [REL] v2.0.0-beta-6
# 2.0.0-beta-6

- fix: stricter check for the component.render deep argument
2022-04-11 11:01:27 +02:00
Géry Debongnie 7d14db7d31 [FIX] component: strict check of deep argument truth value
With this commit, we make sure that the `render` method was explicitely
called with the deep === true argument, instead of assuming that it is a
boolean.  This prevents errors when some unrelated value is given to the
render method. This could happen in some cases, such as

useBus(someBus, 'someevent', this.render)

In that case, the `useBus` code would simply call the this.render with a
customevent, which would be considered truthy before, and not anymore
2022-04-11 10:58:44 +02:00
Géry Debongnie 1179e84971 [REL] v2.0.0-beta-5
# v2.0.0-beta-5

- fix: compiler, components: allow empty slots with default content
- fix: issue with delayed renders being left pending forever
- fix: dynamic t-slot with scope bug
- fix: protect against errors in onWillDestroy
- fix: protect against user code executing in critical sections
- fix: concurrency issue (more robust handling of children per render)
- fix: prevent rendering destroyed children in some cases
2022-04-07 15:36:22 +02:00
Géry Debongnie 24b1ea7604 [FIX] components: prevent rendering destroyed children in some cases 2022-04-01 15:02:57 +02:00
Géry Debongnie 3e4ebb6378 [REF] component: slightly simplify code logic 2022-04-01 15:02:57 +02:00
Géry Debongnie 859748aed9 [FIX] concurrency issue (more robust handling of children per render)
Before this commit, the list of all children was managed at the level of
the root fiber, but this could cause issue when subfibers would be
reused. With this commit, we use the childrenMap object that exists on
each fiber instead.
2022-04-01 13:40:24 +02:00
Géry Debongnie fd13277e1d [FIX] component: protect against user code executing in critical section
Canceling a fiber may cause user code to be run, which means that some
new renderings could be scheduled, but this could interfere with the
current renderings!
2022-04-01 13:40:24 +02:00
Géry Debongnie 7fb166bd50 [FIX] component: protect against errors in onWillDestroy 2022-04-01 13:40:24 +02:00
Lucas Perais (lpe) decf42c742 [FIX] compiler, component: dynamic t-slot with scope
A little typo was preventing a dynamic t-slot with a scope
(`<t t-slot="{{ state.name }}" myScope="someValue" />`)
to work properly.

This commit corrects this.
2022-03-31 16:15:47 +02:00
Géry Debongnie 989b0d6709 [REF] improve children handling in components/fibers 2022-03-31 08:54:59 +02:00
Géry Debongnie 9b93521da4 [FIX] issue with delayed renders being left pending forever 2022-03-31 08:54:59 +02:00
Lucas Perais (lpe) de240b1ebc [FIX] compiler, components: allow empty slot
Before this commit, a t-set-slot that has no content was not even compiled, and thus not passed
to the component for which it has was defined

After this commit, we allow a t-set-slot to have no content (because it can have slot props)
2022-03-29 16:24:05 +02:00
Géry Debongnie 55dbc01a1b [REL] v2.0.0-beta-4
# v2.0.0-beta.4

- fix: useEffect properly handle errors in effect function
- imp: reactivity: add missing support for forEach method
- imp: component: add name property on nodes for debug purposes
- imp: component: emit warning when async hooks take too long
- fix: blockdom: t-att- correcltly sets the value to zero
- fix: reactivity: do not crash when reading reactive frozen objects
- fix: utils: fix calls to batched callback from within the callback
- imp: component: wait for parent rendering to be complete before rendering child
2022-03-29 15:49:50 +02:00
Géry Debongnie e3b1566943 [IMP] component: wait for parent rendering to be complete before doing child
This is a breaking semantic change.  With this commit, the UI is frozen
whenever owl is waiting for a parent to change

Also, this allows Owl not to render components that will be removed
later.
2022-03-29 15:45:27 +02:00
Géry Debongnie 828be28653 [REF] component: introduce RootFiber.setCounter and update scheduler
The goal is to be able to execute code whenever a root fiber is ready,
and before the next animation frame
2022-03-29 15:45:27 +02:00
Samuel Degueldre d80fad760c [FIX] utils: fix calls to batched callback from within the callback
Previously, calling the batched function from within the callback being
batched would fail as it would be treated as part of the same batch.
This commit fixes that by scheduling the reset of the "called" flag
before calling the callback. This means that all microtasks that were
already in the microtask queue when a batch is about to run are treated
as part of the batch, and all microtasks that will be added by the
callback are not.
2022-03-29 09:13:00 +02:00
Samuel Degueldre 7611ea6033 [FIX] reactivity: do not crash when reading reactive frozen objects
This crash was caused by the fact that Proxies *must* return the value of the
property on the target when that property is non-writeable and
non-configurable. Since the reactivity system always attempts to proxify the
value from the target, this crashes.

This commit fixes that by not proxifying such values. This however means that
from that point on, we have escaped the reactivity system and will not
subscribe to any changes in that object or its children.
2022-03-28 13:15:00 +02:00
NsL01 c7d515a6b3 [FIX] doc: fix minor errors in todo app tutorial 2022-03-25 10:34:00 +01:00
Samuel Degueldre d277039b14 [FIX] blockdom: t-att- correcltly sets the value to zero
In 3536f41f00 we added a fallback when setting a
property to a falsy value so that the property was set to the empty string. The
objective being to not get the string "undefined"/"null"/"false" as property
value. However, using t-att- to set a property to 0 is perfectly reasonable and
in fact quite common.
2022-03-18 14:24:54 +01:00
Samuel Degueldre 77ff5ee895 [IMP] component: emit warning when async hooks take too long
This commit adds a warning when an async hook
(onWillUpdateProps/onWillStart) takes longer than 3 seconds, as these
hooks block the rendering and patching of the application, it is rarely
desirable and often a sign of a deadlock. This warning will contain the
stack trace of the call to the hook to help in debugging.
2022-03-14 09:51:47 +01:00
Géry Debongnie 47c6d6cc3c [IMP] component: add name property on nodes for debug purposes
also, improves the implementation of subscriptions
2022-03-11 15:14:55 +01:00
Samuel Degueldre 0625b5883a [IMP] reactivity: add missing support for forEach method 2022-03-11 14:02:42 +01:00
Géry Debongnie 53ab54b1ec [FIX] useEffect: properly handle errors in effect function
Before this commit, if the effect function would throw, then the cleanup
function would not be properly assigned, which caused additional errors
later, when the cleanup code would try to call it.

closes #1149
2022-03-08 15:23:49 +01:00
Samuel Degueldre 4770b91faa [IMP] doc: document dev mode 2022-03-08 14:45:44 +01:00
Samuel Degueldre c356351de2 [REL] v2.0.0-beta.3
# 2.0.0-beta.3

- improve error message for tokenization errors
- fix a bug where errors during rendering were incorrectly reported
- add support for t-on on components and slots (t-slot and t-set-slot)
2022-03-08 12:47:36 +01:00
Géry Debongnie f04423da23 [FIX] playground: properly set dev flag in examples 2022-03-08 12:24:57 +01:00
Géry Debongnie b3062d29f1 [REF] parser: make AST definition more consistent 2022-03-08 12:24:57 +01:00
Géry Debongnie 56086242bb [IMP] compiler: add support for t-on- on t-slots and t-set-slots 2022-03-08 12:24:57 +01:00
Géry Debongnie 998ecbb337 [REF] compiler: introduce define helper, slightly refactor code 2022-03-08 12:24:57 +01:00
Géry Debongnie 50355e6a3d [IMP] component: add support for t-on on compnents 2022-03-08 12:24:57 +01:00
Samuel Degueldre 67f86a4ab8 [FIX] components: wrap onWillRender/onRendered hooks instead of renderFn
Previously, we were wrapping the entire renderFn in a try/catch, causing
errors during template execution to be caught and wrapped by
onWillRender/onRendered which is undesirable. Now we only wrap the hook
that's being registered.
2022-03-08 10:18:15 +01:00
Samuel Degueldre 14d2328c88 [IMP] compiler: improve error message for tokenization errors 2022-03-08 10:18:15 +01:00
Géry Debongnie e4fdd32f22 [REL] v2.0.0-beta.2
# 2.0.0-beta.2

- only log dev message once, instead of once per app
- add subscriptions getter in dev mode on component node
- fix: issue with missing renderings
- fix: env now preserves prototype chain
2022-03-03 16:21:57 +01:00
Géry Debongnie 8d1d0a2244 [FIX] app: make sure we maintain the correct prototype chain in env 2022-03-03 16:19:05 +01:00
Géry Debongnie 0457e5d4ed [FIX] component: missing renderings in some cases 2022-03-03 16:19:05 +01:00
Samuel Degueldre 8920b4b93a [IMP] component, reactivity: add subscription getter in dev mode
This allows to see which objects and which keys in those objects a
component is observing, so that issues with missing renders or extra
renders can be more easily diagnosed.
2022-03-03 10:33:39 +01:00
Géry Debongnie 6908102a72 [IMP] app: only log dev message once
Before this commit, it was logged for every app created, which is
annoying in odoo: because of the compatibility layer, there are many
apps being created.
2022-03-03 08:48:37 +01:00
Géry Debongnie d6348b8310 [REL] v2.0.0-beta.1
# 2.0.0-beta.1

First beta release! The last missing feature has been merged (support for
sets/maps/weakmaps in the reactivity system).
2022-03-02 13:28:50 +01:00
Géry Debongnie 79738e00c7 [REF] small cleanup for template helpers 2022-03-02 13:26:22 +01:00
Géry Debongnie 2a1b99be2d [REM] remove the Memo component
With the new fine grained reactivity system, it was no longer useful.
2022-03-02 13:26:22 +01:00
Géry Debongnie 8a472231cf [FIX] release script was using a hardcoded value for notes
instead of the value that was actually provided by the user
2022-03-02 13:26:22 +01:00
Géry Debongnie bb373e6a7a [DOC] add explanation on structure of compiled template 2022-03-01 15:46:09 +01:00
Samuel Degueldre d735213758 [IMP] reactivity: add support for collections (Set/Map WeakSet/WeakMap) 2022-02-28 15:43:41 +01:00
Géry Debongnie 076b0d774e [REL] v2.0.0-alpha.3
# v2.0.0-alpha.3

A new release, with the fine grained reactivity applied to component props,
and changes in the way Owl render subcomponents: it can now skip patching and
or rendering child components if needed.
2022-02-25 10:57:25 +01:00
Géry Debongnie f405fe9323 [DOC] add information about reactivity 2022-02-25 10:32:25 +01:00
Géry Debongnie 1ae9d514b9 [IMP] component: use reactivity to allow shallow renderings
With this commit, component only render child
components if they have different props (shallow
equality). Otherwise, we trust the reactivity
system to make sure that all impacted components
are updated
2022-02-25 10:32:25 +01:00
Géry Debongnie 592d9a458e [REF] move useState into component_node.ts 2022-02-25 10:32:25 +01:00
Géry Debongnie 0dbd2bd463 [REF] component: slightly simplify fiber code 2022-02-18 16:21:34 +01:00
Géry Debongnie 8ec7a6f9bf [FIX] compiler: prevent block- attributes and tags 2022-02-16 17:32:59 +01:00
Géry Debongnie 12b8ce963e [IMP] reactivity: toRaw now works with non reactive objects 2022-02-16 09:35:36 +01:00
Géry Debongnie bb9d65e95b [IMP] app: better error message when missing template 2022-02-16 09:35:36 +01:00
Géry Debongnie 73c339fff1 [DOC] remove outdated event bus doc 2022-02-15 10:31:03 +01:00
Géry Debongnie 406be446a5 [FIX] app: display correct url in dev mode message
closes #850
2022-02-15 10:15:07 +01:00
Géry Debongnie bd2aa8a72f [MISC] playground: improve benchmarking code 2022-02-15 09:07:32 +01:00
Géry Debongnie 3536f41f00 [FIX] blockdom: undefined properties are treated as empty strings 2022-02-15 09:07:32 +01:00
Samuel Degueldre 804ad3c35e [IMP] component: improve errors when thrown from lifecycle hooks
Previously, a crash in a lifecycle hook for any reason would throw an
error whose stack trace started from the scheduler and contained only
the place where the hook was called by owl, but not the place where the
hook was registered by the user. This proved very difficult for users to
debug as they cannot really tell which component registered that hook.

This commit alleviates the issue by creating a new Error when the hook
is originally called, and wrapping the registered callback in a try
catch, throwing an error with the correct stack trace instead of the
error in the hook, and setting the error in the hook as the cause of
this synthetic error.
2022-02-14 13:54:17 +01:00
Géry Debongnie 4a922ed82d [REL] v2.0.0-alpha.2
# v2.0.0-alpha.2

A new release, with some small fixes. Owl 2.0 is getting close.
2022-02-14 13:42:34 +01:00
Géry Debongnie a6f0985d43 [TOOLING] add benchmarking code to playground samples 2022-02-14 13:10:30 +01:00
Aaron Bohy 6aee1355c8 [IMP] deploy.yml: remove owl-next from the branch list 2022-02-11 11:03:23 +01:00
Géry Debongnie 921ced7c90 [FIX] refs in recursive templates now work properly 2022-02-11 10:46:44 +01:00
Géry Debongnie 1da930cb25 [MISC] tools: fix version string 2022-02-11 10:46:44 +01:00
Bruno Boi cc8e11c9c9 [FIX] can use t-out with String classes 2022-02-11 10:46:44 +01:00
Géry Debongnie 3196b585fd [FIX] slots: process slot params/values like normal props 2022-02-11 10:46:44 +01:00
Géry Debongnie ea2ccc5a03 [DOC] improve changelog 2022-02-11 10:46:44 +01:00
Géry Debongnie 960808aeb2 [IMP] blockdom: apply dynamic part of block before inserting it 2022-02-11 10:46:44 +01:00
Géry Debongnie 1fb1d37e32 [IMP] props validation: cannot set default value on mandatory props 2022-02-11 10:46:44 +01:00
Géry Debongnie 24ce8613c5 [DOC] add some info to the changelog 2022-02-11 10:46:44 +01:00
Géry Debongnie 2c1226d737 [IMP] compiler: translatableAttributes can be added/removed 2022-02-11 10:46:44 +01:00
Samuel Degueldre 140818b5f9 [IMP] compiler: allow to declare default slot scope on component 2022-02-11 10:46:44 +01:00
Géry Debongnie 83de53d283 [REF] allow external code to override validateTarget 2022-02-11 10:46:44 +01:00
Géry Debongnie 50aac42bdc [IMP] component: validate mounting target at patch time 2022-02-11 10:46:44 +01:00
Géry Debongnie bd98d4d0d0 [IMP] component: disallow calling hooks outside of setup
(and constructor)

Doing so could cause strange and difficult bugs
2022-02-11 10:46:44 +01:00
Bruno Boi 4d68dac24d [FIX] hooks: useSubEnv will not erase previous useChildSubEnv 2022-02-11 10:46:44 +01:00
Géry Debongnie 722abd6d5f [IMP] app: introduce test mode
Same as `dev` mode, but without warning in console
2022-02-11 10:46:44 +01:00
Géry Debongnie a7305a5cdb [TEST] component: add test to make sure a specific issue does not arise 2022-02-11 10:46:44 +01:00
Géry Debongnie ff734c706c [IMP] typing: make app and mount method properly generic 2022-02-11 10:46:44 +01:00
Bruno Boi add5fdd737 [FIX] compiler: never add _ prefix to non variable token 2022-02-11 10:46:44 +01:00
Samuel Degueldre a221411938 [FIX] compiler: do not pass dynamic props object as is
The child receiving the props can observe changes made to the passed
t-props object which is not desirable.
2022-02-11 10:46:44 +01:00
Bruno Boi bb6479f44f [FIX] compiler: add _ prefix to local variables while compiling an expression 2022-02-11 10:46:44 +01:00
Géry Debongnie aa95149997 [IMP] hooks: introduce useChildSubEnv and change useSubEnv 2022-02-11 10:46:44 +01:00
Géry Debongnie e4b4ee471f [FIX] compiler: does not modify xml doc in place 2022-02-11 10:46:44 +01:00
Bruno Boi 3af5e57825 [FIX] component: properly capture expression of t-model 2022-02-11 10:46:44 +01:00
Géry Debongnie 979712f84e [DOC] fix error in slot documentation 2022-02-11 10:46:44 +01:00
Géry Debongnie 93f2c1d766 [FIX] reactivity: clear callbacks at destroy time instead of unmount 2022-02-11 10:46:44 +01:00
Géry Debongnie 0728c8333d [FIX] compiler: add missing ; in some places 2022-02-11 10:46:44 +01:00
Géry Debongnie 6639d361c3 [FIX] component: proper error message in dev mode in some cases 2022-02-11 10:46:44 +01:00
Lucas Perais (lpe) 72962f1dd1 [FIX] compiler: force new block for svg nested in html 2022-02-11 10:46:44 +01:00
Géry Debongnie a4d9aae9a7 [FIX] svg: allow path as root tag 2022-02-11 10:46:44 +01:00
Samuel Degueldre 1e8576ad40 [FIX] blockdom: fix VHtml patching not setting its html correctly 2022-02-11 10:46:44 +01:00
Lucas Perais (lpe) 753d82149e [FIX] compiler: t-model on select with options with dynamic values 2022-02-11 10:46:44 +01:00
Géry Debongnie 700030cc7d [DOC] update changelog renderToString example 2022-02-11 10:46:44 +01:00
Géry Debongnie d828f39a2d [FIX] reactivity: do not observe eventtarget and other stuff 2022-02-11 10:46:44 +01:00
Géry Debongnie 0a73154985 [IMP] reactivity: introduces markRaw and toRaw functions 2022-02-11 10:46:44 +01:00
Lucas Perais (lpe) d88eb34d4f [FIX] compiler: svg in new block takes the right namespace 2022-02-11 10:46:44 +01:00
Lucas Perais (lpe) a8d88d4009 [FIX] compiler: t-key on a sub-domnode pushes an anchor in parent block 2022-02-11 10:46:44 +01:00
Géry Debongnie 6d9ed0d62f [REF] utils: move batched from reactivity to utils 2022-02-11 10:46:44 +01:00
Géry Debongnie b33471e819 [IMP] component: improve error message when invalid handler 2022-02-11 10:46:44 +01:00
Géry Debongnie 3fb65b3a89 [FIX] doc: fix broken link, and fix doc link checker test 2022-02-11 10:46:44 +01:00
Géry Debongnie 09d192999a [DOC] update changelog (add browser removal to changes) 2022-02-11 10:46:44 +01:00
Géry Debongnie 466cf50b73 [FIX] playground: update window management example 2022-02-11 10:46:44 +01:00
Géry Debongnie 96620d3e8e [FIX] scheduler: make sure raf is bound to window 2022-02-11 10:46:44 +01:00
Géry Debongnie 176c89b278 [REF] scheduler: capture requestAnimationFrame asap
This is useful to prevent interactions with other testing code.
2022-02-11 10:46:44 +01:00
Géry Debongnie 38941bc26f [FIX] playground: update example to owl 2 2022-02-11 10:46:44 +01:00
Géry Debongnie ce8ddd1cbf [DOC] improve useEffect doc 2022-02-11 10:46:44 +01:00
Géry Debongnie 81f44ee5d3 [FIX] reactivity: export Reactive type 2022-02-11 10:46:44 +01:00
Géry Debongnie 99b5e9ec55 [FIX] typing: Component class should be generic on Props and Env
Otherwise, it prevents proper typing with typescript
2022-02-11 10:46:44 +01:00
Géry Debongnie 4f35f03986 [DOC] update changelog content 2022-02-11 10:46:44 +01:00
Géry Debongnie eab0caa6cb [IMP] portal: ensure that destroy is synchronous 2022-02-11 10:46:44 +01:00
Géry Debongnie 5a2c769eab [DOC] document synthetic events 2022-02-11 10:46:44 +01:00
Géry Debongnie 89d63ff29a [IMP] components: crash when using unknown suffix/modifiers 2022-02-11 10:46:44 +01:00
Lucas Perais (lpe) a2e8abc243 [FIX] component, error_handling: do not cancel the error fiber twice 2022-02-11 10:46:44 +01:00
Géry Debongnie dfd0dcedb8 [IMP] doc: add changelog to doc test, update changelog 2022-02-11 10:46:44 +01:00
Géry Debongnie ad743c205c [IMP] ci: fails if circular dependencies are found in build 2022-02-11 10:46:44 +01:00
Géry Debongnie 7c78442e43 [FIX] remove circular dependency 2022-02-11 10:46:44 +01:00
Géry Debongnie 0d13c362d3 [DOC] remove reference to catchError, fix mistake in changelog 2022-02-11 10:46:44 +01:00
Lucas Perais (lpe) 374dbb2fd9 [FIX] components: cascading render after microtaskTick (makeChildFiber)
Co-authored-by: Samuel Degueldre <sad@odoo.com>
Co-authored-by: François Georis <fge@odoo.com>
2022-02-11 10:46:44 +01:00
Géry Debongnie 2a5f37cf4b [DOC] update changelog 2022-02-11 10:46:44 +01:00
Géry Debongnie cfb6b9f958 [DOC] update translations page 2022-02-11 10:46:44 +01:00
Géry Debongnie 82f6923a21 [DOC] add more information to the slots page 2022-02-11 10:46:44 +01:00
Michael (mcm) cccb379377 [FIX] bind lifecycle callbacks to component
Before this commit, some of the callbacks were bound to the component
and some were not.
This commit makes all the callbacks bind to the component.
2022-02-11 10:46:44 +01:00
Géry Debongnie 82c7c24438 [DOC] reorganize and update documentation to owl 2 2022-02-11 10:46:44 +01:00
Jorge Pinna Puissant 41ad5db2e3 [IMP] portal: compile t-portal in an internal Component Portal
This commit also clean-up the deepRemove for the Portal that is not
needed any more.
2022-02-11 10:46:44 +01:00
Géry Debongnie 42a140a8e3 [FIX] components: only call handlers if component is mounted 2022-02-11 10:46:44 +01:00
Géry Debongnie 7711733a23 [FIX] blockdom: toString method in multi could crash 2022-02-11 10:46:44 +01:00
Lucas Perais (lpe) 281b32965e [FIX] app: t_call recursive template is bound to the correct this 2022-02-11 10:46:44 +01:00
Lucas Perais (lpe) cec451fd15 [FIX] compiler: slot are called with a specific and different key 2022-02-11 10:46:44 +01:00
Samuel Degueldre 6a7703ea82 [FIX] code_generator: stop matching other variables prefix
Previously, we would replace block declarations in some contexts with
the variable alone, and decalres the variable higher in the generated
code. Issues arise because whe sometimes try to replace "let b2" with
"b2" but end up matching "let b20" which is incorrect.

This commit fixes that by adding a space to the text that we are trying
to match ("let b2 " won't match "let b20")
2022-02-11 10:46:44 +01:00
Lucas Perais (lpe) 4a03a60084 [FIX] component, fiber: subchildren should also patch and destroy their children
Have a GrandParent which controls whether one of its GrandChildren is displayed or not.
First, the GrandChild is displayed. Then, change the state of the GrandParent in order to kill
the GrandChild.

Before this commit the GrandChild is only removed from the DOM, as bdom correctly works.
But it is not destroyed.

After this commit, the GrandChild is correctly destroyed.
2022-02-11 10:46:44 +01:00
Lucas Perais (lpe) a6bdca082a [FIX] components tests: place tests in right submodule 2022-02-11 10:46:44 +01:00
Jorge Pinna Puissant 90167c5436 [IMP] portal: portal as a Directive
Before this commit, portal was a Component, now is a directive.
This commit also clean some unused code, and fix an issue on the clean
optimization when a portal is found in a condition or a loop.
2022-02-11 10:46:44 +01:00
Lucas Perais (lpe) c221721d7f [FIX] components: avoid leaks when children are outdated/destroyed
Every use case involving some sort of key set on a component would give birth to a leak in an async context:
- If a key of a component changed, the outdated one was never destroyed.
- destroyed component were never removed from their parent's reference map.

This commit solves both issues, that are tightly linked anyway.
2022-02-11 10:46:44 +01:00
Lucas Perais (lpe) 38f39b6755 [FIX] test/helpers: useLogLifeCycle supports custom key 2022-02-11 10:46:44 +01:00
Géry Debongnie 1775467434 [IMP] tooling: add testTimeout argument to test:debug command 2022-02-11 10:46:44 +01:00
Géry Debongnie 52d0526ddd [FIX] portal: properly handle errors
Before this commit, Portal overrode the _render function for its
component node, which means it bypassed the error handling mechanism
that was implemented in that method.  It could have been fixed by
duplicating the error handling code as well, but a better solution in my
opinion is to simply override the renderFn function.  This is closer to
the actual intent of the portal implementation: wrap the result of the
rendering in a VPortal vnode.
2022-02-11 10:46:44 +01:00
Lucas Perais (lpe) 4b170b9b45 [FIX] app, components: dynamic t-call should propagate the key
Have a Component which has a Component node, and a dynamic t-call itself having
a Component node.

Before this commit, both children had the same `key`, (as in the key in parent.children, which registers on the parent all its children).

As a result, the scheduler was endlessly hanging.

After this commit, it works as expected.
2022-02-11 10:46:44 +01:00
Géry Debongnie 3e1fe07ba7 [REF] compiler: factorize a common pattern 2022-02-11 10:46:44 +01:00
Géry Debongnie 5bf47500d5 [FIX] compiler: handle t-set as functions 2022-02-11 10:46:44 +01:00
Géry Debongnie 75ad0835e9 [DOC] update quick_start and how to test pages 2022-02-11 10:46:44 +01:00
Géry Debongnie 3d6a5eb828 [REM] doc: remove overview page 2022-02-11 10:46:44 +01:00
Géry Debongnie aceaeef8cc [DOC] update the tutorial todo app 2022-02-11 10:46:44 +01:00
Géry Debongnie 06fc3a2c77 [FIX] reactivity: work even if no callback is given 2022-02-11 10:46:44 +01:00
Géry Debongnie 92cc4375f8 [FIX] components: make sure t-ref work with t-if/t-else 2022-02-11 10:46:44 +01:00
Samuel Degueldre 9f2e2bcc66 [IMP] compiler: scope generated ids to their prefix
This means that unrelated ids (eg the id of a template, variable or key)
not longer share the same incrementing counter, meaning that you no
longer see a variable named "v2" unless another variable "v1" was
generated previously, this is also true for block data.
2022-02-11 10:46:44 +01:00
Géry Debongnie c7af885f43 [IMP] compiler: improve generated compiled code 2022-02-11 10:46:44 +01:00
Géry Debongnie bd5637c0a3 [FIX] useEffect: can depend on dom dependencies
Because the dependencies are now computed in patched.
2022-02-11 10:46:44 +01:00
Géry Debongnie 3c98ef8cb1 [FIX] portal: do not crash in dev mode
Before this commit, the props validation would fail in dev mode because
it did not expect a slot prop.
2022-02-11 10:46:44 +01:00
Géry Debongnie aad6b806ba [IMP] app: improve API, small refactoring 2022-02-11 10:46:44 +01:00
Géry Debongnie 772c275bd4 [REF] build: do not output const enum definitions
We only use 2 const enums in the codebase, but they are defined in the
output, even though this is not useful in any way. This commit reduces
the final output by about 30 loc.
2022-02-11 10:46:44 +01:00
Géry Debongnie 416deeb865 [REM] component: remove support for css tag 2022-02-11 10:46:44 +01:00
Géry Debongnie 7e40fa300a [IMP] components: improve props validation
to be able to specify that additional props are allowed
2022-02-11 10:46:44 +01:00
Lucas Perais (lpe) cc1eea0945 [FIX] component: error_handling when an error is rethrown 2022-02-11 10:46:44 +01:00
Géry Debongnie bf9cceb56f [REF] components: remove .el 2022-02-11 10:46:44 +01:00
Géry Debongnie 7eaecac0b5 [REF] tests: improve test helpers
- remove snapshotApp
- remove addTemplates
- simplify helpers
- make sure snapshotted templates are snapshotted with the app config
2022-02-11 10:46:44 +01:00
Lucas Perais (lpe) ddc358f48a [FIX] fiber, lifecycle: trigger a render during the fiber.complete
Have a component which does a render in its onWillPatch, onPatched, onMounted hooks.

Before this commit, the result was incorrect: the second rendering was not taken into account.

After this commit, those renderings are correctly applied at the price of a delayed render when the fiber
is in a critical state.
2022-02-11 10:46:44 +01:00
Géry Debongnie e2819323ee [FIX] blockdom: properly handle falsy attributes
This commit fixes some issues with falsy attributes not being properly
set/removed in various situations. Also, the behaviour was not
consistent between normal attribute (key/value) and generic attributes
(pair or object)
2022-02-11 10:46:44 +01:00
Géry Debongnie 983b9f996d [FIX] components: improve error handling
Owl provides a way to manage errors occuring in component lifecycle
methods. However, before this commit, these errors were not always
logged or visible, which is very annoying in the common developer
workflow (doing something, checking it works, seeing no error but a
broken interface).

In this commit, we make sure errors are logged/throws in all cases:

- if an error occurs in a mounting operation => the promise is rejected
(which will log the error)
- if an error occurs after the mounting operation and is not handled by
any error handlers => the error will be logged (with console.error).
Also, in that case, this commit adds a warning to explain that owl
destroys the root component, which will help developers understanding
what happened.
2022-02-11 10:46:44 +01:00
Géry Debongnie fd295b3be3 [FIX] compiler: properly handle <t> tags in some cases
The problem was that the compiler is based on the assumption that the
multi block received by the parser only occurs in some cases
where the structure of the template require a multi block, and it does
not work when we have random multiblock elsewhere.

We could fix the issue by modifying the code generator code to support
these usecases, or by simply removing these cases in the parser. Since
this seems more efficient, this is the approach taken by this commit.

Note that it was a good opportunity to simplify the parser.
2022-02-11 10:46:44 +01:00
Géry Debongnie e675f7ff5b [DOC] update changelog 2022-02-11 10:46:44 +01:00
Géry Debongnie 702fb3b253 [DOC] reorganize doc, unskip test, fix some links 2022-02-11 10:46:44 +01:00
Géry Debongnie 63fbcf99fd [FIX] blockdom: ignore attributes with undefined value 2022-02-11 10:46:44 +01:00
Géry Debongnie 14a6289f60 [IMP] component: add .bind suffix to props for easy binding 2022-02-11 10:46:44 +01:00
Lucas Perais (lpe) 894deed13b [FIX] component: render in delayed willUpdateProps
Have a child component on which a render is triggered.
This component delays its willUpdateProps and makes a rendering during the willUpdateProps

Before this commit, renderings of the child were inconsistent across
its parent's renderings.

After this commit, it works as expected.
2022-02-11 10:46:44 +01:00
Lucas Perais (lpe) 6f435c36d8 [FIX] app: factorize to allow smoother developments in projects
It should be usefull to allow developpers to implement mounting/unmounting
if they wish to.
2022-02-11 10:46:44 +01:00
Lucas Perais (lpe) 5dddf8f9a3 [FIX] blockdom: do not propagate svg namespace to siblings 2022-02-11 10:46:44 +01:00
Lucas Perais (lpe) 463eb4bb86 [FIX] hooks: useSubEnv supports arbitrary descriptors in env
Before this commit, when defining a getter in the env passed to useSubEnv,
the value was read, losing the definition of the property.

After this commit, declaring a getter in the env works as expected:
the property stays a getter.
2022-02-11 10:46:44 +01:00
Lucas Perais (lpe) b66d5231d3 [FIX] app: support for arbitrary descriptors in env
Before this commit, when defining a getter in the env passed to the App,
the value was read, losing the definition of the property.

After this commit, declaring a getter in the env works as expected:
the property stays a getter.
2022-02-11 10:46:44 +01:00
Lucas Perais (lpe) 3c12519277 [FIX] parser: correctly parse pre node within a div with new lines 2022-02-11 10:46:44 +01:00
Lucas Perais (lpe) c1a973a4d8 [FIX] component: error handling in class inheritance
Before this commit, class inheritance when using the onError hook was unclear nay wrong.

After this commit, error handlers are called from the bottom up  in the inheritance hierarchy.
If a handler doesn't rethrow the error, the handling stops there and no other handler is called.
If a handler does rethrow, the handlers declared in a parent class are executed.
2022-02-11 10:46:44 +01:00
Géry Debongnie e91e50a812 [REF] compiler: simplify all compiled templates 2022-02-11 10:46:44 +01:00
Géry Debongnie 2e176f135d [FIX] compiler: allow t-if with empty content 2022-02-11 10:46:44 +01:00
Géry Debongnie 49c7585998 [REF] components: unskip concurrency test 2022-02-11 10:46:44 +01:00
Géry Debongnie f32b1deb2c [FIX] move error handling out of fiber, fix complicated mounted issues 2022-02-11 10:46:44 +01:00
Géry Debongnie 1da3ecdbee [FIX] component: improve error handling
In the following situation: A parent of B, B parent of C, with an error
when C is mounted, caught by B and retriggering a rendering in B, then
the onMounted hook of A wasn't properly called. This commit fixes this
problem.
2022-02-11 10:46:44 +01:00
Géry Debongnie a1c619f094 [FIX] blockdom: properly handle references
Before this commit, there were situations where the reference numbers
were not properly set, which caused the blocks generated to crash
because the algorithm could not get correct references.
2022-02-11 10:46:44 +01:00
Géry Debongnie eceb3e6280 [IMP] component: render does not return a promise anymore 2022-02-11 10:46:44 +01:00
Géry Debongnie 8a1ac13975 [IMP] add support for top level comments 2022-02-11 10:46:44 +01:00
Géry Debongnie 779003e715 [REF] component: remove onDestroyed, implement onWillDestroy 2022-02-11 10:46:44 +01:00
Géry Debongnie 8c600fa539 [TESTS] test lifecycle in reactivity tests 2022-02-11 10:46:44 +01:00
Géry Debongnie bcc4fe2a27 [REF] tests: improve useLogLifecycle and helpers 2022-02-11 10:46:44 +01:00
Samuel Degueldre bb4948f3dc [FIX] reactivity: only call clearReactivesForCallback once on unmount 2022-02-11 10:46:44 +01:00
Samuel Degueldre cc4480e001 [FIX] reactivity: fix memory leak 2022-02-11 10:46:44 +01:00
Géry Debongnie 7143c2e39b [FIX] compiler: readd template name in compiled code 2022-02-11 10:46:44 +01:00
Géry Debongnie a8d8310b8e [REF] code_generator: move generating code to CodeTarget
Before this commit, we had two places with code that generate a function
code. Now, all this code is moved in a method 'generateCode' on
CodeTarget.
2022-02-11 10:46:44 +01:00
Géry Debongnie 0bbea351a6 [FIX] compiler: call dynamic templates with correct this 2022-02-11 10:46:44 +01:00
Géry Debongnie 2601a176c4 [FIX] slots: properly bind this in t-on arrow functions 2022-02-11 10:46:44 +01:00
Géry Debongnie 05a57d6da5 [REF] component: small cleanup
This commit makes it simpler to understand the way fibers are assigned
to nodes.
2022-02-11 10:46:44 +01:00
Géry Debongnie e6e6c31632 [FIX] component: concurrency issue
When a parent and a child were rendered at the same time, it was
possible for the 2 renders to decrement the same fiber internal
counter, which meant that the render was stalled.
2022-02-11 10:46:44 +01:00
Samuel Degueldre 3f66d9fe6c [FIX] slots: allow t-call and components in slot default content 2022-02-11 10:46:44 +01:00
Bruno Boi 5d8141a67c [IMP] owl: upgrade rollup-plugin-typescript2 to version 0.31.1 2022-02-11 10:46:44 +01:00
Samuel Degueldre 6459d8d289 [IMP] parser: normalize document before parsing 2022-02-11 10:46:44 +01:00
Samuel Degueldre 2943ca3921 [IMP] components: add test for template string in props 2022-02-11 10:46:44 +01:00
Samuel Degueldre 4866ed8e8a [IMP] parser: throw when using unsupported directive on component 2022-02-11 10:46:44 +01:00
Samuel Degueldre 93b88cad8d [FIX] components: allow prop names that are not valid bare property name 2022-02-11 10:46:44 +01:00
Mathieu Duckerts-Antoine b90180a9e0 [FIX] props: prop names can contain - 2022-02-11 10:46:44 +01:00
Bruno Boi 8239a5d2cd [DOC] Update CHANGELOG.md 2022-02-11 10:46:44 +01:00
Mathieu Duckerts-Antoine a073568667 [IMP] slots: via prop 'slots'
The slot inner working has been reworked. A prop "slots" is now passed
explicitely to the component. It looks like

{ slotName_1: slotInfo_1, ..., slotName_m: slotInfo_m }

with the objects slotInfo_i with mandatory keys "__render", "__ctx",
and optional key "__scope" and possibly others.

Here is how a slotInfo object can be created:
A slotInfo object is normally created by setting in a template something
like

<div>
    <t t-set-slot="foo" t-set-scope="scope" param_1="var" param_2="3">
        content
        <t t-esc="scope.bool"/>
        <t t-esc="scope.num"/>
    </t>
</div>

and it will be used somewhere like

<div>
    <t t-esc="props.slots.foo.param_1"/>
    <t t-slot="foo" bool="other_var" num="5">
</div>

In the above example, the function "__render" produces the block dom
element for the content of the t-set-slot.
The context "__ctx" will have a key "scope" with value { bool: ..., num: 5 }
and "__scope" will be set to "scope".
2022-02-11 10:41:18 +01:00
Samuel Degueldre 7143dd3ff5 [FIX] components: capture context in prop expressions 2022-02-11 10:41:18 +01:00
Samuel Degueldre c0cf2c9e3d [FIX] components: throw on duplicate t-key instead of hanging the app 2022-02-11 10:41:18 +01:00
Géry Debongnie db9658c140 [IMP] app: add templates in app config
Also, improve the parsing code
2022-02-11 10:41:18 +01:00
Géry Debongnie eb2c41aa91 [REM] tools: remove benchmarks/debug script
They are either no longer relevant, or less useful than some
alternatives (such as the js framework benchmark project)
2022-02-11 10:41:18 +01:00
Lucas Perais (lpe) a45ca98dac [FIX] package: bump owl version to 2.0.0-alpha1 2022-02-11 10:41:18 +01:00
Lucas Perais (lpe) ced777f0be [FIX] tools: adapt playground to owl 2 2022-02-11 10:41:18 +01:00
Lucas Perais (lpe) 7df0a4e93f [FIX] index, reactivity: export reactive function in index 2022-02-11 10:41:18 +01:00
Samuel Degueldre f3555cfae0 [IMP] misc: update typescript to 4.5.2 2022-02-11 10:41:18 +01:00
Géry Debongnie 629b379ea9 [IMP] components: rename onRender->onWillRender, add onRendered 2022-02-11 10:41:18 +01:00
Samuel Degueldre a400fc5e69 [IMP] reactivity: overhaul reactivity system
This commit makes the reactivity system more fine grained and makes it
more eager to stop observing keys or objects when they are modified,
this results in fewer "false positive" notifications.
2022-02-11 10:41:18 +01:00
Bruno Boi 5d4a38ad0f [IMP] svg namespace support 2022-02-11 10:41:18 +01:00
Géry Debongnie 093218a067 [FIX] remove cyclic dependency, improve error typing (#982) 2022-02-11 10:41:18 +01:00
Lucas Perais (lpe) ed3e6dcbb6 [FIX] component, fiber: error_handling at the Fiber level
Before this commit, errors triggered at the level of the fiber (as opposed to at the level
of a component's rendering), were handled as the very top level of the rendering, that is,
in the scheduler.
This was wrong because components below in the rendering tree would not have a chance to handle their
children's or their own errors.

After this commit, error triggered in willPatch, onMounted and onPatched are correctly handled
at the closest component to where they were thrown.
2022-02-11 10:41:18 +01:00
Géry Debongnie cb107cef7d [REM] remove some outdated tests 2022-02-11 10:41:18 +01:00
Géry Debongnie aecc320c29 [MOV] move memo and portal to root folder 2022-02-11 10:41:18 +01:00
Géry Debongnie e580ec00fe [REM] tests: remove async root tests 2022-02-11 10:41:18 +01:00
Lucas Perais (lpe) ee5f6c7569 [FIX] component: error_handling on current component
Have a Child Compnent which has one component that succeeds and another
one that fails at its instanciation.
The Child component handles the Errors by rendering itself.

Before this commit, the error handling algorithm made impossible for the scheduler to finish.
This was because the current fiber was still counted as ongoing, when it was actually completed.

After this commit, this use case is handled correctly.
2022-02-11 10:41:18 +01:00
Géry Debongnie c627b0add8 [DOC] add a change log 2022-02-11 10:41:18 +01:00
Lucas Perais (lpe) b902edc1be [IMP] app, compiler: introduce t-out
t-out automatically escaped content when it is a string not marked
with the `markup` function

t-out renders the raw content if it is a Block, or if it has been marked
with the `markup` funtion.

t-esc has been kept since it is safe and is optimized to render text nodes.

all t-raw calls are in fact the same as t-out.
2022-02-11 10:41:18 +01:00
Lucas Perais (lpe) 1761af9c24 [FIX][BREAKING] t-esc on component is not supported anymore 2022-02-11 10:41:18 +01:00
Bruno Boi db93ef08ff [IMP] templates: can load multiple at once and also from XMLDocument 2022-02-11 10:41:18 +01:00
Mathieu Duckerts-Antoine 03787cfb39 [REF] reactivity: new API 2022-02-11 10:41:18 +01:00
Mathieu Duckerts-Antoine 10745c52d0 [REF] tests: remove debugger 2022-02-11 10:41:18 +01:00
Mathieu Duckerts-Antoine 2b90e3a688 [FIX] reactivity: memory leak
The deletion of a key in an observed object did clear the observers of
that key but did not clear the atoms created (if any) when the key existed
(e.g. on the key value if it was trackable). This can lead to a growing
set of atoms that are useless but kept in memory if a lot of keys are
added/deleted. The same thing can happen if a key value is changed many
times and the values are trackable.

Here we fix the problem by
- keeping tracks of the objects that have been observed by an external call
  to the method "atom" (we call them seeds).
- remove all observer atoms that are not seeds for observers of at least
  one key deletion or key value change.

Note the fix is in some sense partial: a user could use the "atom" primitive
making the new system uncapable of avoiding a leak (see test "atom on an
object with a getter 3" where a getter is used in a weird way in an
observed object).
2022-02-11 10:41:18 +01:00
Bruno Boi b2ea241270 [IMP] hooks: reintroduce useExternalListener 2022-02-11 10:41:18 +01:00
Bruno Boi 81e5b24f2f [IMP] hooks: introduce useEffect
Co-Authored-By: Samuel Degueldre <sad@odoo.com>
2022-02-11 10:41:18 +01:00
Bruno Boi 717fd3b6ab [IMP] owl: mount util now takes an AppConfig 2022-02-11 10:41:18 +01:00
Bruno Boi 3fa1bb62f6 [IMP] env: env is now frozen, useSubEnv does not affect user env 2022-02-11 10:41:18 +01:00
Géry Debongnie 201f06c187 [FIX] tests: remove useless log 2022-02-11 10:41:18 +01:00
Géry Debongnie ae30d9db7d [FIX] portal: unskip some tests 2022-02-11 10:41:18 +01:00
Géry Debongnie af80cefa76 [FIX] component: fix lifecycle order 2022-02-11 10:41:18 +01:00
Géry Debongnie 1f6e84d141 [FIX] unskip tests 2022-02-11 10:41:18 +01:00
Géry Debongnie 1658d15b87 [REF] move event_bus into utils, readd 2 functions 2022-02-11 10:41:18 +01:00
Géry Debongnie c1439814bf [REM] tests: remove debug script tests 2022-02-11 10:41:18 +01:00
Géry Debongnie d5fbaff9f7 [REF] app: move TemplateSet into its own file 2022-02-11 10:41:18 +01:00
Géry Debongnie 8c16790471 [REF] move app and compiler code around 2022-02-11 10:41:18 +01:00
Géry Debongnie 9b8c582b32 [REF] component: fix typescript error 2022-02-11 10:41:18 +01:00
Géry Debongnie 1700a6fba3 [REF] compiler: rename qweb/ into compiler/ 2022-02-11 10:41:18 +01:00
Géry Debongnie 7513b1e507 [IMP] reactivity: slightly improve code and typing 2022-02-11 10:41:18 +01:00
Lucas Perais (lpe) e0c0306acd [IMP] component: re-introduce error handling in lifecycle 2022-02-11 10:41:18 +01:00
Samuel Degueldre bca6afeb90 [IMP] qweb: turn handlers into function expressions only
For the sake of consistency with vanilla JS, and to allow some things
that were previously not possible.
2022-02-11 10:41:18 +01:00
Mathieu Duckerts-Antoine 756d32daa0 [IMP] reactivity: Context replacement
Aim to replace the abstraction "Context" from OWL 1 with the new primitives
"atom" and "useState":

- notification is done only after a batch of modifications.
- observers are notified at most once for a batch.
- an observer of type component is notified (and rerendered)
  only if it does not have an ancestor that has to be notified for the
  same batch of operations (anywhere in the web of references!).
- notification of components is done on all levels "simultaneously".

Co-authored-by: Aaron Bohy <aab@odoo.com>
Co-authored-by: Géry Debongnie <ged@odoo.com>
Co-authored-by: Mathieu Duckerts-Antoine <dam@odoo.com>
2022-02-11 10:41:18 +01:00
Géry Debongnie 8169f05edc [IMP] pin prettier version to ensure consistent results 2022-02-11 10:41:18 +01:00
Samuel Degueldre 153f4379f4 [FIX] qweb: fix crash with ref an component in same slot 2022-02-11 10:41:18 +01:00
Samuel Degueldre 7ffb9afbd9 [FIX] qweb: fix crash when component only renders empty slot 2022-02-11 10:41:18 +01:00
Samuel Degueldre c03042b44d [IMP] qweb/components: remove t-ref on components
Refs to component expose a lot of implementation details that should be
private to parents. Parent to child communication should go through
props.
2022-02-11 10:41:18 +01:00
Bruno Boi df2d6b6a0e [IMP] qweb: reintroduce t-tag directive
will not be compatible with t-model directive !
2022-02-11 10:41:18 +01:00
Lucas Perais (lpe) 7c04cc425e [IMP] qweb: compiler: support t-key on node and component without t-foreach 2022-02-11 10:41:18 +01:00
Bruno Boi 16f1e2c237 [IMP] bdom: support multiple synthetic events on one node 2022-02-11 10:41:18 +01:00
Bruno Boi 8a84b5be56 [IMP] qweb/attributes: uncomment two tests
- textarea with t-att-value
- select with t-att-value
2022-02-11 10:41:18 +01:00
Bruno Boi 219923d752 [IMP] qweb: introduce t-model directive
supported modifiers: lazy, trim, number
2022-02-11 10:41:18 +01:00
Bruno Boi 348b505e5f [IMP] tags: reintroduce inline css tag
The CSS tag is useful to define a css stylesheet in the javascript file:
```js
class MyComponent extends Component {
  static template = xml`
        <div class="my-component">some template</div>
    `;
  static style = css`
    .my-component {
      color: red;
    }
  `;
}
```

The `css` tag registers internally the css information. Then, whenever the first instance of the component is created, will add a <style> tag to the document <head>.

Original commit in Owl v1: 953778dc5
2022-02-11 10:41:18 +01:00
Mathieu Duckerts-Antoine d3745e4e5f [IMP] reactivity: new primitives for reactivity
fine grained reactivity:

existing key in source changes --> only observer having read the key are notified

add/delete key in source changes --> all source observers are notified

Co-authored-by: Aaron Bohy <aab@odoo.com>
Co-authored-by: Géry Debongnie <ged@odoo.com>
Co-authored-by: Mathieu Duckerts-Antoine <dam@odoo.com>
2022-02-11 10:41:18 +01:00
Mathieu Duckerts-Antoine 80cb6b7a91 [REF] Code prettification 2022-02-11 10:41:18 +01:00
Lucas Perais (lpe) 4cceb239dd [IMP] qweb, blockdom, components: t-on with modifiers
supported modifiers: capture, prevent, stop, self.
2022-02-11 10:20:09 +01:00
Lucas Perais (lpe) 2ae0149adb [IMP] blockdom: t-on supports synthetic and native event handler
Synthetic handler is a sort of event delegation that allows placing
only one listener on the document to improve performance. It is an opt-in option.

Native listener places the listener on the node itself.
2022-02-11 10:20:09 +01:00
Lucas Perais (lpe) 3eb63452e7 [FIX] qweb, component: remove support for t-on on component node 2022-02-11 10:20:09 +01:00
Lucas Perais (lpe) 1296964ae2 [FIX] qweb: t-key in t-foreach is mandatory, throws otherwise 2022-02-11 10:20:09 +01:00
Bruno Boi c71db28bc6 [FIX] qweb: reintroduce test on t-debug 2022-02-11 10:20:09 +01:00
Mathieu Duckerts-Antoine a0b2551e4a [IMP] tests: component mounting
We re-add some tests for component mounting.
2022-02-11 10:20:09 +01:00
Mathieu Duckerts-Antoine ebd2e4324f [IMP] app: mount app in "first-child" position
We reintroduce the possibility to mount the app in first position in
a target. The option "self" has been dropped since it is now possible
for a component to have several top level nodes.
2022-02-11 10:20:09 +01:00
Bruno Boi aa3148eddf [IMP] package.json: add watch arg to test:debug command
Before this commit
The command "npm run test:debug" runs the tests once.

After this commit
Jest runs in watch mode
2022-02-11 10:20:09 +01:00
Bruno Boi 42811344da [IMP] package.json: add remote test:debug command
Usage:
Open chrome://inspect then run in console:
> npm run test:debug ./path/to/your/testfile.ts
2022-02-11 10:20:09 +01:00
Mathieu Duckerts-Antoine a0e1af83ac [IMP] component: defaultProps application
We re-add the application of defaultProps. Note that the application
is done twice in dev mode.
2022-02-11 10:20:09 +01:00
Mathieu Duckerts-Antoine c16d8ed6de [IMP] component,qweb: props validation
We re-add the possibility to validate props when dev mode is active.
No change in the API right Now. The dev mode is activated via the
configure method of App class.
2022-02-11 10:20:09 +01:00
Samuel Degueldre 15e4c856da [FIX] component: correctly create a new node when previous is destroyed
Previously, when a component node had been created and destroyed, and
the corresponding component was then recreated, the destroyed node was
reused. This commit fixes that
2022-02-11 10:20:09 +01:00
Samuel Degueldre ced5d0f69f [IMP] *: re-add a bunch of tests 2022-02-11 10:20:09 +01:00
Mathieu Duckerts-Antoine b6eb4d009e [IMP] qweb: t-props directive
We reimplement the directive "t-props" and add some tests for it.
2022-02-11 10:20:09 +01:00
Géry Debongnie 8c71d99e5f [MOV] move lifecycle_hooks into component/ 2022-02-11 10:20:09 +01:00
Mathieu Duckerts-Antoine d7f3f4defe [FIX] qweb: re-add test on memory leak
Re-add test from 6e185f9.
2022-02-11 10:20:09 +01:00
Mathieu Duckerts-Antoine 0f2192604c [FIX] qweb: t-set directive
This commit reintroduces some tests for the t-set directive and make
them pass. For that, it was necessary to adapt the qweb compiler in
order to get the following behaviors:

A t-set can affect parent contexts (up to the first parent tagged as
boundary) when the key changed is found in one of the parent contexts.
Some context are marked as boundaries in such a way that

   - rendering contexts (e.g. components) cannot be modified via a t-set.
   - a t-set in a t-call body or in a called template can never change a
     context above the t-call context.

Code prettification has been done.
Snapshots have been modified.
2022-02-11 10:19:44 +01:00
Lucas Perais (lpe) 10df0b5f4a [FIX] re-introduce tests 2022-02-11 10:19:44 +01:00
Mathieu Duckerts-Antoine d569ea1c28 [IMP] qweb: throw error when t-component is not used with a 't' tag 2022-02-11 10:19:44 +01:00
Lucas Perais (lpe) 52fa81c510 [FIX] re-introduce some missing tests
The point is to have visibility on the development of the owl2 features.
This commit reintroduces some tests keeping them skipped in order to fulfill that purpose.

There still are some missing tests though.
2022-02-11 10:18:03 +01:00
Mathieu Duckerts-Antoine d6668e3439 [IMP] qweb: re-add support of t-on directive
We add some test for the t-on directive.

For making them pass, it was necessary to change the code produced by
compileTForeach: the const declaration is not done by using generateId
and there was some conflict with the variable names produced in
captureExpression. Consequently, many snapshots had to be changed.

Code prettification has been done too.
2022-02-11 10:18:03 +01:00
Mathieu Duckerts-Antoine ee1ef20ce1 [ADD] components: re-add a test for t-foreach directive 2022-02-11 10:18:03 +01:00
Samuel Degueldre 9d5ffe11c7 [IMP] components: re-add a bunch of components tests from owl 1
Some tests are skipped because they rely on not-yet-implemented
features.
2022-02-11 10:18:03 +01:00
Samuel Degueldre 900a3ee501 [IMP] components: add back style_class tests
The tests have been adapted to the new way of doing things, some tests
are skipped because they rely on features that are not implemented yet
2022-02-11 10:18:03 +01:00
Mathieu Duckerts-Antoine 0a544bd7e8 [ADD] Translation feature
This commit brings back the possibility to translate text nodes and
the attributes "label", "title", "placeholder", and "alt" in an app
configured with a suitable translation function.

It is also possible to deactivate translations under a node via
the directive t-translation="off".

For flexibility it is possible to define the list of translatable
attributes in the app.
2022-02-11 10:18:03 +01:00
Samuel Degueldre 4415cc8932 [REF] doc: remove references to router and store
Owl 2 will not have a router or store implemented inside the library
2022-02-11 10:18:03 +01:00
Samuel Degueldre efa147fdab [REF] qweb: use native Node and Element instead of custom Dom types 2022-02-11 10:18:03 +01:00
Géry Debongnie e746574a1d [REF] initial prototype of owl 2 2022-02-11 10:18:01 +01:00
Géry Debongnie c06049076a [FIX] qweb: renderToString should not escape twice text content
Since commit
https://github.com/odoo/owl/commit/b2f12a111524f37348b142ac248813f9cb25ca2e,
Owl escape text content twice. It seems that it was done to prevent
security issues, but without realizing that the standard t-esc method
already escapes.

closes #708
2021-12-14 15:21:37 +01:00
Samuel Degueldre bc04f727ac [REL] v1.4.10
#v1.4.10

- fix: make arrow function capture backwards-compatible
2021-12-07 15:32:05 +01:00
Samuel Degueldre 0bc9573a8a [FIX] component: make arrow-function capture backwards compatible
When fixing the absence of capture for arrow functions passed as props,
we unintentionally introduced a breaking change: bare function calls in
the arrow functions used to be called  with the rendering context as
their this value and this was no longer the case.

This commit fixes that by intentionally not capturing the value of
functions that are called withing the arrow function.
2021-12-07 15:27:00 +01:00
Samuel Degueldre 73f94fba3f [REL] v1.4.9
# v1.4.9

- fix: correctly capture the scope of arrow functions passed as props
2021-12-07 10:09:12 +01:00
Samuel Degueldre 7a16449724 [IMP] CI: make formatting check mandatory for ci check 2021-12-03 14:08:05 +01:00
Samuel Degueldre 718c765e3b [FIX] qweb: correctly capture the scope of arrow functions in props 2021-12-03 14:08:05 +01:00
Samuel Degueldre 150d620b8e [REF] run prettier 2021-12-03 14:08:05 +01:00
Géry Debongnie 307b936d01 [REL] v1.4.8
# v1.4.8

- fix: prevent crash in some rare cases
2021-11-03 13:44:46 +01:00
Achraf (abz) 6950f8e628 [FIX] components/fiber: Call patch only if target is valid
Currently in some cases, adding an attachment via lognote creates a traceback.
Error : shouldPatch is true while `vnode` is not defined, so `patch()` failed
This is a hotfix correcting this problem by calling `patch()` only if `shouldPatch` is true **and** the `vnode` is set.

opw-2645203
2021-11-03 11:37:04 +01:00
Géry Debongnie 4e3b7c74da [REL] v1.4.7
v1.4.7

fix: memory leak in some templates
2021-10-19 16:47:20 +02:00
Géry Debongnie 98bb2842d8 [FIX] run prettier on codebase 2021-10-19 16:45:04 +02:00
Géry Debongnie 6e185f987b [FIX] qweb: do not leak values in global context in rare cases
In some very rare cases (such as the use of the t-foreach directive),
Owl did leak the values in the render context in the global context.
This was due to the fact that the compiled template looked like this:

let _3 = _4 = _5;

instead of

let _3 = _5;
let _4 = _5;
2021-10-19 16:41:45 +02:00
Géry Debongnie c0f495661d [REL] v1.4.6
# v1.4.6

- fix: crash in component render (in rare cases)
- fix: build system now target ES2017 instead of ESNext
- fix: remove useless log in prod mode
2021-10-04 15:16:01 +02:00
Géry Debongnie 0f7a8289a6 [FIX] config: do not log anything if in prod mode
It is worse having a dev mode in a production environment than the
opposite. The purpose of the warning was to avoid that situation.

However, in prod mode, it is not really necessary to log the config key.

closes #915
2021-10-04 14:57:30 +02:00
Géry Debongnie 1c3b04f6a8 [FIX] build: fix typescript target to ES2017
This makes sure that we do not leak modern code in odoo.
2021-10-04 14:57:30 +02:00
Géry Debongnie 64db7777dd [FIX] component: async issue
This is a tricky commit. The key point is that the Fiber.complete
method, which commits a rendering to the DOM works like this: it
traverses the component tree, patch the corresponding DOM for each
component, calls the mounted/destroy hooks, and reset the currentfiber
of components to null, all synchronously.

However, this means that it is possible for components to initiate a
rendering (which create a new currentFiber) before the currentFiber is
reset to null, so the internal state of owl is corrupted. This can
occurs in a crash, as in the test that accompanies this commit.

To fix this, we take care of resetting the currentFiber first, while we
walk the component tree. Then, the internal state is always consistent
(i.e. a currentFiber to null means that there is no pending rendering)

closes #904
2021-10-04 14:57:30 +02:00
Géry Debongnie 37313c47a3 [REL] v1.4.5
# v1.4.5

- qweb: expose translatable attributes
- ci/tests: update jest/rollup
- doc: clarify tutorial
- doc: update readme, add nice badges
2021-09-22 16:34:02 +02:00
Géry Debongnie 3f563de9c0 [CLEANUP] run prettier on codebase 2021-09-22 16:29:59 +02:00
Géry Debongnie 97564a7612 [FIX] tests: update tests error messages
Updating my node version to v16, I noticed many tests breaking, because
the way errors are formatted did change.  This commit ensures that the
test suite keeps working for all node versions.
2021-09-22 16:00:37 +02:00
Géry Debongnie f1abf7f2ea [DOC] update readme, to add nice badges 2021-09-21 09:36:15 +02:00
Géry Debongnie 8464a1b04e [IMP] qweb: expose translatable attributes
This commit allows owl users to add any attribute to the list of
translatable attributes.

closes #903
2021-09-21 09:36:15 +02:00
Géry Debongnie c0a62dfd05 [DOC] clarify tutorial
The part about setting up the various files did not express clearly that
we need the iife file, not the cjs.
2021-09-21 09:36:15 +02:00
Lucas Lefèvre 600f1e35d4 [IMP] package.json: update jest and rollup
If we want to upgrade Typescript to version >4 (in this repo or another using
owl), we also need jest >25. Jest <26 do not support Typescript >4.

However, jest >26 has a few breaking changes that completely breaks owl in
tests.

This commit updates jest to the current latest version (27) and adapts the
code accordingly.

A few words on what changed
---------------------------

1. the default test environment is no longer `jsdom`. It is now manually
   configured to restore the previous env.

2. the jsdom version has been upgraded. This brings a few breaking changes,
   detailed later.

3. there's a bug in jsdom >16.4. Manually created `<t/>` (by qweb compilation)
   are recognized as "T" and not "t". Qweb thinks it's a component (since the
   first letter is capitalized), but it's not a component: boom, everything
   breaks.
   A fix has been proposed here jsdom/jsdom#3240. But it's not likely to land
   in jest in the short term (jest would need to update its dependency to the
   next major jsdom version). This commit works around the problem for now by
   creating `<t/>` slighty differently such that they are in an XML document
   from the start (and not HTML document).

4. the xml parser implementation changed to increase the strictness and
   correctness of XML parsing, according to specifications. A few tests needed
   to be adapted.
   https://github.com/jsdom/jsdom/commit/c96decf837ece54bdc550dfb7dca7e5d6c97bc2d

5. jest matcher `toHaveProperty` now check inherited properties. This breaks a
   few tests. Since the breaking assertions didn't bring a lot of value from a
   behavior point of view (it was more "white box" technical tests), they are
   removed in this commit
   https://github.com/facebook/jest/commit/1256f76a5a83034b51c7524142b60b099f69a7ab

6. jsdom now implements the behavior of links (`<a/>`). One test was `click`ing
   on such a link, with the right click. Jsdom now tries to navigate to the
   pointed URl...but crashes because navigation is not implemented :(
   It turns out the test is probably not a valid/realistic scenario. On every
   tested browser (chrome - chromium - brave - edge -firefox - safari), a
   right click with the mouse triggers a `contextmenu` event and no `click`
   event.
   https://github.com/jsdom/jsdom/commit/cc95abc576f596ff7f3eaf8245f376e1f21aa485
2021-09-08 11:47:50 +02:00
Géry Debongnie b3181f119d [REL] v1.4.4
# v1.4.4

fix: overlapping multi-class in t-att-class
2021-09-03 09:57:00 +02:00
Géry Debongnie 1e1e05350a [REF] run prettier on codebase 2021-09-03 09:56:09 +02:00
Samuel Degueldre b242230e20 [FIX] qweb: fix overlapping multi-class in t-att-class
Previously, if two attributes in t-att-class shared some classes, their
presence would be determined by the last attribute declared, instead of
being present if any attribute containing it evaluates to true. This
commit fixes that.
2021-09-01 11:58:45 +02:00
Géry Debongnie 9fe2da704e [REL] v1.4.3
# v1.4.3

- fix: another scoping issue with t-slots
2021-07-08 11:54:32 +02:00
Géry Debongnie 21b1661d39 [CLEANUP] run prettier on codebase 2021-07-08 11:53:48 +02:00
Géry Debongnie ec05b1f5e3 [FIX] slots: fix bad interaction between t-call and slots
The previous changes in the combine method (used to copy all the
variables defined in the current scope for use in a slot) had the effect
of squashing the prototype chain: instead of `Component -> Obj1 ->
Obj2 -> Obj3`, the combined scope had: `Component -> Obj1'`.

This has an unfortunate interaction with the way t-call is implemented,
which uses the fact that we are in a subscope to add a own
__access_mode__. It depends specifially on the prototype chain, and that
the parent scope may have a different value for that property. But with
the way combine was implemented, we lost all that subtlety since
everything is squashed.

In this commit, we reimplement that function in a way to make sure we
keep the prototype chain structure
2021-07-08 11:49:25 +02:00
Géry Debongnie 8083678f03 [REL] v1.4.2
# 1.4.2

- qweb: properly handle inline expressions with lists such as '[a,b,c]'
2021-07-07 14:56:46 +02:00
Géry Debongnie 61c2ec5d83 [FIX] qweb: properly handle lists in inline expressions
Before this commit, Owl inline expressions with a list with multiple
elements such as [a,b,c] was transformed into

[scope['a'], b: scope['b'], scope['c']]

instead of

[scope['a'], scope['b'], scope['c']]

This is due to a previous commit adding support for short object
descriptions such as {a,b}.

To fix this means that we have to keep track of the current group type
for the expression, which is done by using a stack.
2021-07-07 14:50:27 +02:00
Géry Debongnie e579a993fd [REL] v1.4.1
# 1.4.1

This release brings in two small fixes:

- vdom: a performance improvement to reduce number of calls to classList.remove
- slots: fix subtle issue with wrong context used in event handlers when
  multiple slots are involved
2021-07-07 11:10:05 +02:00
Géry Debongnie ea3c6f7bf0 [FIX] slots: make sure handlers are properly bound to component
In some situations (a slot inside a slot), the combine method was
wrongly copying all properties of the scope into the context, which
caused the event handling system to wrongly use a subobject as component
(since it detects the fact that __owl__ is a own property_).
Consequently, we could have very subtle issue with some properties being
shadowed by a sub object.
2021-07-07 11:04:25 +02:00
Pierre Paridans 9cfafc30b5 [IMP] vdom: performance improvement
Port from original snabbdom project: snabbdom/snabbdom#634

The issue is that before this commit, the removeClass method was
sometimes called even if it is not useful. See this comment for more
detail: https://github.com/snabbdom/snabbdom/issues/633#issue-618706258
2021-07-06 14:14:40 +02:00
Aaron Bohy ad42c583c6 [FIX] package.json: bump node version to v12
Node 10.x is no longer maintained, and since a recent commit [1],
a test fails with that version.

[1] 88fd1cf483
2021-07-06 13:30:17 +02:00
Géry Debongnie 6faaa6c361 [REL] v1.4.0
# v1.4.0

This release is larger than usual: lot of small fixes, and a few improvements as
well.

- config: change debug mode warning to info
- fix: add support for callable expression in event handler (for example, `t-on-click="some.function"`)
- fix: allow specific props to override generic props (in `t-props`)
- fix: add support for short object description in inline expressions: `{ hey }`
- fix: add support for t-att-value on `<textarea/>` and `<select/>`
- fix: slots: issue with scoping in nested loops
- fix: slots: default slot is not lost in some cases
- fix: do not shadow an error in case the finalizing code fails
- imp: qweb: allow multiple class in class attribute object notation: `t-att-class="{'a b': value}"`
- imp: better detection for dynamic component change (less need for `t-key`)
- fix: router: allow querystrings in path
- fix: qweb: add support for template strings
- fix: qweb: make sure nodes with t-transition are removed in all cases
2021-07-06 10:27:55 +02:00
Géry Debongnie bff539cabf [FIX] tooling: make sure we escape content in release script 2021-07-06 10:27:30 +02:00
Joseph Caburnay 88fd1cf483 [FIX] extensions: guarantee to call transitionend callback
There is a possibility that the transitionend event of an element/component
with t-transition directive won't trigger. Though this situation is
difficult to assert, it was observe in odoo runbot for the pos ui.

When the transitionend event is not fired, the callback that removes
the element from the dom won't be called, resulting to a corrupted view.
An example of which is the following:

```html
<div t-if="show" t-transition="fade">Hello</div>
```

If `show` is set to false by some ui action and by any chance the
transitionend event is not fired (perhaps because the transition didn't
actually start or because of completely unknown reason), the div element
will remain in the view -- and this is not desirable.

This commit patches this situation such that if after 50ms that the
transitionend event is supposed to be fired but the event isn't fired, we
force the callback using a setTimeout. This guarantees the call of the
callback that is suppose to remove the element from the view.
2021-07-06 09:11:12 +02:00
Russell Briggs f0b75b6890 [IMP] router: allow query string in paths 2021-07-06 09:05:58 +02:00
Géry Debongnie a1552117f9 [IMP] qweb: add support for template strings
in inline expressions, such as t-esc or t-value.

closes #746
2021-07-05 10:09:23 +02:00
Géry Debongnie 17ae1d06c4 [IMP] component: better detection for dynamic component change
Before this commit, Owl could not detect that the underlying component
in a template such as <t t-component="{{state.child}}"/> was changing,
if the two components have the same tag as root element.

This is because the reconciliation is done at the vdom level, which does
not know about components.  To solve this, one could use a t-key to make
sure owl can make the difference.

With this commit, we can simply use our knowledge of the fact that we are
dealing with a dynamic component and autogenerate a suitable key.

closes #623
2021-07-05 10:09:23 +02:00
Géry Debongnie 27629cedfa [IMP] qweb: allow multiclasses in t-att-class object form
the low level method htmlelement.classList.add does not accept multiple
classes in one string, which is why, in owl, the expression

`<div t-att-class="{'a b c': value}" />`

did not work as one might expect. It is however very convenient in real
life templates, so this commit improve owl by adding support for this
feature.

closes #813
2021-07-05 10:09:23 +02:00
Géry Debongnie 3a93370ab6 [FIX] component: do not shadow the initial error in some cases
Before this commit, the error handling code simply destroyed the
application whenever an unhandled error occured in the owl rendering
process. This is perfectly fine, except that since the application is
potentially corrupted, the destroy code may crash as well. We simply
catch those errors to avoid shadowing the main issue.

closes #866
2021-07-05 10:09:23 +02:00
Géry Debongnie a6bb4d8ee1 [FIX] component: make sure default slot is applied
Before this commit, owl was erroneously defining default slots in most
cases, even though they are empty. The problem occurs when the content
of a component slots is a t-set-slot, and we remove that, then use the
rest as default slots, even though it is only reduced to a set of text
nodes.

With this commit, we only consider the content as default content if it
is not only a sequence of text nodes containing only spaces.

closes #882
2021-07-05 10:09:23 +02:00
Géry Debongnie caf842c482 [FIX] component: fix scoping issue in nested loops
The templates contained in a slot have to be rendered with the current
scope, but during the rendering of the sub component, which happens
later (after the willStart for the sub component). Therefore, we need to
save the scope that should be used for the slots, so we can access the
proper variables. This was done using an Object.assign() statement,
which is actually only a shallowclone for the own properties.

In this commit, we properly copy all the properties for the current
scope, even those contained in the prototype.

closes #855
2021-07-05 10:09:23 +02:00
Géry Debongnie 1b513a1637 [FIX] qweb: add support for t-att-value on <select> tags
Before this commit, it was not possible to set the value of a select tag
by using the t-att-value attribute.

Doing so is not actually trivial because of the way the vdom works: it
processes the node attributes before its children are created, which
means that the vdom code tries to set the initial value of the select
before its children are created, which means that it is ignored. To make
it work, I added a node create hook which is called after the children
are completely processed.

closes #873
2021-07-05 10:09:23 +02:00
Géry Debongnie 52a200878a [FIX] qweb: add support for t-att-value on textareas
The code did not treat textareas in the same way as inputs. As a result,
using t-att-value on a textarea did not work.

closes #872
2021-07-05 10:09:23 +02:00
Géry Debongnie f4994a20d8 [MISC] owl: add temp/ in gitignore
I sometimes use the temp folder to keep stuff in while working
on refactorings/switching branches.
2021-07-05 10:09:23 +02:00
Géry Debongnie 7419c1982a [DOC] tags: add missing information
The example given in the tags page was misleading.

closes #884
2021-07-05 10:09:23 +02:00
Bishal Pun a8c8f6affe Update comparison.md 2021-07-03 07:27:47 +02:00
Géry Debongnie dabe7f9bfa [FIX] qweb: properly parse short object description
Before this commit, using an expression such as "{machin}" was compiled
in qweb into "{scope['machin']}" which is not valid.

With this commit, we instead transform it into "{machin:
scope['machin']}".

closes #885
2021-07-02 14:20:13 +02:00
Michael Mattiello (mcm) d08ea63565 [IMP] directive: make props override t-props
Before this commit, props and t-props were computed like
`Object.assign(props, t_props)`.
Now, it computes like `Object.assign(t_props, props)` so props will
override t-props.

closes https://github.com/odoo/owl/issues/886
2021-07-02 11:50:23 +02:00
Sébastien Theys 7ebe0da962 [IMP] component: add support for callable expression in event handler 2021-07-01 12:26:23 +02:00
Xavier Morel 3e0e8475a6 [CHG] config: flip debug mode warning to info
Backport of odoo/odoo@e4834fce69

There's no way to easily disable / silence this warning, because
multiple tours explicitly opt into debug mode (with good reasons). So
it's not enough to bypass the `mode` setter in the test setup helpers
and set `QWeb.dev` directly (which works for test_main in POS and
main_tests in web), there would also need to be special workarounds in
the 4 modules which set `owl.config.mode` based on the session's debug
mode.

I'm not sure how useful this warning is: it defaults to `false` so the
only situation in which this would be relevant would be for a
third-party to use Owl *and* explicitly enable the debug mode
in-source *and* forget to remove it when deploying to production *and*
look at their console.
2021-06-29 08:43:20 +02:00
Géry Debongnie 2e83c739b9 [REL] v1.3.2
# v1.3.2

Fixes

- components: correctly propagate errors to parent
2021-06-18 10:41:51 +02:00
Géry Debongnie 922eb7cd98 [FIX] component: propagate errors to parent
Before this commit, the error handling process was too naive: once an
error occurs in a rendering, owl catches it, looks for a component that
implements the catchError method, then calls it.

However, in real life, we sometimes need to rethrow that error (or
another one) to propagate the error to some parent handler. This error
needs to be handled by the closest parent component that implements
catchError.

This is what this commit implements: it wraps the catchError call in a
try/catch, then in case of errors, try to handle it by a parent.
2021-06-18 10:34:09 +02:00
Géry Debongnie d12115554c [REL] v1.3.1
# v1.3.1

Fixes

- components: fix issue with t-call in nested t-slot (parent component was incorrect)
2021-06-10 10:36:33 +02:00
Géry Debongnie 1a6b26c8c6 [REF] cleanup: prettier 2021-06-10 10:23:48 +02:00
Lucas Perais (lpe) d67d295eaa [FIX] qweb, t-call: t-call nested in t-slot
Have a t-call within a t-set-slot of a component.
The called template has a t-component directive.

It should be like:

```xml
<t t-name="Zero">
  <Slotted>
    <t t-call="someTemplate" />
  </Slotted>
</t>

<t t-name="someTemplate">
  <SomeComponent />
</t>
```

Before this commit, the parent of SomeComponent was the Zero component

After this commit, the parent of SomeComponent is the Slotted Component as it should be

closes #862
2021-06-10 10:00:22 +02:00
Géry Debongnie 9cbcf20b33 [REL] v1.3.0
# v1.3.0

## Improvements

- qweb: add support for  directive
2021-06-04 14:19:07 +02:00
Géry Debongnie 3a461e1dd1 [IMP] qweb: add support for t-tag directive
Very useful in some cases, when one needs to define a generic component.

closes #721
2021-06-04 14:11:31 +02:00
Géry Debongnie e8387810e6 [REL] v1.2.6
# v1.2.6

## Fixes

- router: add support for arbitrary param placements in paths
2021-05-19 12:28:13 +02:00
Samuel Degueldre acac9d1741 [FIX] router: add support for more arbitrary param placements in paths
Before this commit, params in paths had to be be between slashes and
comprise the entirety of the contents between those slashes (eg:
`/books/{{id}}/{{name}}`)

This is unnecessarily restrictive. This commit removes this restriction,
which allows for paths such as:
- `/books/{{id}}-{{name}}`
- `#books&id={{id}}&name={{name}}`

among others

closes #858
2021-05-19 12:25:58 +02:00
Géry Debongnie 968a5460bb [REL] v1.2.5
# v1.2.5

## Fixes
- qweb: correct order for component class lookup (most specific to least specific)
2021-05-18 10:01:22 +02:00
Samuel Degueldre e646eb697e [FIX] qweb: fix order of lookup in t-component directive
Previously, the order of resolution was:
- components defined on the class of the current component
- components defined on the QWeb instance
- the current instance's context

This is unnatural because it doesn't go from most specific to least, as
the current instance's context is the most specific. This is also
fragile, as adding components to the QWeb instance can break unrelated
components.

This commit fixes that by making the lookup start with the current
component's context instead
2021-05-18 09:58:30 +02:00
Simon Genin (ges) 7dfa901332 [IMP] tooling: improve release script
Release script errase dist folder
closes #793

Release can only be done on master branch
closes #829

Update the playground owl version on release
closes #814

Add logError method in release to show messages in red.

Check-formatting command added to the release process.
2021-03-30 10:58:25 +02:00
Géry Debongnie 0290f63ba3 [FIX] component: various issues while mounting manually components
The initial problem solved by this commit is that it was possible to get
into a situation where a mounting/rendering was started, then the component was
updated, but then another mounting operation begins, and it tries to
reuse the previous rendering operation, which is no longer uptodate.

The underlying issue is that Owl did not track properly the various
internal state change of a component.  These issue should be solved by
the introduction of the status enum, which currently tracks 6 possible
states:

- CREATED
- WILLSTARTED
- RENDERED
- MOUNTED
- UNMOUNTED
- DESTROYED

This status number replaces the isMounted and isDestroyed boolean flags.
It has the advantage of making sure that the component is in a
consistent state (it is no longer possible to be destroyed and mounted,
for example)

Another advantage is that it gives us an easy way to track the fact that
a component has been rendered, but is not in the DOM.  This is a subtle
situation where some various events can happen, and we need to be able
to react to that case.

Note that there is a change of behaviour: if a component is mounted in a
specific target, then before the mounting is complete, the component is
mounted in another target, we no longer reject the first mounting
operation.
2021-02-08 10:59:28 +01:00
Géry Debongnie 370fae4e1a [FIX] package.json: rollback live-server from 1.2.3 to 1.2.1
No idea why, but it looks like the npm package 1.2.3 disappeared.
2021-02-04 09:07:26 +01:00
Géry Debongnie 76735410f8 [FIX] qweb: prevent issue with builtin object properties
The QWeb expression parser use an object as a mapping between some
strings and the desired output in the compiled template.  However, as we
should all know, objects are not Maps, they have some additional
properties, such as "constructor" or "hasOwnProperty".

The simple solution is to make sure the mapping object does not have
anything in its prototype chain to pollute its purpose.

closes #835
2021-02-04 09:07:26 +01:00
Géry Debongnie 19a47a7001 [IMP] component: add setup lifecycle hook 2021-02-03 15:32:38 +01:00
Géry Debongnie 398f9f4e53 [IMP] component: can trigger event handlers even if unmounted
From the beginning, Owl was designed to only call event handler on
components that are mounted in the DOM.  The main benefit is that if a
component is destroyed, we are guaranteed to not execute any useless (or
potentially dangerous code).

However, there is one downside: if a component tree is being mounted,
and a child component trigger an event in its mounted hook, then it
cannot be caught by the parent, since the parent is technically not yet
mounted.

This may not be a good situation, but the point is that Owl
unnecessarily prevent the handler to be called.

We can fix this issue by simply checking if the component is not destroyed
instead of checking that it is mounted.

closes #809
2021-02-03 14:46:18 +01:00
Géry Debongnie af426aa902 [DOC] misc small fixes
closes #827, #825, #822, #821
2021-02-03 13:44:04 +01:00
Géry Debongnie 490cf18079 [REL] v1.2.3
# v1.2.3

This is just another small bug fix release, because we need it in Odoo.

Fix: prevent crash when rendering a component before mounting it
2021-01-19 15:39:26 +01:00
Géry Debongnie dfc782599b [FIX] crash when rendering component before mounting
This commit makes sure that Owl does not crash when a component is
created, then updated (for example, with a (observed) state change), and
then, some moment later, mounted.

The initial render is not useful, because it is not linked to a mounting
action anyway.  And it caused issues such as a crash when Owl tried to
patch it to a non existing target
2021-01-19 15:26:15 +01:00
Géry Debongnie 71f545058b [REL] v1.2.2
# v1.2.2

This is just a small bug fix release, because we need it in Odoo.

Bug fix: allow renderings for detached components. Before this release, Owl
ignored renderings in some cases if a component is detached.  We now still render
it, because it is important in some cases.
2021-01-14 09:10:35 +01:00
Géry Debongnie 1a20cc57de [FIX] component can be updated while detached from the main DOM
This commit tries to improve the interactions involving unmounted
components, or components mounted in an htmelement which is detached
from the main DOM, and rendering actions.

The main example is mounting a component in detached div, to prepare all
children.  If we just mount the component, it will work as expected: the
full component tree is rendered in memory, and ready to be really
mounted at the desired target.

However, if before doing that, we update the component and call render
on it (for example, with a change in an observed state), then this
rendering will be ignored, and therefore, the full subcomponent tree is
not uptodate.

This commit will also solve another issue in the compatibility layer in
odoo: in the form renderer, we mount components with the adapter in a
div, which is not yet attached to the DOM. We then manually call the
mounted hook when on_attach_callback is called.  This means that before
this commit, any change to the components between the initial rendering
and the call to mounted will be ignored.

As a bonus, this commit has the effect of bringing closer the semantics
of render and mount operations, which is certainly good.

closes #823
2021-01-14 09:05:05 +01:00
Géry Debongnie 25738a1bf0 [REL] v1.2.1
# Owl v1.2.1

## Changes

- fix: issue with components with shouldUpdate and remounting not rendering
- fix: issue with connected components using onUpdate callback not rendering
- fix: error in todoapp example code
2021-01-08 15:26:28 +01:00
Géry Debongnie 4a96eff3c6 [FIX] store: properly call onUpdate functions in some cases
Before this commit, the following scenario could happen:

Suppose that we have a parent component A, connected to a store,
 and a child component B, also connected to the store and using
the onUpdate feature.

Then, we remount the A component in some other places and a
rendering is initiated in A.  We immediately update the store state.
What happens next is:

- rendering A is done, A internal revid is updated
- store update A (but nothing is done because the state change here
  does not modify A)
- rendering B is done (from parent), B internal revid is updated
- store update B, notice internal revid is updated, does not call the
  onUpdate function

We then have the B component which has not its internal state updated,
because we did not call its onUpdate function.

The solution is to move the onUpdate call in a "preupdate" event, to be
sure that it is called everytime the store is updated.

closes #816
2021-01-08 15:05:07 +01:00
Géry Debongnie d043d47754 [FIX] component: propagate correct info when reusing fibers
In some cases, a rendering initiated in some component is then remapped
into a larger rendering initiated by some parent.

If we have some components which implement shouldUpdate to return false,
then the following scenario can happen:

- some parent component is mounted (which triggers a rendering with
force: true => bypass the shouldUpdate)
- some sub component is updated and rerendered, AFTER the previous
rendering goes through it
- the sub component notices that there is an ongoing rendering, and
  remaps itself in the parent rendering

Before this commit, the new fiber in the subcomponent does not have
force flag set to true, so the new rendering for the subcomponent does
not go through its own children (if they have shouldUpdate=false)

Another more complex kind of scenaria can happen when a remapped
rendering happen with sub components with dynamic shouldUpdate. The
problem is the same at the end: the new rendering should ignore the
shouldUpdate, to make sure we have the last correct information.

With this commit, we make sure that the flag of the new fiber is set to
true.

closes #818
2021-01-07 10:08:29 +01:00
Vishnu Vanneri 3a10468f7b Update todoapp mount issue (#817)
APP gets error while running "ReferenceError: mount is not defined"
because of mount not defined with "Component"
2021-01-06 08:43:33 +01:00
Géry Debongnie 144b323d2b [REL] v1.2.0
# Owl v1.2.0

## Changes

- translation fix for terms surrounded by spaces
- fix: properly remount components with shouldUpdate=false
- add: add two new generic hooks:  and
- fix: do not skip rendering in components using store and local state (in some cases)

Note that the last change is a pretty significant change: component connected to
a store should be very careful if the data that they represent is deleted, because
they will always be rendered with the current state of the store.
2020-12-14 13:23:46 +01:00
Géry Debongnie bb64e87634 [FIX] store: properly render, even if shouldupdate is implemented
Before this commit, an unwanted behaviour happened when using components
with shouldUpdate implemented, and store/state.

The actual problem is the following: the sub component is using a store,
and shouldupdate.  Whenever the component is rendered, it checks if there is an incoming
rendering from the context.  If that is the case, it skips the
rendering, because we actually only want to be rendered by the store
rendering (otherwise, we may run into issue with inconsistent data (more
recent data from the context, older data in the component).

However, if shouldUpdate is implemented, then the rendering coming from
the context simply does not arrive.

To fix this, we tried to just force these renderings to go through all children,
regardless of their shouldUpdate status. This actually works, but then
shouldUpdate is ignored, which is an issue in Odoo discuss.

Then, after discussing this situation, we noticed that the context/store
system is actually unsafe: the protection given by the check mentioned
above is in fact fundamentally insufficient: there are other perfectly
valid situations where a rendering can be triggered on the component,
which will bypass the check (for example, an explicit call to
this.render() or a rendering initiated by some parent component) and
cause a crash if the component is not properly defensively written.

Therefore, it is currently mandatory for all components using
context/store to be aware of that, and to protect themselves against
such situations. So, in that regard, the check is not really a
protection, it just helps hiding an unsafe situation anyway and we
decided to remove it.

Note that this is a potentially breaking change: components using a
store and some local state will now be rendered twice in some cases...

closes #799
2020-12-14 13:19:36 +01:00
Géry Debongnie 9a87b9a4a0 [IMP] hooks: add some building blocks for hooks
This commit introduces two new hooks: useComponent, and
useEnv.
2020-12-14 11:53:01 +01:00
Géry Debongnie 2a53a9592e [FIX] component: force mounting subcomponents with shouldUpdate
Components can implement shouldUpdate to return false.  In that case,
renderings coming from above should be ignored.

However, if the component was unmounted and is remounted, we actually
need to force a rerendering in that case, so it is mounted, otherwise
the subcomponent is left in unmounted state, which means that rendering
are ignored.

closes #800
2020-12-11 15:19:37 +01:00
Ivan Yelizariev f54b9a4a0c [FIX] properly translate terms surrounded by spaces
This reimplements logic from Odoo v13 [1], i.e. if we have a text that follows
by space e.g. "This database will expire in " [2], then we want get translation
for the term without that space and add the space manually. This way we can
export trimmed terms for translations and don't miss the space, when atranslator
forget to add it at the end of translation

[1] https://github.com/odoo/odoo/blob/26927417e2957acba6fb79446c2520107daa7eea/addons/web/static/src/js/core/qweb.js#L46
[2] https://github.com/odoo/enterprise/blob/ab0e893493f909ec3033e8a1cf6c141ea9375587/web_enterprise/static/src/xml/base.xml#L21

---

opw-2410708
2020-12-03 13:36:17 +01:00
Géry Debongnie abb9d0b364 [REL] v1.1.1
# Owl v1.1.1

## Changes

- export  object to make utility functions testable
- minor doc improvements and corrections
- fix: make sure owl does not crash in iframe in private mode
2020-11-20 11:02:19 +01:00
Géry Debongnie 8483cc805e [FIX/IMP] export browser object, prevent crash in private mode
This commit performs two tasks:

1. it exports the internal browser object (in owl.browser), for ease of
testing
2. it makes sure that Owl does not crash inside iframes in incognito
mode, because window.localStorage raises an exception in that case

closes #791
2020-11-20 10:55:08 +01:00
Simon Genin 142f47ac82 [DOC] Fix animation documentation (#783)
The documentation was a bit missleading around which and when css
classes were added to the DOM.
Also added a scss mixin usage exemple.

Co-authored-by: Simon Genin (ges) <ges@odoo.com>
2020-11-18 09:41:50 +01:00
Stephen Mugisha c8a27aa1a3 Fix minor grammatical errors
Correct minor grammatical mistakes in the `why_owl.md` file
2020-11-02 16:36:16 +01:00
Simon Genin 323cb61d2c [DOC] minor fix - missing this.
Proposed by @obayit with https://github.com/odoo/owl/pull/689
2020-11-02 16:33:02 +01:00
glovebx ac9cc91701 typo correct 2020-11-02 16:03:10 +01:00
Géry Debongnie d83cfc12ee [IMP] qweb: the t-slot directive is now dynamic
It is useful for some kind of components to be able to use a completely
dynamic slot expression.
2020-10-30 15:31:03 +01:00
Géry Debongnie cb07c99d40 [IMP] owl: add a new mount method 2020-10-30 15:31:03 +01:00
Géry Debongnie d615ffd81b [REL] v1.0.13
# Owl v1.0.13

## Bug fixes

- fix: slots: prevent infinite loop in some cases
2020-10-26 08:32:05 +01:00
Géry Debongnie 8d2b250fef [FIX] slots: prevent infinite loop in some cases
The reviewer for the commit on named slots inside named slots did not
notice that there was an infinite loop.  Because of his sloppiness, Owl
could block in an infinite loop when a named t-slots was defined inside
a subcomponent, but not as a direct child.
2020-10-23 12:14:46 +02:00
aab-odoo 7626cc01b3 [IMP] rollup: properly indent generated files (#774)
Also lint rollup.config.js
2020-10-22 13:58:10 +02:00
Géry Debongnie 392185ab67 [REL] v1.0.12
# Owl v1.0.12

## Bug fixes

- fix: properly handle named t-slots inside named t-slots
- fix: do not render comments as text in t-raw
- fix: allow dynamic template in t-call
- fix: correctly handle top-level t-call with body
- fix: correct cause of non determinism in tests

## Tooling improvements

- setup github actions for CI
- improve owl bundling pipeline
- add  flag in owl configuration
- add prettier to github CI
2020-10-20 17:35:23 +02:00
Géry Debongnie 392dc0131a [FIX] config: make enableTransitions work on components (#773)
Fun: the transition is handled at two different places, once for dom
nodes, once for components.  Obviously, I only applied the change to the
first case and forgot about the second.
2020-10-20 17:30:08 +02:00
Simon Genin 4e8e9dee3e Update deploy.yml => add prettier (#772)
* Update deploy.yml

Add the npm run prettier command action to every push request

* Update deploy.yml
2020-10-20 16:38:14 +02:00
Simon Genin 25d4cb2aab Improve the release script for easier deployment (#771)
Co-authored-by: Simon Genin (ges) <ges@odoo.com>
2020-10-20 16:36:14 +02:00
Bruno Boi 4724652533 [IMP] component: allow using TypeScript type hints (#758) 2020-10-20 16:30:09 +02:00
Géry Debongnie b08cc1d084 [IMP] config: add enableTransitions flag to config
It is useful to be able to disable the t-transition directive for
testing purposes.  This commit introduces a global config flag to do
just that.

closes #768
2020-10-20 13:22:25 +02:00
Géry Debongnie a68d7774c6 [FIX] qweb: issue when rendering twice dynamic t-calls
The previous implementation generated an id each time the template was
rendered, instead of just once per new dynamic template found.
2020-10-20 08:02:03 +02:00
Géry Debongnie ed9d820d9e [FIX] tests: fix cause of non determinism
Since commit 7e4baf6, some tests were failing non deterministically. It
seems like the root cause for the problem is that the nextTick method
was sometimes completed too early.

From my understanding of the problem, the nextTick method was correct,
however it is running in a jest test, in node, which simulates the
requestanimationframe behaviour, probably not perfectly.

Switching to an alternate implementation, which swaps the setTimeout and
the requestanimationframe seems to be more solid.

Note that this commit had to introduce the nextFrame method as well,
because the animation tests really seems to want to be in the next
frame, not in a callback executed in the same frame, but at the end.

closes #757
2020-10-19 21:43:49 +02:00
Géry Debongnie 4a2d019161 [DOC] qweb: explain how to work with iterables in t-foreach
Owl is meant to stay low level-ish, and making it work magically with
sets/maps/... seems to be a little too much in term of code/magic. Also,
using iterables in t-foreach is actually quite simple, making this
improvement not as important.

closes #720
closes #754
2020-10-19 20:52:31 +02:00
Géry Debongnie 89eae191b1 [FIX] qweb: correctly handle top level t-call and body
Whenever a top level t-call was made with some non empty body, Owl
complained that a template should not have more than one root node.

The reason was that the compilation context for the body of the t-call
directive was the same as the root compilation context, and it already
had a parentNode set.

To fix the issue, this commit simply use the subContext method to create
a different compilation context, which actually makes sense, because the
body of a t-call is really a different situation.  Also, as a bonus, it
slightly improves the code for the t-call directive.

closes #760
2020-10-19 20:51:44 +02:00
Géry Debongnie 3fbc02986c [FIX] qweb: allow string interpolation in t-call
This commit allows the t-call directive to choose a dynamic template.
This is working in QWeb Python, but was not possible in Owl.

closes #709
2020-10-19 16:27:38 +02:00
Géry Debongnie a28ce440dc [REF] qweb: simplify _compile method arguments
Strangely, the _compile method required a CompilationContext whenever it
was compiled as a sub template, but this parent context was actually not
really needed.  I guess that it was the case in the past, but this was
changed at some point.

This commit makes another significant change: the xml element is no
longer mandatory.  It is actually only required for slots (because the
template is not registered to qweb).

Finally, the interface for the whole method has been changed to use an
option object, which makes more sense with 3 optional paremeters.
2020-10-19 16:27:38 +02:00
Géry Debongnie 8e018fbbda [FIX] qweb: do not render comments as text in t-raw
The code converting html to a vnode did not handle comment nodes as
expected.

closes #761
2020-10-19 16:27:14 +02:00
Simon Genin 33f7fc8e83 [IMP] bundling: Improve owl bundling process and output (#751)
The bundle pipeline can use a bit of a improvement:

Most of the process is moved from npm scripts to rollup.
Add package keys to smooth out the use of bundlers of the end users.
(Rollup by example check amongst others the main, module and browser key
to import the right version of a lib when needed).
Refactor rollup logic to make it more modular.
Add bundled module formats.
Add comments to tsconfig to see more clearly what's possible.
Add reference tag to help @types discovery in test files.

Co-authored-by: Simon Genin (ges) <ges@odoo.com>
2020-10-16 16:11:11 +02:00
Simon Genin 6a833c54ec [IMP] setup github actions for CI
Add action to launch the tests on the PRs
2020-10-13 16:57:24 +02:00
Géry Debongnie cb38d795f9 [FIX] slots: properly handle named t-slots inside named t-slots
Previous code naively handled nested t-set-slots: if a second named
slots was found, it overrode the first.

In this commit, we use a set to make sure that we only use the first
found t-set-slot node. Also, we ignore set-slots defined in a sub
components, because these slots are only relevant to the sub component
itself.

Note that it works as expected because document.querySelectorAll
performs a search depth first, so we will always use the named slots
closer to the parent element, in term of depth.

closes #682
2020-10-09 15:01:25 +02:00
Géry Debongnie 8da68e925b [REL] v1.0.11
# Owl v1.0.11

- improve release script to make sure we get correct code on npm
2020-10-08 10:50:39 +02:00
Géry Debongnie 474ffa1cd9 [FIX] release: try to publish correct version on npm 2020-10-08 10:48:08 +02:00
Géry Debongnie e73fb462c5 [REL] v1.0.10
# v1.0.10

Bug fixes!

- qweb fix: scoping issue with t-call in t-foreach
- qweb fix: issue with t-set with a body in a t-call
- qweb fix: handle input value attribute as a property
- qweb fix: allow t-call on arbitrary nodes
- qweb fix: add indeterminate to special input properties
- component fix: allow using t-model with bracketed expression
- component fix: properly validate multiple props
- component fix: issue with higher order component, and t-keys
- component fix: issue with unmounted children that should be destroyed
- component fix: make concurrent renderings more robust in some cases
- component fix: allow using vars with body as props
- observer fix: do not proxify promises
- test infrastructure: stop mocking requestanimation frame
2020-09-18 15:16:27 +02:00
Géry Debongnie 38c7ad9629 [FIX] t-model: support expressions with [ ]
Before this commit, the t-model directive worked well with expressions
such as "state.value", but not with bracketed expression: "state[value]"
(it generated invalid code).

This commit make the t-model smarter by detecting this case, and
properly capturing the base expression and key variable.

closes #694
2020-09-18 14:58:48 +02:00
Géry Debongnie d0c76c5854 [IMP] qweb: add indeterminate to special input properties
Input with type="checkbox" have a special property (indeterminate) to
visually display the fact that the input value is non determinate (in my
chrome browser, the checkbox is then drawn with a simple - inside). It
does not actually modify the value of the input, only the way it is
displayed.

So, with this commit, owl will properly set the property, as expected.

closes #713
2020-09-18 13:43:25 +02:00
Géry Debongnie e032314739 [FIX] qweb: allow t-call on arbitrary html nodes
This is a rarely (if ever) used feature, but according to our qweb
reference implementation, it is possible to use the
t-call directive on an arbitrary html tag, like this:

<div t-call="my.template"/>

It is then interpreted as:

<div><t t-call="my.template"/></div>

So, with this commit, we make sure that the owl qweb implementation
matches that behaviour.

closes #706
2020-09-18 08:39:57 +02:00
Géry Debongnie b2db7f21ed [FIX] observer: does not proxify promises
Promises are kind of special, and do not behave like usual javascript
values.

For this issue, the problem is that when the observer tries to observe a
promise value, the code will crash with an error like this:

Uncaught TypeError: Method Promise.prototype.then called on incompatible receiver [object Object]

Also, note that it does not make much sense to proxify promise methods
anyway, since they are not (supposed) to be modified.

So, with this commit, we simply consider that promises should be treated
like a primitive value: simply ignored when determining if it should be
proxified

Note that I actually believe that putting promises in a useState is not
a good idea in general.

closes #677
2020-09-17 13:51:10 +02:00
Géry Debongnie 7b8ac13d3f [REF] qweb: mostly revert fix with t-call and vars with body
The previous fix (overriding tostring of VDomArray) is actually more
general, and solves the same issue. So, let us simplify the code and
keep the more general solution.

This reverts commit 3bf91afc3f.
2020-09-17 09:44:08 +02:00
Géry Debongnie 06d852fcf9 [FIX] component: allow using vars with body as props
Consider this scenario:

- a variable v (with a body) is defined in a template
- it is then passed to a sub component as a prop
- and now, it is t-esc-ed.

Before this commit, the displayed value was [object object], because the
value actually passed to the sub component was a VDomArray (internal
structure used to represent nodelists)

This issue is actually quite a problem in practice, because values in a
templates are translated, but not in attributes.  Therefore, using a
t-set directive with a body text content is the proper way to have
translated values at runtime.

We override in this commit the method toString of VDomArray to make sure
it is properly displayed.

Note that we considered changing the way props were generated (by trying
to detect VDomArray, then calling vDomToString), but then the value
would not be able to be used in a t-raw.  Also, it is quite elegant to
be able to format the VDomArray only at the end.

closes #670
2020-09-17 09:44:08 +02:00
Géry Debongnie 7e4baf668a [FIX] test: timing issue
Before this commit, we artificially replaced in the tests the
requestAnimationFrame by a setTimeout, to actually increase the speed of
the tests.  However, this is not really a true replacement.  For
example, a real setTimeout can come before or after a real
nextAnimationFrame, depending on when/where it is requested.

Also, this change exposed another problem: the nextTick function did a
setTimeout before a nextanimationframe. This is not a problem when
nextAnimationFrame is replaced by a setTimeout, because then all
expectations holds in owl.  However, it is wrong: to get to the next
animation frame, we need to request an animation frame, and THEN wait
with a setTimeout.

closes #729
2020-09-17 09:18:05 +02:00
Géry Debongnie fe34ba00a6 [FIX] component: properly validate multiple props
Because of a "break" statement instead of "continue", the check for valid
props was stopping as soon as it met an optional props, which kind of
invalidate the whole system.

closes #717
2020-09-17 08:33:18 +02:00
Géry Debongnie e5e7790530 [FIX] qweb: handle input value attribute as a property
Sometimes, HTML is slightly more subtle than what I initially expect.
Rendering some html is simple, we have tags and attributes.  However,
once we add behaviour, then the situation is more complex:

<input value="abc"/>

is an input with an INITIAL value of "abc", but the attribute does not
actually represent the CURRENT value of the input, which may be
different if the user did change it.

This is basically the difference between "attribute" and "property".

So, when rendering html with owl, we sometimes want to actually set
the property (current value), instead of the html attribute.

This commit make sure that this is the case for inputs with the "value"
attribute.

closes #722
2020-09-17 08:32:02 +02:00
Géry Debongnie 3bf91afc3f [FIX] qweb: fix issue variables set in body of t-call
The body of a t-call directive may be used to define private variables
to the sub template call.

However, the code that handles t-call worked like this:

- compile sub template if necessary
- then compile body of t-call to extract variables

This means that the variables defined in the t-call body were not yet
processed and available in the context.  Because of that, when the call
to t-esc is done, there is not internal qweb var, and the code simply
outputs a scope['varname'], which is in our case a VDOMArray, so it is
displayed as [object object]

What this fix does is changing the way t-esc works: if we are in the
context of a sub template, then it assumes that any outside variable may
or may not be a VDomArray, so it needs to check and eventually convert
it to a string, if necessary.

closes #719
2020-09-16 11:39:32 +02:00
Géry Debongnie 2529aa3ef2 [FIX] component: make concurrent renderings more robust
Here is a situation that can happen in some complicated case:

1. a parent component is rendered, which includes some children
2. it is then willPatched
3. the sub components are then mounted/willUnmounted
4. because of complicated business logic, this causes the parent
component to be rerendered (before parent "patched" method is called)
5. owl will internally reset its currentfiber to null (but there is a
pending rendering!)
6. subsequent rendering will ignore pending rendering
7. havoc ensues

This is actually one of the reason why modifying a component state in a
willPatch component is actually not a good idea.  However, the good news
is that this specific situation can be properly handled: we can simply
make sure that we do not reset currentFiber to null if there is a new
pending rendering.

closes #728
2020-09-16 09:21:33 +02:00
Géry Debongnie 8d25bddda4 [FIX] component: subtle issue with unmounted children
Owl has to manage a lot of interesting situations.  One of them is when
a rendering is initiated, which creates a sub component, but then
another rendering starts, which invalidate the previous one, and will
create another sub component.  Since the first sub component was not
ever in the DOM, we cannot rely on the vdom patching process to remove
it, so we have to do it manually.

Sadly, this is actually a very tricky situation, since there are other
subtle situations where the code that remove an unmounted widget could
be executed, in particular when the parent component is unmounted, then
remounted, then modified to trigger yet another rendering.

In this commit, we handle this case more carefully by making sure that
the destroyed subcomponent properly configures its pvnode so the patch
process happens as expected.

joint work with the framework team, and in particular LPE for his work on
finding a testcase!

closes #724, #731
2020-09-15 15:51:30 +02:00
Lucas Perais (lpe) 81af21a025 [FIX] component, fiber: update props with virtual node should not crash
Have a hierarchy of A, B, C components where:

```xml
<div t-name="A">
  <div>
    <B t-key="key1"/>
  </div>
</div>

<t t-name="B">
  <C t-key="key2"/>
</t>

<div t-name="C">
  <div><t t-esc="keys_as_props" /></div>
</div>
```

The subtility of the issues lies in B, which doesn't have its own
concrete DOM element, rather, it borrows it from C.

With the sequence of events:
- change key2
C1 is destroyed and replaced by another instance, and another node.
B1 has its props updated and is patched with the C2's node (CRITICAL)
A1 is patched

- change key1 AND key2
C2 is destroyed
B1 is destroyed
A1 is patched replacing B1 by B2, and their nodes too (which at this point should be C2's to C3's)

Before this commit, at the CRITICAL point, the node representing the component itself
(technically its pvnode) was not updated with the new concrete node provided by B1 patch with C2 node
i.e. it held the previous node still
The second array of steps crashed because at A1 patch, the new B2 node would replace B1, which
was out of the DOM (removed because C1 was destroyed long before),
and therefore without a viable parent to insert B2 node.

After this commit, we update the component's pvnode after the patch which elm had possibly changed
There is no crash anymore for this use case.
2020-09-14 15:17:45 +02:00
Jigar Patel 9baea2c1cd [DOC] props validation: The validation type should be a String object. 2020-07-28 08:56:33 +02:00
Lucas Perais (lpe) 8e03f9cd9c [FIX] qweb: t-call should protect scope and let it accessible
Have a t-call nested in a t-foreach nested in a t-foreach

```xml
<t t-name="template">
  <t t-foreach="..." t-as="a">
    <t t-foreach="..." t-as="b">
      <t-call="templateCalled" />
    </t>
  </t>
</t>
```

Before this commit, the `a` variable was not accessible within the t-call.
That was because the way t-call protected its scope by hiding other protected scope
in this case, the first protected scope for the first `t-foreach` was hidden

After this commit, `a` and `b` are accessible in the t-call, whether the t-call
defines its own variables by `t-set` or not.
Also, as expected from other fixes, there is no leaks of variables defined within a `t-call`

fixes #695
2020-07-28 08:56:00 +02:00
Géry Debongnie c5a2f52afb [REL] v1.0.9
# v1.0.9

- qweb fix: add support for svg namespace in t-raw
- qweb fix: properly handle subtemplates in shared templates
2020-06-02 10:38:32 +02:00
Michael Mattiello (mcm) 9fd8315c53 [FIX] qweb: support of svg in t-raw
Before this commit, t-raw a string containing `<svg>` did not display
the svg element. This was because of missing namespace in vnode's data.

Now, `vdom.addNS` is called to add the svg namespace when necessary.
2020-05-25 14:02:34 +02:00
Géry Debongnie 85318b3ae6 [FIX] qweb: properly handle subtemplates in shared templates
With QWeb, we can register globally templates (using the xml tag or
the registerTemplate function). However, these templates, once
compiled, can generate sub template compiled functions. Before this
commit, these sub functions were local to a specific instance.

This means that creating a new QWeb instance and rendering a global
parent template would crash, since it was unable to find the actual sub
function.

This commit fixes the issue: the sub functions are now shared
statically, but with a unique ID, so we do not have issues with sub
functions having a same name in different QWeb instance.

closes #701
2020-05-25 11:43:24 +02:00
Géry Debongnie 4b961cbffe [REL] v1.0.8
# v1.0.8

- qweb fix: do not override t-att-class with class attribute in some cases
- component fix: refuse to mount a destroyed component
- hooks type improvement: useRef is now generic, and can capture the type of a component
- qweb fix: t-esc inside t-call using outside t-set
2020-05-18 09:07:31 +02:00
Aaron Bohy 2af8cccd65 [FIX] qweb: t-esc inside t-call using outside t-set
Before this commit, the generated code was incorrect, and crashed,
when there was a t-esc="abc" in a subtemplate, with t-set="abc"
done outside the subtemplate, with syntax <t t-set="abc">value</t>.
2020-05-15 13:47:57 +02:00
Géry Debongnie b8d3618afa [IMP] hooks: improve useRef typings
With this commit, we can get the type for the target component for a
ref.

By default, if the generic type is not given, the ref will simply use
the base Component type.
2020-04-30 16:23:36 +02:00
Géry Debongnie 559fadb62a [FIX] component: properly handle mounting a destroyed component
part of #685
2020-04-22 09:29:39 +02:00
Géry Debongnie c36333dbbc [CLEANUP] update prettier to v2.0.4 2020-04-21 16:23:31 +02:00
Géry Debongnie b5c3422b4d [FIX] qweb: do not override t-att-class with class
There was some code in qweb to make sure that we support setting class
and t-att-class on the same html element:

<div class="some class" t-att-class="{b: true}">...</div>

But the code did not work in the other direction:

<div t-att-class="{b: true}" class="some class">...</div>

With this commit, we just add the missing if statement

closes #664
2020-04-21 16:23:31 +02:00
Géry Debongnie 23ce19e57a [REL] v1.0.7 2020-04-17 15:52:52 +02:00
Géry Debongnie aaf40e9bec [IMP] tooling: add iife build to npm package
This is useful to link to the iife version in some other projects.
2020-04-17 15:47:20 +02:00
Géry Debongnie 211f6ebdd6 [REL] v1.0.6 2020-04-17 15:16:24 +02:00
Géry Debongnie 1707bd240d [IMP] add browser bindings to standard environment
This could be done by each application, but it does cost only a few
lines of code, and it helps standardizing the Owl ecosystem.

For example, some library (such as o_spreadsheet) needs to mock side
effects, and Odoo also needs to do that, so this prevents duplicated effort.

closes #686
2020-04-17 13:39:46 +02:00
Géry Debongnie 142b69823f [IMP] types: do not make Env an indexed type
Before this commit, Env was an indexed type, this means that one could
write env.anything, and it would accept it as a valid type. This is
actually quite dangerous, because we lose the typing advantages for all
keys that are properly defined.

For example, if a component is defined as:

class MyComponent extends Component<Props> {
 ...
}

Then Typescript will let it use anything from the environment, even if
it is wrong.  So, most properly typed Typescript applications should use
instead a sub environment:

interface MyAppEnv extends Env {
  someKey: someValue
}

Then, the component should be defined this way:

class MyComponent extends Component<Props, MyAppEnv> {
 ...
}

Before this commit, any typos in the environment accesses would not be
noticed by typescript.
2020-04-17 13:39:46 +02:00
Joseph Caburnay 94c8bce810 [IMP] allow anonymous Component extensions
It is possible that a Component is extended dynamically and if this is
the case, the class that extends it can be anonymous, with property
name=''. If this is the case, current implementation interprets the empty
string to be false so the while loop is terminated without further
scanning the super classes.

In this proposal, we allow anonymous class to be scanned until its
Component ancestor. Basically, the anonymous class assumes the name of
it super.
2020-04-15 08:54:02 +02:00
Géry Debongnie ae172d42e7 [IMP] slots: add new t-set-slot directive
This new t-set-slot directive is meant to replace t-set when we need to
define the content of a sub slot. All new code should use that
directive.

The old t-set directive is still supported for now, but this should be
removed when we publish Owl 2.0.
2020-04-06 15:42:32 +02:00
Géry Debongnie ddf30a8a97 [CLEANUP] run prettier on the codebase 2020-04-06 15:42:32 +02:00
Géry Debongnie 8d0d8538ad [FIX] slots: better heuristic to determine named slot content
Unfortunately, we chose to use the directive `t-set` to define sub slot
contents in a template.

The goal was to reuse a directive for a similar use case: defining sub
template is almost the same as defining a slot content.

Obviously, this introduces a name conflict: the inner content of a
component cannot use t-set t-value anymore (nor t-set with a body
value), since they are interpreted as slot names.

We mitigate the issue here by only interpreting as slot content the
`t-set` statement located immediately below the parent component tag
name and with a body content.

However, a real fix need to introduce an additional directive to resolve
the ambiguity.
2020-04-06 15:42:32 +02:00
Joseph Caburnay 2b0315c03f [FIX] hooks: order of brackets for multiple async hooks 2020-03-30 08:46:16 +02:00
lucas c469cac315 [FIX] qweb: protect scope in t-call writing recursively
Have something like
```xml
 <div t-name="Parent">
   <t t-call="nodeTemplate">
     <t t-set="recursive_idx" t-value="1"/>
     <t t-set="node" t-value="root"/>
   </t>
 </div>

 <div t-name="nodeTemplate">
   <t t-set="recursive_idx" t-value="recursive_idx + 1"/>
   <p><t t-esc="node.val"/> <t t-esc="recursive_idx"/></p>
   <t t-foreach="node.children or []" t-as="subtree">
     <t t-call="nodeTemplate">
       <t t-set="node" t-value="subtree"/>
     </t>
   </t>
 </div>
```

Where we want to propagate a recursion index through recursive t-calls

Before this commit, it did not work as we protected the scope in order
to not leak, in the wronf manner. Namely the protected scope only took
firt level prototype properties of the original scope.

After this commit, this case works as we mark the scope as read only

solves #672
2020-03-12 13:15:28 +01:00
Lucas Perais (lpe) b4ad14edc0 [FIX] component: self mounting position keeps the reference
Have

```xml
<body t-name="webclient" />
```
and
```js

const comp = new WebClient();
comp.mount(document.body, {position: 'self'});
```

Before this commit, the body that was there before anything had happened
was *replaced* by the new body node created by the WebClient OWL component

After this commit, we ensure that the element body is the same at reference level
2020-03-05 16:35:33 +01:00
Aaron Bohy 718e5264ae [FIX] test: missing await 2020-03-03 10:42:22 +01:00
Aaron Bohy f5d019bb69 [FIX] component: concurrency issue with cancelled fiber
Since ee956a197, the rendering is skipped if the currentFiber is
completed. Unfortunately, cancelled fibers remain set in __owl__,
so when a fiber is cancelled, subsequent calls to render are
skipped.

It would be nice to reset __owl__.currentFiber to null when the
fiber is cancelled, but when trying to do so, a lot of tests fail.

Part of issue #622
Closes #665
2020-03-02 11:35:47 +01:00
Géry Debongnie afa36f52a0 [DOC] doc: fix t-debug example
also, remove a useless console.log

closes #661
2020-02-24 11:05:12 +01:00
Géry Debongnie fd6327b068 [REL] v1.0.5 2020-02-21 09:47:01 +01:00
Géry Debongnie d5098dd138 [MISC] set package.json license field to a valid SPDX expression
closes #646
2020-02-21 09:32:35 +01:00
Géry Debongnie ce052e0992 [FIX] transition: no crash if added/removed quickly
This commit should fix crashes coming from transition code on nodes.
This does not impact transitions on components.

closes #637
closes #641
2020-02-21 09:30:47 +01:00
Géry Debongnie b00188c1ce [IMP] qweb: add support for event capture
In this commit, we uses the "!" as suffix to designate an event that
should be captured.  This is inspired by the Vue source code.

This solves the issue of communicating additional information to the
underlying virtual dom.  However, this will most likely disappear when
we rewrite the vdom as a virtual block system.

closes #650
2020-02-21 09:22:43 +01:00
Géry Debongnie 2c01802b8e [FIX] qweb: support attributes with quotes
closes #651
2020-02-21 08:08:55 +01:00
Géry Debongnie 20eb848262 [FIX] component: merge hooks properly
Before this commit, creating a sub component with
t-att-style/t-att-class attributes or with t-on- event handlers would
override the *hook* object rendered by the sub component.

This is an issue for some directives, such as t-ref, which defines
hook functions.

This commit fixes the issue by checking for an override, and wrapping
the hooks in a function that calls each defined hook.

closes #638
2020-02-17 15:50:53 +01:00
Géry Debongnie 8b479749b7 [IMP] add yarn.lock to .gitignore 2020-02-17 13:06:23 +01:00
Géry Debongnie f7728b93bd [FIX] component: cancel previous mounting operations if necessary
closes #626
2020-02-17 12:49:32 +01:00
Géry Debongnie 03585d8fea [DOC] add dedicated page on error handling
closes #632
2020-02-17 09:11:04 +01:00
Géry Debongnie 047a9c8993 [DOC] add dedicated page on event handling
part of #632
2020-02-17 09:11:04 +01:00
Géry Debongnie 69d35abe4f [DOC] add a dedicated page on slots
closes #640
2020-02-17 09:11:04 +01:00
Géry Debongnie 1d7503913e [FIX] qweb: ignore comment nodes between t-if/t-elif/t-else
closes #636
2020-02-17 08:10:20 +01:00
Géry Debongnie ee956a1977 [FIX] component: resolve a subtle concurrency issue
Asynchronous rendering is subtle. Before this commit, it was possible
(though not easy) to get into a situation where the Owl rendering
pipeline decremented twice the counter of a fiber that indicates that
its work is complete.

The situation occurs in the `render` method, where we create a fiber,
wait for a micro tick before starting the actual rendering (the goal was
to batch all changes coming from a single call stack). However, in this
microtask tick, it was possible that the fiber was cancelled, and we did
not have a check for that.
2020-02-07 14:19:43 +01:00
Géry Debongnie 3fdc7a48f3 [IMP] types: make component generic types optional
In most cases, we just want Component<any, Env>. But since it was so
annoying to have always the type Env, we actually used
Component<any,any> everywhere.

With this commit, the generic types have a default (and their order is
swapped), so we can simply use Component in most cases, and
Component<Props> when we want to type the props.
2020-02-06 09:37:44 +01:00
Fabrice Henrion d212309f1b [FIX] typo
Courtesy of the en_US police
2020-02-04 09:03:02 +01:00
Géry Debongnie 8866905f33 [DOC] large refactoring, add section on starting project 2020-02-03 22:06:44 +01:00
Géry Debongnie 50b116c56d [DOC] add information on why odoo made owl 2020-02-03 22:06:44 +01:00
Géry Debongnie a823373220 [FIX] tool: properly wait in release script 2020-01-24 15:25:08 +01:00
Géry Debongnie e402ee62de [REL] v1.0.4 2020-01-21 10:28:50 +01:00
Géry Debongnie 5711eb065d [ADD] tooling: add release script
More work is needed to complete this, but the basics is here, and it is
difficult to test.

closes #612
2020-01-21 10:10:45 +01:00
Géry Debongnie 6739e79aac [ADD] tools: add single file component example to playground 2020-01-21 09:27:30 +01:00
Géry Debongnie 1c8dc97fca [FIX] component: can mount on different target without unmounting
closes #616
2020-01-21 09:26:38 +01:00
Géry Debongnie f9cac94dc7 [REF] tests: split component.test into multiple files 2020-01-21 09:26:38 +01:00
Géry Debongnie c62c3fea19 [FIX] types: improve type of useExternalListener
so it can work on window

closes #613
2020-01-21 08:11:40 +01:00
Géry Debongnie 3845607feb [DOC] store: clarify how a component can find a store
closes #617
2020-01-21 08:08:14 +01:00
Géry Debongnie 3fcbb9ad16 [REL] v1.0.3 2020-01-09 16:27:18 +01:00
Géry Debongnie e04b160bff [REL] v1.0.2
v1.0.2 because I am fighting with npm...
2020-01-09 15:12:32 +01:00
Géry Debongnie bc234d2053 [ADD] tools: add benchmarks for 1.0.0 2020-01-09 14:52:27 +01:00
Géry Debongnie 3d0f046d9a [REL] v1.0.0
Finally!!
2020-01-09 14:37:36 +01:00
Géry Debongnie 4c75bae0e8 [IMP] owl: improve npm packaging
closes #611
2020-01-09 14:35:13 +01:00
Géry Debongnie 54f5819ef9 [ADD] hooks: add useExternalListener hook
It is very useful.

Also, this commit prettifies the code.

closes #608
2020-01-09 14:06:30 +01:00
Joseph Caburnay 0c9c5b877b [FIX] playground: not all completed is deleted
Before this fix, not all completed tasks are deleted when clicking clear
completed button because we are looping to a mutated array. Looping thru
a copy of the mutated array fixes this problem.
2020-01-09 09:40:13 +01:00
Joseph Caburnay b7b0e38fca [FIX] docs: some spelling corrections 2020-01-09 09:40:13 +01:00
mcm-odoo 74bd119bf5 [IMP] styles: handle & selector
This commit adds the support of the & selector.
This selector is useful to join a subrule with a parent selector.

example:

button {
  &:hover {
    background-color: red;
  }
}

will give

button:hover {
  background-color: red;
}
2020-01-09 09:37:27 +01:00
Géry Debongnie 4a0d04e4ae [FIX] debug tools: do not crash on non json-stringifiable props
closes #595
2020-01-09 09:24:50 +01:00
Géry Debongnie 49931104a1 [CLEANUP] update snapshots 2020-01-08 16:05:22 +01:00
Lucas Perais (lpe) 21d1306ec2 [FIX] qweb: t-foreach needs to hold on scope
Have a t-on within a t-foreach
the t-on has an expression

Before this commit, when triggering the t-on, the expression was falsely evaluated
In details, the expression took scope from outside the foreach loop
as we protect it to have similar results than an actual for loop

But, at triggering time, the scope protection had already been terminated
meaning the info of the iteration of the loop the handler has been built in
had already disappeared

This commit fixes that

closes #594
2020-01-08 15:45:44 +01:00
Lucas Perais (lpe) 21737d33fa [FIX] qweb: variables set outside foreach must be altered by inloop t-tset
In a template, have t-set t-value outside a t-foreach
in the t-foreach, alter that variable by resetting it (as for a incrementation variable)

Before this commit, when printing the variable when the loop had finished
its value was the one set in the first place

After this commit, the value becomes the one altered by the loop iterations

closes #598
2020-01-08 15:45:44 +01:00
Géry Debongnie 23012f3e7c [FIX] component: multiple t-calls
Before this commit, owl could crash in some specific situations:
multiple t-calls with sub components, outside a loop.  The reason is
that the t-call did not generate a key, so from the point of view of the
children component, it had the same key, even though it was at a
different place in a template.

Also, with this fix, we can fix the playground responsive example.

closes #602
2020-01-08 15:24:43 +01:00
Géry Debongnie 55889febd5 [FIX] qweb: add support for "in " operator in expressions
closes #603
2020-01-08 15:20:01 +01:00
mcm-odoo 0af46bc123 [FIX] styles: fix selector generation
This commit fixes the css selector generation for nested rules

Before this fix, a selector like:

.parent {
	.child-a, .child-b {
		color: red;
	}
}

was generated as:

.parent .child-a, .child-b {
	color: red;
}

Now it generates:

.parent .child-a, .parent .child-b {
	color: red;
}
2019-12-27 12:31:17 +01:00
Géry Debongnie b63cd4c9d9 [REL] v1.0.0-beta5 2019-12-20 11:26:53 +01:00
Géry Debongnie 953778dc50 [IMP] component/tags: add inline css tag
This add an important feature: defining completely standalone owl
components, with the template/style and javascript code together.

closes #284
2019-12-20 11:20:10 +01:00
Géry Debongnie 4f61d9f1e0 [FIX] component: no crash if empty props
The expression parser properly format an empty string into an empty
string. But then, this empty string was injected in the props object of
a component, and the compiled code looked like this:

let props5 = { val: };

So, in this case, we simply put undefined, since there are no props
value.

closes #587
2019-12-19 14:32:10 +01:00
Sébastien Theys bc2c7edff4 [FIX] store: prevent crash when selector returns null
Because `typeof null === 'object'`.
2019-12-19 14:24:36 +01:00
Géry Debongnie c8d9c0b50e [DOC] add npm install instruction 2019-12-19 14:12:00 +01:00
Géry Debongnie 15b25fd838 [IMP] owl: prepare owl to be released on npm
closes #196
2019-12-19 14:09:41 +01:00
Géry Debongnie 1db0f5ac9b [REL] v1.0.0-beta4 2019-12-17 15:26:49 +01:00
Géry Debongnie 6465665550 [FIX] qweb/component: handle nested t-foreach and components
The way keys were handled in QWeb was mostly ok, but a little naive. It
is fine when we deal with a list of dom nodes, since the reconciliation
algorithm need only to be able to differentiate/reconcile nodes in that
list, but it is an issue with components, which needs to globally be
able to find themselves in their parent's children map.

Because of the way this was handled, there were situations were Owl
internal virtual dom would crash, since components wrongly assumed that
they were already rendered in a different place.

To fix this, we generalize the way keys are generated, by concatenating
all sub keys coming from each iteration loops.

closes #584
2019-12-17 15:23:24 +01:00
Géry Debongnie 9216c5c24b [FIX] qweb: t-call properly transfer key to sub components
Since t-call is now a function call, we need to properly handle the
internal key used to find previous components.  If a t-call is inside a
t-foreach, then we need to transfer the key to the sub template.
Otherwise, each component in the subtemplate will be associated to the
same key, which means that it will lead to big issues: components are
destroyed and reused...

closes #581
2019-12-16 20:30:34 +01:00
Géry Debongnie d9bf4284c6 [REL] v1.0.0-beta3 2019-12-16 09:56:35 +01:00
Géry Debongnie ef6fd457f8 [FIX] qweb: add support for spread operator
closes #575
2019-12-13 22:35:26 +01:00
Sébastien Theys 455e45c148 [FIX] store: make Array.map work correctly on the result of selector
closes #577
2019-12-13 20:32:02 +01:00
Lucas Perais (lpe) 5e7f1d5e6d [FIX] qweb: t-call must pass extra parent
Before this commit, when template was t-call'ed and defined
t-component directive within it, there was a crash because extra.parent was never defined

After this commit, this use case works
2019-12-13 20:28:49 +01:00
Géry Debongnie 0b05ad619f [FIX] qweb: t-set with a body should not be joined with comma
closes #574
2019-12-13 20:15:37 +01:00
Géry Debongnie 29a80d0b28 [FIX] qweb: properly display falsy values
While it is not tested, nor documented, the reference QWeb
implementation display the `false` value as "false". So, we have to
adapt the Owl implementation to match that behaviour.

At the same time, this commit uses 'let' instead of 'var' in various places,
to make the compiled code more consistant.
2019-12-13 14:48:19 +01:00
Géry Debongnie 0931a4dc5b [FIX] qweb: bind handlers to component
Before this commit, the handlers were bound to the current context,
which is often the component but not necessarily.  In some cases, a sub
scope can be created (with t-foreach, or slots, or t-call), and the
context is actually an object with the actual component instance it its
prototype chain, but not the component.
2019-12-12 14:32:43 +01:00
Géry Debongnie 4e22dbcad6 [FIX] qweb: accept assignations in qweb expressions
closes #560
closes #569
2019-12-12 14:32:43 +01:00
Géry Debongnie b283e65ad4 [REF] qweb: improve t-on generated code
and deduplicate logic between directive t-on applied on a node and on a
component
2019-12-12 14:32:43 +01:00
Géry Debongnie f517d44e32 [IMP] qweb: slightly simplify generated templates
- In some cases, we can simply inline a template key instead of assigning
  it to a variable and then using that variable
- Add component name in generated code for components
2019-12-12 09:39:26 +01:00
Lucas Perais (lpe) 08022b49df [FIX] qweb: conditional t-call with body
When a t-call has a condition and a body
the t-if's and its flavors should be ignored when compiling the body of a t-call
2019-12-11 14:09:45 +01:00
Géry Debongnie b96ea79f2b [FIX] qweb: renderToString now properly escape
closes #565
2019-12-11 12:25:05 +01:00
Géry Debongnie 97d8b3ed8c [REF] tests: remove Widget common class
Bad name, and bad practice to use it. It makes tests less standalone.
2019-12-11 12:25:05 +01:00
Géry Debongnie 9921ae07b1 [REF] tests: move slots tests out of main component file 2019-12-11 12:25:05 +01:00
Géry Debongnie 41cb5f1abd [FIX] *: remove useless values to t-else and t-debug
The actual value does not matter, only the fact that it is present.

closes #564
2019-12-11 12:25:05 +01:00
Géry Debongnie 0762eeb010 [REL] v1.0.0-beta2 2019-12-11 10:19:04 +01:00
Géry Debongnie bc455be720 [IMP] components: slots can now define default content
closes #554
2019-12-11 10:11:47 +01:00
Lucas Perais (lpe) 9145799ae9 [FIX] qweb: evaluate body of t-set immediately 2019-12-11 10:07:41 +01:00
Géry Debongnie ce9c2f8613 [FIX] qweb/component: refactoring of scoping/variables/slots
This commit is a significant refactoring of the internal of QWeb. It
simplifies the way variables/scoping and slots interact together.  The
main idea is that we use a simple scope object instead of a
context/var/scope object.

This commit also implement the actual correct QWeb semantic for the
t-call directive with a sub body.  Before, we simply extracted the
variables from the body and injected them at the top of the sub
template.  We now simply compile the body before the sub template.

This is a joint work with Lucas (lpe).

closes #541
closes #544
closes #545

closes #557
closes #556
2019-12-11 10:07:41 +01:00
Géry Debongnie b890e7ceae [IMP] qweb: add template name in generated compiled code 2019-12-10 16:14:09 +01:00
Géry Debongnie 124211c18b [DOC] clarify store documentation on connected components
closes #538
2019-12-06 12:25:55 +01:00
Géry Debongnie be8c3bbf6f [IMP] tooling: add warning if component not mounted, but rendered
closes #551
2019-12-06 12:07:54 +01:00
Géry Debongnie e162a6fb6c [IMP] qweb: add support for arrow functions in expression parser
closes #542
2019-12-06 11:49:55 +01:00
Géry Debongnie 7ec05ff8cf [IMP] component: add position option to mount method
A component can now be mounted in different positions: either 'before' (at
the start), 'after' (at the end), or 'attach' (take possession of a target
element)

closes #539
2019-12-06 10:53:01 +01:00
Géry Debongnie a0bfbf6dd0 [FIX] qweb/component: do not call handlers for unmounted components
Unmounted components should be considered inactive, at least from the
perspective of Owl itself.

closes #543
2019-12-06 09:58:12 +01:00
Géry Debongnie b67cb71048 [FIX] slots: propagate vars to correct function
closes #529
2019-12-06 09:53:48 +01:00
Géry Debongnie f5b3ef5cf3 [DOC] add some information on variables and t-call
closes #540
2019-12-05 21:49:51 +01:00
Lucas Perais (lpe) ecfccf2448 [FIX] portal: manually unmounting works
Before this commit, when manually unmounting the portal
or one of its parents, the teleported elements were not cleaned
and stayed teleported forever

After this commit, the teleported content is brought back and
unmounted much like any component

closes #531
2019-12-04 09:48:08 +01:00
Géry Debongnie f12d3373c9 [FIX] qweb: properly handle empty class attribute
The classList.add method actually crashes when given an empty string (or
a string with just white spaces).

closes #530
2019-12-03 16:19:09 +01:00
Géry Debongnie 286090efca [FIX] tooling: debug tool logged too many scheduler stops
This was caused by additional calls to flush (because of connected
components)

closes #533
2019-12-03 15:16:29 +01:00
Géry Debongnie 2b4ff7b2fd [FIX] doc: the debugOwl helper was missing a parameter
closes #532
2019-12-03 14:13:42 +01:00
Géry Debongnie c43178a45b [CLEANUP] observer: remove useless variable 2019-12-03 11:17:37 +01:00
Géry Debongnie 033a431e18 [ADD] tools: add benchmark for 1.0.0-beta1, remove old ones 2019-12-03 09:12:52 +01:00
Géry Debongnie 42aa9d3ae1 [REL] v1.0.0-beta1 2019-12-03 08:52:04 +01:00
Géry Debongnie 85f26a0286 [IMP] tools: update debug script, add tests
closes #525
closes #526
2019-12-03 08:28:46 +01:00
Géry Debongnie ed4ab51c17 [FIX] component: tricky concurrency issue
This is a really interesting problem: there was a situation where a
component would not have an event handler properly bound. The reason was
that we were in a situation where the scheduler task queue was flushed
at an unfortunate timing:

- parent component template is rendered
- subcomponent is prepared:
   - sub component is willStarted
   - it is rendered (so, fiber counter is set to 0)
- scheduler task queue is flushed => we patch the DOM
- the code registered in the __prepare.then(handler) is executed, which
  add the createHook to the vnode (but after the dom is patched)

Usually, the last two steps happen in a different order, but in an
environment with connected components, we sometimes flush the task queue
at various moments, so some code could be executed between the end of
__prepare and the registered handler.

The fix is interesting: we give a callback to the __prepare function
instead of registering a .then handler to the deferred.  This callback
is then guaranteed to be called at exactly the proper timing.

Thanks seb for the hard work of finding the root cause of this issue

closes #520
2019-12-03 08:23:10 +01:00
Lucas Perais (lpe) 556a4644f0 [ADD] misc: component Portal
The component Portal is used to teleport the content
in its slot as a child of an element
somewhere else in the DOM, usually 'body'

It is designed to be transparent and is just here to do the teleportation task

OwlEvents (with method `Component.trigger`) are redirected from
any Component instanciated within the Portal (and therefore teleported
somewhere else) to the place it would have been without teleportation
i.e. they are re-triggered onto the Portal root node

Co-authored-by: Aaron Bohy <aab@odoo.com>

closes #184
closes #466
2019-12-02 21:04:07 +01:00
Géry Debongnie 821bd0b4b8 [IMP] tooling: add debug code
closes #521
2019-12-02 09:03:48 +01:00
Géry Debongnie 06a6d890d7 [DOC] move some component doc in sub pages
closes #354
2019-12-02 08:55:12 +01:00
Géry Debongnie c1269288f5 [REL] v1.0.0alpha5 2019-11-29 16:11:34 +01:00
Géry Debongnie 8c17bb0411 [FIX] component: reorganize fiber update algorithm
Closes #473
Closes #484
Closes #489
Closes #492
Closes #512

Co-authored-by: Aaron Bohy <aab@odoo.com>
2019-11-29 15:13:37 +01:00
Lucas Perais (lpe) 7f6782d009 [FIX] qweb: cascading t-call and t-raw="0"
Have a t-call having a t-raw="0"
that call is made to a template of the same form
i.e. itself as a t-call t-raw="0" structure

Before this commit, there was recursion crash
This was because the caller to which a t-raw="0" referred to
was incorrect. The caller here is the node which makes the t-call.
In particular, the caller was always set to last caller of the context

After this commit, there is no crash and this imbrication
of t-call and t-raw="0" is well rendered.
To sum up, we count the recursive calls to t-raw="0" and fetch
the caller in the context accordingly

closes #510
2019-11-29 13:17:40 +01:00
Aaron Bohy 6e5d6aa226 [FIX] slots: use correct scope and vars at update
Part of #473
2019-11-28 14:42:46 +01:00
Aaron Bohy 9400c0adad [FIX] playground: stop using class fields
as Edge doesn't support them.

Closes #509
2019-11-28 10:21:45 +01:00
Aaron Bohy 85d4393242 [FIX] t-slot: correct parented relationship with nested slots
Closes #506
2019-11-28 10:15:57 +01:00
Aaron Bohy 6c8b401092 [FIX] component: slots: multiple slots with components
Closes #508
2019-11-27 15:47:55 +01:00
Aaron Bohy 12be815342 [REF] qweb: use global nextID
and reset it to 1 before each test s.t. snapshots are deterministic.
2019-11-27 15:47:55 +01:00
Sébastien Theys 65344dbf1f [FIX] store: fix useStore update when mixing state and props changes
This commit also fixes an issue where updates would not be triggered when the
new and old revNumber where the same but concerned a different object.
2019-11-27 15:09:47 +01:00
Sébastien Theys a6f9b26057 [FIX] store: ensure useStore proper clean up on destroy 2019-11-27 15:09:47 +01:00
Géry Debongnie 6c753bb49f [FIX] qweb: scope t-key directive to node and subnodes
not to siblings

closes #503
2019-11-27 13:31:40 +01:00
Géry Debongnie 1f079b883e [IMP] store: prevent changes to store state in useStore return value
closes #500
2019-11-27 08:18:44 +01:00
Géry Debongnie 8fb35ed969 [FIX] owl: add prettier to devDependencies
also, run prettier on codebase

closes #498
2019-11-27 08:06:17 +01:00
Géry Debongnie a3f2d07b40 [DOC] add link to useSubEnv in environment doc 2019-11-26 22:32:25 +01:00
Sébastien Theys c993278c80 [IMP] store: allow useStore to return primitive types
Related to #404
2019-11-26 22:17:05 +01:00
Géry Debongnie 3aa586db43 [IMP] component: allow custom validator functions for props
closes #375
2019-11-22 15:43:22 +01:00
Géry Debongnie 14db513f3b [FIX] component: allow fragments in method mount
It is now possible to mount components in fragments

closes #494
2019-11-22 15:00:37 +01:00
Géry Debongnie 7bb04185c7 [FIX] playground: fix wms sample
It was crashing when we close a window, because there are two event
handlers for the click event on Window.  But when we close a window, we
actually do not want to update the z index.
2019-11-22 13:41:44 +01:00
Géry Debongnie 48744cfa87 [DOC] add hooks explanation, and testing/debug page
closes #372
closes #419
2019-11-22 13:41:44 +01:00
Géry Debongnie ff76747a05 [REL] v1.0.0-alpha4 2019-11-22 13:03:02 +01:00
Aaron Bohy 7e6b1a28a0 [IMP] qweb: throw error if t-component not used on a node t
Before this rev, using t-component on a div (for example) node
would silently ignore the div and replace it by the root node of
the component. A way to improve this was to create an extra div
node and to put the component inside it. However, it raised
questions: what do we do with other attributes set on this tag?
Do we apply them on the div, or on the component? In addition,
some of them only make sense on the component (e.g. props), so we
have to detect them. Whatever we would have decided, it wouldn't
have been obvious from the user point of view, so we chose not to
support it, and we thus now raise an error in this case.

Closes #487.
2019-11-21 17:06:35 +01:00
Aaron Bohy 58f6724194 [FIX] component: reset isRendered when reusing fiber
It is important to reset the isRendered flag to false to ensure
that other (subsequent) simultaneous calls to render will be
skipped, as the currentFiber is actually no yet (re-)rendered.

Closes #483
2019-11-21 15:35:30 +01:00
Aaron Bohy 3c0f8ac76f [IMP] component: introduce OwlEvent
Closes #485
2019-11-21 13:12:22 +01:00
Géry Debongnie cb11c0118c [FIX] context tests: make them deterministic
We learn something new every day, and today is no exception. Promise.all
of a pending promise does not actually resolve as fast as possible after
the initial promise is completed, but a small delay after, because it is
put on the macrotask queue or something like that (I assume)

closes #480
2019-11-20 15:44:12 +01:00
Géry Debongnie 27b4eece66 [FIX] component: display correct error in some case
It could happen that a component would crash. But then, the __render
code tried to copy the class properties into the vnode, which does not
exist, creating a new error.

So, the solution is to process the classObj only in the successful part
of the render call, which then will not crash, so the normal error
handling will occur.
2019-11-20 14:35:25 +01:00
Aaron Bohy 2e3e8cd603 [FIX] component: destroy not yet mounted components (2)
Following 2922cee6ea

Previous commit was not correct: used children with a cancelled
fiber (for instance, with a new currentFiber) could be destroyed.
This commit fixes the issue differently, by directly detecting
children that are not used anymore (and not mounted), and destroy
them directly (no need to wait for willStart promise to be resolved
anymore).
2019-11-20 14:31:03 +01:00
Aaron Bohy 28ee790b3e [FIX] context: always remove subscription when destroyed
Before this rev., components destroyed before being mounted didn't
stop listening to the context changes.

Closes #476
2019-11-20 11:43:14 +01:00
Aaron Bohy 2922cee6ea [FIX] component: can destroy not yet mounted components
Sub-issue of #476
2019-11-20 11:43:14 +01:00
Géry Debongnie 7749fd3b96 [FIX] component: remove stale fiber in scheduler
Owl takes care of not rendering a component that will be unmounted
immediately after, and it works.  However, it also should clean
up the newly added fiber.
2019-11-20 11:24:32 +01:00
Géry Debongnie f44b9a38ae [IMP] component: better coordination for errors in rendering
part of #410
2019-11-20 11:24:32 +01:00
Géry Debongnie c7773bfd2a [FIX] qweb/component: fix scoping issue with t-model and t-foreach
Without this fix, the handler set by t-model did not capture properly
the expression that needs to be updated.

closes #474
2019-11-19 13:15:34 +01:00
Géry Debongnie bd39797f17 [FIX] component: propagate errors to caller
Errors from mounted/willPatch/patched should be returned to caller
(either mount or render functions)

part of #410
2019-11-18 14:29:54 +01:00
Géry Debongnie 94a595ef5b [FIX] qweb: add support for typeof expression
closes #469
2019-11-18 07:57:43 +01:00
Lucas Perais (lpe) f83846e054 [FIX] package, vdom: condition always true, TS 3.7.2
Before this commit, a condition deemed always true made
the building crash. The happened with TypeScript == 3.7.2

After this commit, the required typescript version has been
changed, as well as the incriminated true condition
2019-11-15 13:10:02 +01:00
Géry Debongnie a97144366d [FIX] playground: fix downloaded app code
The generated downloaded code from the playground did not work because
it did not load templates into QWeb anymore.

closes #461
2019-11-15 11:19:27 +01:00
Aaron Bohy 79983de4ed [FIX] context: notify changes even if owner not mounted
Closes #444
2019-11-15 07:34:15 +01:00
Géry Debongnie 54e1734f2f [IMP] component: display better error message if render is empty
closes #446
2019-11-14 16:40:07 +01:00
Géry Debongnie 4aea093ed9 [FIX] tools: fix benchmark for v0.24.0
It was not using the correct owl version
2019-11-14 15:51:53 +01:00
Géry Debongnie 56087b95cd [REF] observer: notify subscribers directly
This rev. moves the logic of batching the notifications of changes
occurring in the same microtask tick, from the observer, to the
listeners (the context, and the render function of components).
By doing so in render, we ensure that similar renderings are
batched in a single one, wherever they come from (state change,
store change, direct call...).
2019-11-14 15:12:31 +01:00
Aaron Bohy e5940b4b6b [FIX] component: concurrent calls to mount and render
Closes #450
2019-11-14 15:12:31 +01:00
Géry Debongnie bbdc9d90d7 [FIX] qweb: allow mixing body and expression variables
closes #445
2019-11-14 14:54:27 +01:00
Géry Debongnie f2b3ebd1ec [FIX] component: properly set currentFiber to null in all cases
Whenever a rendering is completed, we need to reset the currentFiber
to null to make sure all subsequent renderings will not be
confused.

However, the way it was done before this commit was wrong in a
specific situation: we resetted the currentFiber to null in the
patch method.  The idea was that this method was called every time
the component completes a rendering. But this is not true: it
can happen that a component is unmounted and remounted without
changes.  Then the component will be patched, but if there is no
change, it will not call recursively the patched methods of its
children.

So, we need to choose a better place to reset it to null.

closes #454
2019-11-14 11:56:13 +01:00
Géry Debongnie 55bb09ba1a [FIX] component: fix invalid prop validation situations
closes #453
2019-11-14 09:27:09 +01:00
Géry Debongnie d249f50d09 [REL] v1.0.0-alpha3 2019-11-13 15:43:47 +01:00
Géry Debongnie 749f0063ea [FIX] component: properly validate optional types in objects
closes #440
2019-11-13 15:36:46 +01:00
Géry Debongnie 263f31fea9 [DOC] miscellaneous improvements
including:

- add a link to the tutorial in the main readme page
- remove learning page on 'env', move content on reference page
- add dynamic sub components section in component page
- add reference page on props
- split qweb page into engine/language pages
- move t-key information into qweb language page
2019-11-13 08:49:25 +01:00
Géry Debongnie b891ae7de4 [REM] tools: remove error handling in playground
There was some code to attempt to display the error in the right
pane, whenever it occured in the app early phase.

However, it made it much harder to properly handle all cases. It could
silently swallow some errors (if more than one was done), And it was
not behaving the same way in Firefox and in Chrome.
2019-11-13 08:49:25 +01:00
Géry Debongnie c5a80497ac [FIX] tooling: properly set playground in dev mode
It was not in dev mode since changes to config system
2019-11-13 08:49:25 +01:00
Aaron Bohy e47f604449 [FIX] component: concurrent rendering issue
Resolved rendering with cancelled fiber for (not yet) destroyed
component -> Cannot read property 'sel' of null

Closes #421
2019-11-12 10:01:12 +01:00
Aaron Bohy 7e721a96b5 [IMP] hooks: useRef on component: set el anyway
Closes #437
2019-11-06 17:06:37 +01:00
Aaron Bohy af4f372506 [REF] component: mount: remove renderBeforeRemount option
Re-render the component all the time before remounting it, which
seems safer anyway.

In the test, we had to add a nextTick to wait for the changes to
be notified (before, we waited thanks to the additional call to
mount). If we don't do the nextTick, mount is called, and render
is called right after (before the promise returned by mount is
resolved). This scenario doesn't work right now (see #441).

Closes #381
2019-11-06 16:26:12 +01:00
Aaron Bohy 5731358607 [IMP] component: expose scheduler instance
Closes #433
2019-11-05 15:11:13 +01:00
Géry Debongnie 1226f015d7 [DOC] add a tutorial (TodoApp) 2019-11-04 16:50:16 +01:00
Géry Debongnie b211e75140 [IMP] store: display error if no store found 2019-11-04 08:41:29 +01:00
Géry Debongnie 8d1dd06340 [IMP] component: error when mounted on invalid target 2019-11-04 08:41:29 +01:00
Géry Debongnie bd3c1265d3 [REL] v1.0.0-alpha2 2019-11-01 09:12:33 +01:00
Géry Debongnie 2413c98f50 [REF] component: small optimization in rare cases
When we have default props, we do not need to allocate a new
props object and copy it. This commit simply modify the props
object in place, which is fine, since the props object is always
a new one any way, generated by the directive.
2019-11-01 09:03:30 +01:00
Géry Debongnie d74b5a03db [IMP] component: add props on root components
This is a partial revert of commit 7d249d6f09.

The reason is that this changes made it much harder to unit test
components.  Before, we could simply instantiate a component
like this:
const my|Comp = new MyComponent(null, props);

and then simply test it.  This commit reestablish that possibility.
2019-11-01 09:03:27 +01:00
Géry Debongnie 83532db48f [DOC] adapt documentation to env changes
part of #430
2019-11-01 09:03:27 +01:00
Géry Debongnie 534152eff7 [REF] component: small improvement
and run prettier
2019-11-01 08:39:35 +01:00
Aaron Bohy 05a678c039 [IMP] component: get env from constructor
closes #430
2019-11-01 08:39:35 +01:00
Géry Debongnie 8fbf2172c5 [DOC] slightly reorganize main documentation page 2019-10-31 12:32:26 +01:00
Géry Debongnie ea1376d0ca [FIX] tools: make benchmarks work on firefox
Firefox does not support the static keyword yet, so the benchmark code should be modified to make it work.
2019-10-31 12:32:26 +01:00
Géry Debongnie ba483b6e2c [FIX] component tests: make them work on windows
For an unknown reason, it looks like the way ticks, micro task ticks or other subtle scheduling issues are different on a windows machine (it may be because of other difference, such as a specific version of nodejs).

Anyway, I could not find the cause of the issue, but
simply waiting an extra microtask tick seems to work.
2019-10-31 12:32:26 +01:00
Géry Debongnie 2fc71cfb62 [REL] v1.0.0-alpha
v1.0alpha

The Alpha release!

Owl is finally getting stable. This relase is all about cleaning Owl
API.  We
are pretty happy with the current state, and hopefully, we won't have to
make
any non trivial change for a while.

QWeb

- add an option to setup a translate function
- implement `t-key` with a directive (it now works on `t` tags)

Component

- properly handle errors in `mount` and `render`
- fix: make sure props are validated in all cases
- fix: make sure default props are applied at the proper time
- fix: better error handling with sub components
- imp: simplify constructor API: does not take an `env`
- imp: do not set `props` in root components
- remove `t-keepalive` directive

Context

- update components concurrently, instead of sequentially

Observer

- remove `revNumber` (and rename `deepRevNumber` into `revNumber`)

Router

- fix: preserve pathname in hash mode

Config

- create new config object, with `mode` and `env` keys

Playground

- log git commit hash in console
2019-10-30 16:35:45 +01:00
Aaron Bohy 08cb83149e [REM] component: remove t-keepalive directive
We don't see any usecase for it, it makes the code more complex,
and there were still potential unresolved concurrency issues with
it.

Part of task #295
2019-10-30 16:35:45 +01:00
Aaron Bohy 7d249d6f09 [IMP] component: do not set props in root components
Also remove props from Fiber, as it was not useful anymore.
2019-10-30 15:09:10 +01:00
Géry Debongnie 0addca63a0 [DOC] update the documentation to new config and env
part of #306
2019-10-30 15:09:10 +01:00
Géry Debongnie 5ba73cc09d [DOC] move quick_start into learning/ sub folder 2019-10-30 15:09:10 +01:00
Aaron Bohy 9106c19066 [IMP] component: simplify constructor API
It now takes two arguments: parent (optional, only for non-root
components) and props (optional). In the case of the root component,
the env is taken from the config (config.defaultEnv). If it doesn't
exists, the default env is created on the fly.

Closes #306
2019-10-30 15:09:10 +01:00
Aaron Bohy 9f93da4765 [REF] config: move mode from owl.__info__ to owl.config
and move it to its own file.
2019-10-30 15:09:10 +01:00
Aaron Bohy 9e37b968e8 [FIX] component: error handling: rendering with sub components
Closes #425
2019-10-30 13:27:48 +01:00
Aaron Bohy fa6801b523 [REF] observer: remove revNumber
Closes #257
2019-10-30 11:13:52 +01:00
Géry Debongnie 9edf29a3a1 [IMP] context: group components by depth
closes #399
2019-10-29 16:02:51 +01:00
Géry Debongnie 6a434310ee [FIX] *: run prettier 2019-10-29 16:02:51 +01:00
Géry Debongnie e7967d0779 [FIX] package.json: improve prettier task
to take into account files at more than one level
2019-10-29 16:02:51 +01:00
Géry Debongnie b0e2ef82f7 [REL] bump to v0.24.1 2019-10-28 14:58:52 +01:00
Aaron Bohy c9c2b3fa6d [IMP] tests: add concurrency test 2019-10-28 14:46:21 +01:00
Géry Debongnie 62608cbb0d [DOC] add architecture notes on rendering pipeline 2019-10-28 14:23:02 +01:00
Géry Debongnie 3035a9f009 [DOC] move reference doc in subfolder 2019-10-28 14:23:02 +01:00
Géry Debongnie c2adb429bd [FIX] package.json: update node and typescript version
closes #414
2019-10-28 13:58:44 +01:00
Géry Debongnie da9dda5eca [DOC] component: add more information on t-key
closes #353
2019-10-28 11:45:51 +01:00
Géry Debongnie 5614c85b04 [IMP] qweb: implement t-key with a directive
closes #331
2019-10-28 11:45:51 +01:00
Aaron Bohy 5d57a7bf13 [FIX] component: updateProps: validation and default values
Before this rev., default values weren't taken into account when
validating props whenever a component was updated. Moreover, there
was no test attesting that props were validated at update.
2019-10-28 11:32:43 +01:00
Géry Debongnie 4ebe419c56 [FIX] component: make sure props are validated in all cases
closes #379
2019-10-28 11:32:43 +01:00
Géry Debongnie 9779cd196c [REF] fiber: small cleanups 2019-10-28 11:32:43 +01:00
Géry Debongnie 9cee12d7b4 [IMP] component: propagate error to mount and render 2019-10-28 11:32:43 +01:00
Géry Debongnie 2c563ee380 [REF] component: move error handling into the fiber 2019-10-28 11:32:43 +01:00
Géry Debongnie 2aa705f5c8 [FIX] router: preserve pathname in hash mode
closes #397
2019-10-28 11:32:43 +01:00
Géry Debongnie 5911c8e3f6 [DOC] store,hooks: useState/useStore should return object
or array

closes #404
2019-10-28 11:32:43 +01:00
Géry Debongnie 2279dafbec [IMP] qweb: add an option to setup a translate function
closes #393
2019-10-28 11:32:41 +01:00
Géry Debongnie f07ec21a07 [FIX] playground: add missing ;
Because of that missing ";", the playground application tried to inject
this:

window.TEMPLATES = `...`

instead of this:

window.TEMPLATES = `...`;

So, when the following line started with a (, then the javascript code
was interpreted as a function call. And it could happen, because some
people like to use the IIFE syntax to have some contained code.
2019-10-26 09:34:51 +02:00
Géry Debongnie b5b6b7342e [DOC] improve main readme.md 2019-10-26 09:27:35 +02:00
Géry Debongnie 97b914b9cd [IMP] playground: log url for current owl commit
closes #405
2019-10-26 09:21:04 +02:00
Géry Debongnie 9dfcfda365 [DOC] add more info on xml tag and single file component
closes #401
2019-10-26 09:10:50 +02:00
Géry Debongnie e026f537ae [ADD] tools: add benchmarks for v0.24.0 2019-10-25 17:17:20 +02:00
Géry Debongnie f0b5a55ad1 [REL] bump to v0.24.0 2019-10-25 17:07:51 +02:00
Géry Debongnie 690d8edf67 [FIX] context: solve tricky concurrency issue
part of #330
2019-10-25 16:01:52 +02:00
Géry Debongnie 3c38bbc076 [REF] component: large cleanup of concurrency branch
We remove here old comments, add some tests and documentation, and in
general, make sure the state of the code is in a good shape

part of #330
2019-10-25 16:01:52 +02:00
Aaron Bohy 9c5cad15c1 [IMP] component: refactor rendering pipeline
This commit introduces a brand new rendering system based on a fiber
class and a scheduler.

closes #330
2019-10-25 16:01:52 +02:00
Géry Debongnie 2bed1cfbd1 [REF] asyncroot: create asyncroot component
This component replaces the t-asyncroot directive.
2019-10-25 16:01:52 +02:00
Géry Debongnie caa9ac5cb2 [ADD] project: add prettier task to package.json 2019-10-25 16:01:52 +02:00
Géry Debongnie 67349eb0f0 [IMP] vdom: remove handling of combined selectors
this is done by qweb anyway
2019-10-25 16:01:52 +02:00
Géry Debongnie 1ca401811f [DOC] add example of inline statement in main doc 2019-10-25 14:56:09 +02:00
Aaron Bohy 2beb12678e [IMP] t-on directive: allow empty handler
Closes #377
2019-10-25 14:11:44 +02:00
Aaron Bohy 0ea1091692 [IMP] t-on directive: handle inline statements
Closes #265
2019-10-25 14:11:44 +02:00
Nicolas Bayet 71827c3ba8 [DOC] explain router history and hash mode 2019-10-25 13:36:18 +02:00
Géry Debongnie c2f42d3b82 [FIX] qweb: do not format expression twice in t-if
closes #392
2019-10-24 14:57:48 +02:00
Géry Debongnie a3317ab997 [FIX] qweb: handle variable expressions in t-if
closes #390
closes #362
2019-10-24 08:55:30 +02:00
Géry Debongnie 403935a41e [DOC] qweb: document t-att variant
closes #378
2019-10-22 22:03:10 +02:00
Géry Debongnie 39af9ec938 [DOC] improve store documentation on useGetters
closes #386
2019-10-22 22:00:41 +02:00
Géry Debongnie 13128ed425 [FIX] component: do not validate props twice
it is not useful to do it in the component directive, especially since
it is done in the constructor, and the default props are not applied.

closes #379
2019-10-22 21:58:51 +02:00
Géry Debongnie be556a970e [FIX] qweb: properly calls directive finalizers
closes #382
2019-10-22 21:56:29 +02:00
Aaron Bohy da6c24bbca [FIX] test: do not check external links in doc 2019-10-21 09:47:20 +02:00
Géry Debongnie f6d6da8393 [FIX] component: fix issues with component internal template key
closes #298
2019-10-21 09:41:27 +02:00
Géry Debongnie 918945c11e [DOC] improve the comparison documentation page
closes #365
closes #366
2019-10-20 14:46:01 +02:00
Géry Debongnie 29c2c5b9c9 [DOC] improve the documentation
closes #340
closes #344
closes #352
closes #355
2019-10-20 09:17:52 +02:00
Aaron Bohy 1bb4577ec1 [DOC] improve hooks and qweb doc
Closes #358
Closes #359
2019-10-18 09:42:03 +02:00
Géry Debongnie 0aeebd7b6e [REF] utils: rename loadTemplates into loadFile
closes #351
2019-10-18 08:05:26 +02:00
Géry Debongnie 4bc49e7241 [DOC] add a roadmap
closes #347
2019-10-17 22:36:44 +02:00
Géry Debongnie 2b5783d9bd [FIX] playground: update samples to make them work on firefox
Sadly, Firefox does not support yet static class fields, so we need to
use an equivalent, but slightly not as nice, syntax.

closes #335
2019-10-17 16:57:40 +02:00
Géry Debongnie 1f40f113aa [DOC] update the documentation
closes #334
closes #336
closes #338
closes #339
closes #341
closes #342
closes #343
closes #346
closes #348
2019-10-17 12:08:24 +02:00
Géry Debongnie 9e65b0686f [REL] bump to v0.23.0 2019-10-16 22:31:04 +02:00
Géry Debongnie 1d72164015 [FIX] component: support component reduced to a slot 2019-10-16 21:48:49 +02:00
Géry Debongnie 2825a5a55d [FIX] qweb: properly handle xml comments 2019-10-15 15:47:50 +02:00
Géry Debongnie d40ff53f5a [DOC] doc: add more information in store section 2019-10-14 15:00:31 +02:00
Aaron Bohy 23246c42aa [REF] *: snakecase filenames 2019-10-14 11:06:59 +02:00
Géry Debongnie 895fe7c60f [REF] store: replace ConnectedComponent by useStore hook
Closes #304
2019-10-14 11:06:59 +02:00
Géry Debongnie 19b10f7c1d [IMP] playground: update todoapp sample 2019-10-14 11:06:59 +02:00
Géry Debongnie 0788d9fe75 [REF] qweb: rename Context into CompilationContext 2019-10-14 11:06:59 +02:00
Géry Debongnie 4a346d0615 [FIX] qweb: properly remove t-ref reference
when the node is removed from the dom
2019-10-14 11:06:59 +02:00
Géry Debongnie 1337aa0107 [IMP] component: add current key for easier hook creation
closes #319
2019-10-14 10:25:34 +02:00
Géry Debongnie 3e8f60cefa [FIX] qweb: properly handle t-raw in various situations
closes #325
closes #327
2019-10-14 09:59:26 +02:00
Géry Debongnie 41b0618c93 [FIX] qweb: improve generated compiled code 2019-10-11 14:10:44 +02:00
Aaron Bohy 0928c189f4 [FIX] qweb: allow to combine t-esc with other directives
With this rev., when a t-esc is not set on a <t> tag, we create
it inside the node on which it is set, to ensure that the t-esc
directive is always set on <t> tags.

Same applies for t-raw.

Closes #324
2019-10-11 14:10:44 +02:00
Aaron Bohy 2f27768be2 [FIX] qweb: event modifier with arg in t-foreach
Closes #266
2019-10-11 14:01:07 +02:00
Aaron Bohy aa1b0f502d [FIX] tests: fix import 2019-10-11 14:01:07 +02:00
Géry Debongnie da1824f4dd [DOC] doc: improve navigation to main doc page
also, fixes a small error
2019-10-10 12:28:36 +02:00
Géry Debongnie 07dac970f7 [IMP[ component/hooks: add onWillStart and onWillUpdateProps 2019-10-09 15:09:26 +02:00
Géry Debongnie 5f6f081ae2 [IMP] playground: save changes to local storage
closes #316
closes #101
2019-10-09 10:15:09 +02:00
Géry Debongnie 1c3c2e5c51 [IMP] hooks/Context: add Context and useContext
Closes #310
2019-10-08 15:56:46 +02:00
Aaron Bohy 17ce73e6a9 [REF] hooks: improve makeLifecycleHook 2019-10-08 15:52:44 +02:00
Géry Debongnie cedb1f411f [REF] component: move template check in constructor 2019-10-08 13:51:55 +02:00
Géry Debongnie e7516be95c [DOC] component: remove doc for removed updateEnv method 2019-10-07 16:07:56 +02:00
Géry Debongnie 683993dbc4 [FIX] component/hooks: onWillUnmount was not properly called 2019-10-07 16:01:28 +02:00
Géry Debongnie 50d569411c [DOC] hooks: fixing broken link 2019-10-07 15:51:45 +02:00
Géry Debongnie c3453d35b9 [IMP] hooks/component: remove updateEnv, add useSubEnv
closes #182
2019-10-04 22:54:27 +02:00
Géry Debongnie b0dd0252a4 [REF] component: move method at proper place 2019-10-04 22:54:27 +02:00
Géry Debongnie e2b2e54e29 [DOC] tooling: add missing link 2019-10-04 22:12:56 +02:00
Géry Debongnie 766c378ac9 [DOC] hooks: add missing doc for onWillPatch/onPatched 2019-10-03 11:57:58 +02:00
Géry Debongnie 022b29b6a0 [IMP] component/qweb: remove t-mounted directive
The t-mounted directive main goals can be achieved with hooks, in a
better and more intuitive way.

closes #308
2019-10-03 10:57:24 +02:00
Géry Debongnie 367725d194 [IMP] hooks: add onWillPatch and onPatched
This commit also changes the behaviour of willPatch and patched: they no
longer transfer data from one to the other, because it can be done
cleanly by hooks and a closure.

closes #307
2019-10-03 10:20:28 +02:00
Géry Debongnie e82ed7dc8c [DOC] component: add information on svg components 2019-10-02 16:40:13 +02:00
Géry Debongnie 63c3d4f6b0 [IMP] playground: slightly improve default text 2019-10-01 21:37:36 +02:00
Géry Debongnie b859fcb8f0 [REL] bump to v0.22.0 2019-10-01 21:05:04 +02:00
Géry Debongnie 3005756d89 [LEGAL] add copyright file 2019-10-01 20:44:39 +02:00
Géry Debongnie f6820bb8ac [REF] hooks: better implementation of onMounted/onWillUnmount 2019-09-28 21:14:40 +02:00
Géry Debongnie 090880f478 [DOC] readme: add quick overview section 2019-09-27 17:34:27 +02:00
Géry Debongnie 5cdaa7b473 [IMP] hooks: implement useRef hook
closes #194
2019-09-27 11:20:08 +02:00
Géry Debongnie 91b9e78182 [DOC] update component, tooling doc 2019-09-27 11:20:08 +02:00
Géry Debongnie 5335fb8fba [IMP] components: add hooks mechanism
part of #194
2019-09-27 11:20:08 +02:00
Géry Debongnie 4513e3f31c [FIX] qweb: improved svg support for components
If we want to generate dynamically svg components, it is useful to be
able to define components with a <g> tag as root, and then getting the
correct namespace.

closes #302
2019-09-26 15:46:42 +02:00
Géry Debongnie ecf12f6eee [FIX] qweb: properly supports svg
Snabbdom supports svg, but it adds the namespace at the creation of the
virtual node.  However, owl works slightly differently: it adds children
after creating the parent virtual node.

So, we need to actually call the addNS method after the children nodes
have been created.

As a bonus, this is slightly faster than snabbdom: we only check at
template compilation time once if a node is a svg.
2019-09-24 21:40:46 +02:00
Géry Debongnie 82a6961b3a [FIX] component: properly handle wrapper component and slots
closes #297
2019-09-23 07:13:51 +02:00
Géry Debongnie 78a4550ebb [IMP] component tags: allow injecting values in xml tag string
With this commit, we can now do this:

      const SUBTEMPLATE = xml`<span><t t-esc="state.n"/></span>`
      class Parent extends Widget {
          static template = xml`<div><t t-call="${SUBTEMPLATE}"/></div>`
          state = {n: 42};
      }
2019-09-21 23:05:44 +02:00
Géry Debongnie cc82b3ffcd [IMP] component: support dynamic t-component 2019-09-21 21:58:19 +02:00
Géry Debongnie bbbaf95c8e Merge pull request #296 from odoo/issue-293-owl-fibers
[MERGE] component: introduce owl fiber
2019-09-20 13:54:59 +02:00
Géry Debongnie caa63628dc [REF] component: refactor fiber creation methods 2019-09-20 11:14:50 +02:00
Géry Debongnie 7a49b9d94e [REF] component: move render props and promise to fiber
part of #293
2019-09-20 10:48:10 +02:00
Géry Debongnie 01eb338e69 [REF] component: move patchqueue management to fiber
part of #293
2019-09-20 10:47:58 +02:00
Géry Debongnie 3048c6f961 [REF] component: introduce fiber
part of #293
2019-09-20 10:47:55 +02:00
Géry Debongnie 8edc637033 [FIX] qweb: remove comments in xml strings before parsing
It was done in loadTemplates, but this does not work if we want to add
templates from another source.
2019-09-19 15:18:59 +02:00
Géry Debongnie c9910077a4 [FIX] qweb: do not capture current qweb instance in closure
it is not needed, and has a bad effect on globally registered templates.
2019-09-12 23:23:55 +02:00
Géry Debongnie 6bf70f016c [DOC] doc: update readme.md 2019-09-12 23:23:39 +02:00
Géry Debongnie 905619f80f [ADD] tools: add benchmark for 0.21.0 2019-09-12 14:50:56 +02:00
Géry Debongnie 14ceb382ef [REL] bump to v0.21.0 2019-09-12 14:21:36 +02:00
Géry Debongnie 9846b2e997 [IMP] tags: introduce xml tag
Big change! This commit introduces an xml function tag to easily define
inline templates.

This is a pretty big change toward single file owl components

Part of #284
2019-09-12 14:17:21 +02:00
Géry Debongnie cfc2fb2ba2 [REF] qweb: rename register method to registerComponent 2019-09-12 14:17:21 +02:00
Géry Debongnie d57017b6ed [IMP] qweb: add registerTemplate method 2019-09-12 14:17:21 +02:00
Géry Debongnie 5bf7a5c671 [IMP] component: make template key static
closes #288
2019-09-12 14:17:21 +02:00
Géry Debongnie 9b589af75a [REF] qweb: improve generated code in some cases 2019-09-12 09:43:09 +02:00
Géry Debongnie 471fd49063 [IMP] router: replace t-routecomponent directive by RouteComponent
closes #287
2019-09-11 14:58:36 +02:00
Géry Debongnie 4fc3423682 [IMP] component: support dynamic t-props
It is useful in some rare situations.

closes #144
2019-09-11 14:12:52 +02:00
Géry Debongnie ffb3263c79 [IMP] component: allow dynamic root nodes
closes #283
2019-09-11 13:12:57 +02:00
Géry Debongnie e1acf66143 [IMP] component: components key is now static
This is a breaking change!

closes #279
2019-09-11 11:18:49 +02:00
Géry Debongnie 2a40907e35 [FIX] qweb: do not crash in some rare t-call situation
Before this commit, QWeb crashed when it had to deal with a t-call with
multiple sub nodes on the same line, and one text node:

<t t-call="SomeTemplate">
  <span>hey</span> <span>hey</span>
</t>

This was because we need to compile the content to be able to extract
all possible t-set t-value statements. But doing so means that we had a
multiple root templates, which caused a crash in this case.

Solving this issue is simple: the sub template is compiled with the flag
allowMultipleRoots set to true.
2019-09-09 11:51:33 +02:00
Géry Debongnie 1c0dd79955 [MISC] update package.json 2019-09-05 21:44:29 +02:00
Géry Debongnie 9fad164c79 [REL] bump to v0.20.0 2019-09-05 14:41:12 +02:00
Géry Debongnie 53a8841914 [TEST] component: snapshots slot functions 2019-09-05 14:33:43 +02:00
Géry Debongnie 19f0863aa3 [IMP] qweb: allow recursive templates t-calls
closes #267
2019-09-05 14:33:43 +02:00
Géry Debongnie 28f7b44f9e [IMP] component: make t-model works with sub state keys
closes #273
2019-09-05 08:47:37 +02:00
Géry Debongnie fe46a6ccee [CLEANUP] run prettier on some code 2019-09-04 22:48:37 +02:00
Géry Debongnie 3c23a7b246 [FIX] component: t-model properly works with select
The initial value was not set on the select tag.

closes #271
2019-09-04 22:45:21 +02:00
Géry Debongnie c52799de2c [FIX] ConnectedComponent: keep props uptodate
This is a tricky bug. The problem is that a ConnectedComponent can
trigger a rendering before it is aware that there is a state change in
the store, and just before the store update event comes in.

What we do in this commit is to update the storeProps whenever a
rendering is scheduled.  However, we need to keep the rendering
information as a promise to give it in some case to the __checkUpdate
method (see the note in the render method)

closes #268
2019-09-04 15:36:10 +02:00
Géry Debongnie 4edb90f44b [FIX] router: properly handle popstate
It was not correct, the url was changed multiple times and back
navigation was broken.

Also, note that there are no tests because the history api is not
available in jsdom.
2019-09-04 13:59:54 +02:00
Géry Debongnie 0c1a7aabae [FIX] component: better templateId for multiple subcomponents
Of course, the templateId computation is kind of tricky.  Here, an issue
occurred because the templateId did not take the componentId into
account when we were in a loop, but with no keyed parent.

This meant that multiple sub components shared the same templateId,
confusing the vdom algorithm.
2019-09-03 16:38:24 +02:00
Géry Debongnie cfdce29ce7 [FIX] component: avoid key collisions in sub components
This is a difficult part of owl: we need to be able to reconcile the
vdom generated (this is done with our virtual dom algorithm), but also
to be able to reconcile the proper components.

The issue here is that when we are in a list, with a t-key attribute on all
list nodes, and those list nodes contains sub component, then the
component system used the index of the list, and did not take into
account the key from the parent.  The fix is to keep track of the
current key in the context, and uses that as a part of the templateId.
2019-09-03 12:13:57 +02:00
Géry Debongnie b344d73e07 [FIX] component: prevent collision between template ids and keys 2019-09-02 15:27:37 +02:00
Géry Debongnie 4cd08d25c8 [FIX] component: solve tricky concurrency issue
In some specific situation, a component could crash, because it was
destroyed before being mounted, but reused anyway for another rendering.
2019-09-01 21:24:54 +02:00
Géry Debongnie f9861040c8 [FIX] router: properly react on hashchange
Before this commit, hashchanges were not taken into account by the
router, if used in history mode.

Also, it's stupid, but i ran prettier on the codebase
2019-09-01 11:45:13 +02:00
Géry Debongnie 40d8090232 [FIX] router: update app if parameterized route changes 2019-08-31 15:03:17 +02:00
Géry Debongnie 55be6437f1 [FIX] router: better support for hash mode 2019-08-31 09:55:45 +02:00
Géry Debongnie 6ff4dd74bf [DOC] readme: improve main example 2019-08-28 12:22:32 +02:00
Géry Debongnie 3628b49c37 [DOC] update readme (swap some sections around) 2019-08-28 12:05:53 +02:00
Géry Debongnie f289cb17ec [REL] bump to v0.19.0 2019-08-28 11:55:36 +02:00
Géry Debongnie e6a3ede4a6 [FIX] component: improve unmount/remount behaviour 2019-08-28 11:41:10 +02:00
Alexandre Kühn 10cfe0b740 [IMP] store: dispatch method returns data from action 2019-08-27 22:26:16 +02:00
Géry Debongnie a3d563ebb4 [FIX] connected_component: some misc issues
- did not properly stop listening to the store after being destroyed
- did not properly synchronize store updates in some async cases
2019-08-27 17:11:54 +02:00
Géry Debongnie 3b1247d476 [REF] vdom: small cleanup 2019-08-27 16:01:01 +02:00
Géry Debongnie beb6c2bc82 [DOC] improve readme and comparison
closes #244
2019-08-27 14:48:02 +02:00
Géry Debongnie f0cd6f61cd [FIX] playground: fix crash in todo app example 2019-08-27 14:09:20 +02:00
Géry Debongnie c950b385a0 [ADD] playground: add window management system example
closes #231
2019-08-27 14:09:20 +02:00
Géry Debongnie c172b31481 [DOC] router: add documentation 2019-08-26 15:45:55 +02:00
Géry Debongnie 9b3a97e732 [DOC] component: improve internal documentation 2019-08-26 12:19:11 +02:00
Géry Debongnie 670c98916c [DOC] store: update documentation and add examples 2019-08-26 10:31:11 +02:00
Géry Debongnie c59abef374 [IMP] connected component: add dispatch method 2019-08-26 10:31:11 +02:00
Géry Debongnie bb4c2506c0 [REF] store: merge actions and mutations
closes #256
2019-08-26 10:31:11 +02:00
Géry Debongnie 9843d16585 [REF] component: improve render method 2019-08-26 10:31:11 +02:00
Géry Debongnie 34e463ad0a [REF] connected component: separate storeprops from props
closes #259
2019-08-26 10:31:11 +02:00
Géry Debongnie 2294c1967f [IMP] qweb: allow xml documents as template definition
Before this commit, the addTemplates method only accepts a string.  But
whenever we perform a $.get call, we get a parsed xml document. So, to
make Owl more convenient to use in that situation, we simply accept xml
documents in addition to strings.
2019-08-23 15:17:28 +02:00
Géry Debongnie 4b53e48e91 [ADD] tools: add benchmarks for 0.18.0 2019-08-22 15:26:17 +02:00
Géry Debongnie 70a70161e7 [REL] bump to v0.18.0 2019-08-22 14:56:39 +02:00
Géry Debongnie e690991a6a [FIX] component: better heuristic to determine if was mounted 2019-08-22 14:55:31 +02:00
Géry Debongnie a621a14028 [MERGE] router: add owl router
First implementation of a declarative router component/directive/plugin
2019-08-22 14:49:11 +02:00
Géry Debongnie 9754cc7521 [REF] small cleanup 2019-08-22 14:26:34 +02:00
Géry Debongnie aa268937a7 [IMP] router: navigate now returns more information 2019-08-22 14:26:34 +02:00
Géry Debongnie 3db6f0a643 [IMP] owl: add commonjs build script 2019-08-22 14:26:34 +02:00
Géry Debongnie 635a7fc72c [FIX] router: do not prevent default click on <a> in some cases 2019-08-22 14:26:34 +02:00
Géry Debongnie 6cd5ec10f0 [FIX] router: properly redirect if necessary when started 2019-08-22 14:26:34 +02:00
Géry Debongnie 0a276fbf1d [IMP] router: basic implementation of navigation guards 2019-08-22 14:26:34 +02:00
Géry Debongnie d593131cc1 [REF] router: remove useless check 2019-08-22 14:26:34 +02:00
Géry Debongnie 3c3dcb44a9 [IMP] router: add test for Link 2019-08-22 14:26:34 +02:00
Géry Debongnie 6ecd1d6ea2 [IMP] router: add validation for destinations 2019-08-22 14:26:34 +02:00
Géry Debongnie 1a931a2a08 [IMP] router: implement redirect feature 2019-08-22 14:26:34 +02:00
Géry Debongnie bf705fcd99 [REF] router: add TestRouter and improve tests 2019-08-22 14:26:34 +02:00
Géry Debongnie bb46346767 [REF] router: change Destination shape 2019-08-22 14:26:34 +02:00
Géry Debongnie cd0762b436 [REF] rework router into a class 2019-08-22 14:26:34 +02:00
Géry Debongnie ca920a0091 [ADD] router: initial implementation 2019-08-22 14:26:34 +02:00
Géry Debongnie e5b1ba24d8 [IMP] component: allow multiple mount/unmount
closes #258
2019-08-22 14:23:08 +02:00
Géry Debongnie eaf912bed7 [FIX] observer: properly handle dates 2019-08-22 14:22:20 +02:00
Géry Debongnie fd0fb5be00 [REF] observer: refactor observer using proxy
closes #253
2019-08-22 14:22:20 +02:00
Géry Debongnie f9f730ab7b [DOC] add some info about return value from actions 2019-08-22 13:05:54 +02:00
Géry Debongnie b30b72fc36 [FIX] update benchmark application 2019-08-22 13:05:37 +02:00
Alexandre Kühn ab08e84bff [IMP] store: return data from dispatching an action 2019-08-22 13:04:32 +02:00
Géry Debongnie cd9cac1246 [REF] qweb: add forceUpdate method
and make sure it only triggers an update once for multiple calls in same
call stack
2019-07-30 15:00:51 +02:00
Géry Debongnie f6369f9750 [REF] qweb: put directives in static QWeb prop
so they can be altered by outside code.  This is mostly useful for tests.
2019-07-30 14:37:39 +02:00
Géry Debongnie f18c73e59f [FIX] component: solve a tricky concurrency rendering issue
When components were initially rendered more than once, in consecutive
microtask ticks, the order of two actions was reversed: the assignation
of the vnode to the __owl__.vnode property, and the assignation of
__owl__.vnode to the final rendered vdom of the component.

As a result, the widget was rendered as null (so, not present).

The reason for this issue was that the renderPromise key was reassigned
at some point.
2019-07-30 08:54:55 +02:00
Géry Debongnie 93d0a7dd46 [FIX] store: properly handle defaultProps in connected components
Thanks to aku for issue + tests + first solution

closes #245
2019-07-16 20:51:57 +02:00
Géry Debongnie b1d022b583 [FIX] qweb: allow t-if with t-call directives
closes #246
2019-07-16 13:19:21 +02:00
Géry Debongnie 5382e824b1 [REF] owl: reorganize src code in sub files 2019-07-16 13:12:08 +02:00
Géry Debongnie 15a3f59744 [REF] owl: move some exported values around
This is a breaking change. Code using Observer, EventBus, Store or
ConnectedComponent need to update the way they import theses classes.

- Observer is now in owl.misc (so you can import it like this:
    const Observer = owl.misc.Observer;)
- EventBus is also now in owl.misc
- Store and ConnectedComponent are now together in store
2019-07-14 09:02:02 +02:00
Géry Debongnie 4a90ec7ff0 [ADD] tools: add v0.17.0 benchmark 2019-07-13 17:13:18 +02:00
Géry Debongnie 9f9b6b174e [REL] bump to v0.17.0 2019-07-13 17:06:43 +02:00
Géry Debongnie 545ceefc3d [REF] store: remove connect function, add ConnectedComponent
closes #238
closes #235
2019-07-13 17:04:36 +02:00
Géry Debongnie 591508e769 [IMP] component: allow top level widgets
closes #166
2019-07-12 14:31:34 +02:00
Géry Debongnie d9cbd23cd9 [IMP] component: add catchError hook 2019-07-12 09:52:09 +02:00
Géry Debongnie f4cd111cc8 [IMP] qweb: more information in an error message 2019-07-11 16:22:30 +02:00
Géry Debongnie ea015af741 [FIX] component: in slots, qweb was looking in wrong component
In slots, the actual parent is where the system should look for existing
widgets, not the rendering context.

closes #239
2019-07-11 15:00:05 +02:00
Géry Debongnie bfc7c81c0d [FIX] component: slots should preserve parented relation
closes #234
2019-07-10 11:01:15 +02:00
Géry Debongnie e24ff8f8aa [IMP] qweb: add renderToString method
closes #230
2019-07-09 10:16:27 +02:00
Géry Debongnie 9f1e64d399 [FIX] component: issue with t-slot,t-set,t-value, but no t-foreach
closes #232
2019-07-08 17:04:06 +02:00
Géry Debongnie 8e1aa71436 [FIX] component: scope issue with slots
Slot templates need to be able to access variables from the parent
scope.

closes #228
2019-07-08 16:24:57 +02:00
Géry Debongnie be2fc965b1 [IMP] playground: reduce duplication in responsive sample 2019-07-08 14:16:12 +02:00
Géry Debongnie 7245ccf8f9 [IMP] component: various prop validation improvements
- add optional form for list props: ['optionalField?']
- accept undefined values for optional props
- allow declaring props with only boolean true
- throw error if extra prop is given to component

closes #223
2019-06-28 16:53:14 +02:00
Géry Debongnie 1c8e1af86d [IMP] tools: improve error message display 2019-06-28 14:54:24 +02:00
Mathieu Duckerts-Antoine 60a6cca960 [IMP] qweb: better error messages for bad xml templates
closes #185
2019-06-28 14:53:19 +02:00
Géry Debongnie ad55b42ccb [IMP] playground: improve first example
Previous example did not illustrate props
2019-06-28 14:31:19 +02:00
Géry Debongnie 50c0a4b126 [DOC] improve component documentation 2019-06-28 13:00:38 +02:00
Géry Debongnie 2ca42e7470 [ADD] tools: add v0.16.0 benchmark 2019-06-28 11:51:37 +02:00
Géry Debongnie d381e85d94 [REL] bump to v0.16.0 2019-06-28 11:20:29 +02:00
Géry Debongnie af7520d869 [REF] *: reformat with prettier and printWidth=100
closes #214
2019-06-28 10:33:13 +02:00
Alexandre Kühn 0095bfa61f [IMP] store: positional arguments with dispatch/commit 2019-06-28 10:12:56 +02:00
Géry Debongnie 1b12cf9b91 [FIX] qweb/component: better handling of class attribute
This changes requires using the class module of vdom.

closes #192
2019-06-28 09:49:41 +02:00
Géry Debongnie dbfc7e4acd [FIX] store/connect: fix bugs with parent/child connected
There were big issues when we use parent/child connected widgets.

- children was rendered twice (and mapStoreToProps was called twice)
- if children was supposed to be destroyed, it was rendered once.

We solve them in this commit by waiting for parent widgets to be ready
before updating children.

closes #216
2019-06-28 09:45:43 +02:00
Pierre Paridans e838e879c0 [FIX] qweb: add missing not equals operators
Implement "!=" and "!==" operator support in QWeb.
2019-06-26 16:14:32 +02:00
Géry Debongnie ee63f6bb0f [IMP] playground: log error in console 2019-06-26 15:50:10 +02:00
Géry Debongnie 16bbb8bc9f [FIX] qweb/component: better handling for t-debug
- fix issue with t-debug on a t-set (defining a slot)
- put t-debug and t-log at a very low (high) priority to make sure they
  are executed before other directives

closes #201
2019-06-25 14:03:05 +02:00
Alexandre Kühn 4a5db0c283 [FIX] qweb: t-component + class with extra whitespaces
Crashed due to `DOMTokenList.add(string)` requiring non-empty string.
2019-06-25 13:08:14 +02:00
Géry Debongnie cc50a2e3bb [FIX] playground: fix some issues with tab handling
closes #200
2019-06-25 09:38:00 +02:00
Géry Debongnie 1e2b204fdd [FIX] component: default slot now works with textnodes
closes #209
2019-06-25 09:37:26 +02:00
Géry Debongnie 4a889b7b6b [IMP] qweb: add option to allow duplicate templates 2019-06-24 22:41:02 +02:00
Géry Debongnie 34695883c2 [REF] component: use __ for private methods
closes #202
2019-06-24 13:42:20 +02:00
Géry Debongnie 3d2e2a1873 [FIX] components: ignore slot if no definition is given
closes #203
2019-06-24 13:38:32 +02:00
Géry Debongnie af6aca83a2 [IMP] components: allow multiple roots in slots
closes #199
2019-06-24 13:36:11 +02:00
Géry Debongnie 8c8ffb6a6b [IMP] qweb,component: make QWeb an event bus
closes #197
2019-06-24 09:47:11 +02:00
Géry Debongnie 63a8fcd7e2 [FIX] component: scoping issue with t-on and t-foreach
closes #193
2019-06-21 16:31:24 +02:00
Géry Debongnie e6a5934162 [REF] component: use 'component' instead of 'widget' 2019-06-20 12:31:00 +02:00
Pierre Paridans 5524c2e323 [IMP] store: connected component reuse base component name
Connected component should have a unique name. To achieve this the
connected component currently have an id based generated name (like
`ConnectedComponent1`).

To make it clearer and ease debugging this commit reuse the extended
component's name to include it in the generated name in the form of
`Connected<ComponentName>`.
2019-06-20 12:26:13 +02:00
Géry Debongnie 35c1de26b8 [IMP] component: allow component name in templates
closes #186
2019-06-18 15:02:35 +02:00
Géry Debongnie d1cf6b1b8d [FIX] playground: sample was using old t-foreach syntax 2019-06-17 16:14:49 +02:00
Géry Debongnie bfa2c681cd [ADD] tools: add v0.15.0 benchmark 2019-06-17 16:07:06 +02:00
Géry Debongnie 609c108607 [REL] bump to v0.15.0 2019-06-17 15:59:15 +02:00
Aaron Bohy a56939f13a [IMP] store: memoize getters
Closes #95
2019-06-17 15:46:48 +02:00
Géry Debongnie 5ff501f8b8 [IMP] component: add support for default slot
closes #180
2019-06-17 09:26:37 +02:00
Géry Debongnie 60917bb102 [DOC] improve main readme.md 2019-06-15 10:38:29 +02:00
Géry Debongnie b201ef8162 [FIX] component: crashes if no template can be found
closes #178
2019-06-14 23:33:45 +02:00
Géry Debongnie 9cacc78ad7 [DOC] component: add section on root widget 2019-06-14 23:11:23 +02:00
Géry Debongnie 0d933b8570 [IMP] tools: improve playground samples
closes #177
2019-06-14 21:44:12 +02:00
Aaron Bohy 72f6daa695 [FIX] playground: t-async leftover in sample 2019-06-14 21:03:21 +02:00
Géry Debongnie 567d78a9ac [DOC] component: put input bindings section higher 2019-06-14 15:46:14 +02:00
Géry Debongnie f013c57050 [REF] component: rename t-async into t-asyncroot 2019-06-14 15:40:32 +02:00
Géry Debongnie b9fae87273 [DOC] doc: miscellaneous formatting updates 2019-06-14 15:33:43 +02:00
Géry Debongnie 1f0457f69b [REF] tools: use t-model in benchmarks 2019-06-14 15:01:29 +02:00
Géry Debongnie c481a73a76 [ADD] component: implement t-model directive
closes #170
2019-06-14 15:01:29 +02:00
Aaron Bohy e64e415b3b [IMP] qweb: add t-async directive on t-widget
Closes #98
2019-06-14 14:58:24 +02:00
Géry Debongnie aa406b53e2 [FIX] tools: react benchmarks did not look like the others 2019-06-14 09:36:29 +02:00
Géry Debongnie 57027bd0fa [FIX] doc: add missing link 2019-06-13 16:02:35 +02:00
Aaron Bohy 671c662fee [FIX] playground: don't remove empty tabs
Fixes #169
2019-06-13 14:04:59 +02:00
Géry Debongnie 0ae70b1d63 [ADD] tools: add v0.14.0 benchmark 2019-06-13 12:22:38 +02:00
Géry Debongnie 2701a7d861 [REL] bump to v0.14.0 2019-06-13 12:10:52 +02:00
Aaron Bohy 3ebe985c3c [FIX] qweb: no more duplicated nodes during transitions
If a node was re-added while being removed (i.e. during the remove
transition), the node was duplicated in the DOM for the delay of
the remove transition. This rev. removes the old occurence directly
in that case.

Fixes #121
2019-06-13 11:55:10 +02:00
Aaron Bohy 1c0d4b5832 [FIX] tests: update snapshots 2019-06-13 11:55:10 +02:00
Géry Debongnie 2840794fa2 [IMP] tools: rework benchmarks application
closes #130
2019-06-13 11:41:49 +02:00
Géry Debongnie 710f42d4e4 [IMP] qweb: add t-slot directive
Closes #67
2019-06-12 14:54:24 +02:00
Géry Debongnie 45a2b0122d [FIX] qweb: add better support for template with only strings 2019-06-12 14:54:24 +02:00
Géry Debongnie 4c41f62364 [FIX] owl: remove inline source maps
They are wrong anyway. Simpler to work with the raw javascript.
2019-06-12 14:54:24 +02:00
Aaron Bohy c2ab9774fb [IMP] utils: whenReady now returns a Promise
Closes #160
2019-06-11 14:45:56 +02:00
Aaron Bohy 22e48e3be0 [REF] store: simplify connect API
Closes #158
2019-06-11 11:41:29 +02:00
Aaron Bohy 1ff3c32fe4 [IMP] store: allow connecting to another store
Closes #58
2019-06-11 11:41:29 +02:00
Géry Debongnie 9a3e1ed99e [FIX] benchmarks: two small fixes 2019-06-11 11:29:31 +02:00
Géry Debongnie 438e2fbc2e [FIX] qweb: add some missing operators
closes #162
2019-06-11 10:45:20 +02:00
Géry Debongnie b3db085745 [REF] vdom: simplify vnode function
This is a snabbdom commit
2019-06-11 10:23:57 +02:00
Géry Debongnie b948c59c6d [DOC] *: improve some parts of the doc 2019-06-11 10:23:46 +02:00
Géry Debongnie 6426fe98f9 [DOC] tooling: improve doc 2019-06-10 09:31:06 +02:00
Géry Debongnie 4dd9de349e [FIX] tests: check links for main README.md as well 2019-06-10 09:31:06 +02:00
Géry Debongnie e1bcea77b5 [REF] tools: rename extras into tools 2019-06-10 09:31:06 +02:00
Géry Debongnie 2a19aeb6a3 [REF] extras: start loading templates earlier 2019-06-08 16:29:01 +02:00
Géry Debongnie b53a34b7d1 [FIX] utils: whenReady should work for all document states
Document readyState can be either 'loading', 'interactive' or
'complete'. We can access the DOM whenever we are no longer in 'loading'
state.
2019-06-08 16:20:44 +02:00
Géry Debongnie f881640d3d [DOC] event_bus: add initial doc
closes #157
2019-06-07 16:07:41 +02:00
Géry Debongnie 54c3dd76e4 [FIX] doc: fix all dead links
closes #149
2019-06-07 15:40:03 +02:00
Géry Debongnie 7b887447da [IMP] qweb: implements an expression evaluator
closes #5
2019-06-07 15:37:45 +02:00
Géry Debongnie 438b21df3f [REF] qweb: improve variable handling 2019-06-07 15:37:45 +02:00
Aaron Bohy d1094f647a [IMP] observer: add set and delete static functions
This rev. add a 'set' and 'delete' static functions to the Observer.
They allow to set or delete (only for objects) properties on
observed objects or arrays.

With this, the 'set' functions in Store and Component are no longer
necessary, so they have been removed.

Closes #138
2019-06-07 14:55:12 +02:00
Aaron Bohy 49baf0de6e [REF] qweb: t-foreach: remove integer support for t-value
Handling it complexifies the compiled code, and it is not really
useful (the same result can be achieved with t-foreach="Array(n)")

Part of #128
2019-06-07 14:52:12 +02:00
Aaron Bohy b14d069ee7 [REF] qweb: drop support of #{.} string interpolation
We only support the {{.}} syntax.

Part of #128
2019-06-07 14:52:12 +02:00
Aaron Bohy e14a4fe338 [REF] qweb: t-foreach: remove x_parity
Part of #128
2019-06-07 14:52:12 +02:00
Aaron Bohy 1f9ec46236 [FIX] qweb: keep ref of unmounted (kept alive) widget
Fixes #120
2019-06-06 09:11:52 +02:00
Géry Debongnie 1464a3631b [ADD] benchmarks: add 0.13.0 to the list 2019-06-05 11:24:27 +02:00
Géry Debongnie 7d3c374b78 [REL] bump to v0.13.0 2019-06-05 10:47:39 +02:00
Géry Debongnie 1dd257f33c [DOC] owl: add comment on updating the doc 2019-06-05 10:44:58 +02:00
Vincent Schippefilt 1206afe6be [FIX] base: compile correctly on windows
Fix package.json and tsconfig.json to build correctly on windows:
the extention scr/* doesn't expand on windows, so I removed it.

Added a precompilation step on npm run extras:watch
2019-06-05 10:31:18 +02:00
Vincent Schippefilt 5842ed51b0 [IMP] extras: update server to python3, disable cache 2019-06-05 10:31:18 +02:00
Géry Debongnie d22219f084 [DOC] reorganize qweb/component doc
Also, document t-foreach

closes #146
2019-06-05 10:28:30 +02:00
Aaron Bohy 0be1a54e03 [IMP] playground: use custom events bubbling 2019-06-04 11:59:21 +02:00
Aaron Bohy 32921ecc20 [IMP] qweb: t-on with t-widget: allow to bind args 2019-06-04 11:59:21 +02:00
Aaron Bohy 1c290c1172 [IMP] qweb: handle t-on modifiers with t-widget 2019-06-04 11:59:21 +02:00
Aaron Bohy 2f9d7ea58f [REF] qweb: revamp event management
Closes #111
2019-06-04 11:59:21 +02:00
Géry Debongnie fe23e76341 [FIX] observer: allow reobserving values twice
closes #139
2019-06-04 11:18:12 +02:00
Géry Debongnie 73023d4869 [IMP] extras: add url in log when starting server 2019-06-04 10:25:50 +02:00
Géry Debongnie ff51443b8e [FIX] playground: keep ace editor alive between mounting/remounting
closes #136
2019-06-04 09:43:58 +02:00
Géry Debongnie f8e07f6d30 [DOC] *: remove all remaining references to t-props
closes #135
2019-06-03 13:34:01 +02:00
Vincent Schippefilt 00da778753 [FIX] extras remove references to t-props 2019-06-03 13:34:01 +02:00
Géry Debongnie 187eb922c0 [IMP] component: define props as attribute (remove t-props) 2019-06-03 13:34:01 +02:00
Géry Debongnie 466c12a0e6 [FIX] component: reuse widget if possible
Previous code always destroy and recreate widgets.
2019-06-03 13:34:01 +02:00
Géry Debongnie 8dc3ec94bf [IMP] qweb: log invalid code generated by template 2019-05-31 13:56:45 +02:00
Géry Debongnie a554436d03 [FIX] playground: properly resize editors when resizing panels 2019-05-31 13:11:08 +02:00
Géry Debongnie 34b5049dee [DOC] doc: small misc fixes 2019-05-31 12:40:02 +02:00
Géry Debongnie 0eccfd08fe [REF] component: add some docstrings 2019-05-31 10:26:37 +02:00
Vincent Schippefilt 98b063fd70 [FIX] owl: ignore idea ide configuration 2019-05-31 09:51:37 +02:00
Géry Debongnie e9ba94ae55 [IMP] playground: add some padding in error window
closes #134
2019-05-29 16:13:29 +02:00
Aaron Bohy 4d72a4f240 [FIX] qweb: enclose interpolated expr in parentheses
Since rev 53e53e9b,
 <div class="o_app" t-attf-class="{{ true ? 'o_extra' : '' }}"/>
produced
 <div class="o_extra"/>
whereas it should have produced
 <div class="o_app o_extra"/>

This is because there were missing parentheses around the string
returned by `interpolate`, which produced instructions like

 var _1 = 'o_app ' + true ? 'o_extra' : '';

Fixes #132
2019-05-29 13:31:48 +02:00
Géry Debongnie a08deb895d [ADD] benchmarks: add 0.12.0 to the list 2019-05-29 13:24:58 +02:00
Géry Debongnie 60cea14b01 [IMP] extras: improve landing page 2019-05-29 13:16:35 +02:00
Géry Debongnie f60904b740 [REL] bump to v0.12.0 2019-05-29 11:26:21 +02:00
Aaron Bohy 376f801541 [IMP] qweb: t-widget: accept dyn values 2019-05-29 11:22:12 +02:00
Aaron Bohy 26f14180e2 [IMP] qweb: t-ref: dyn values with string interpolation
Closes #100
2019-05-29 11:22:12 +02:00
Géry Debongnie bced9f3d04 [IMP] *: use lower level loops in hot code
The goal is to gain a few % of perf improvement.

closes #125
2019-05-29 11:20:30 +02:00
Géry Debongnie 94208d9cbb [IMP] extras: add some css 2019-05-29 10:50:29 +02:00
Géry Debongnie 681983142d [IMP] component: add props validation and default props system
closes #116
2019-05-28 11:56:22 +02:00
Géry Debongnie a525b42537 [IMP] playground: improve code samples
closes #126
2019-05-27 13:33:26 +02:00
Géry Debongnie a4cc085b6d [DOC] qweb: add note to explain t-transition limitation 2019-05-27 12:46:20 +02:00
Aaron Bohy 837dacf1cb [DOC] animations: correct link 2019-05-27 12:10:33 +02:00
Aaron Bohy 7cdd1aa9a1 [IMP] qweb: add global Component registry to qweb
Closes #112
2019-05-27 12:10:33 +02:00
Géry Debongnie 24c569e6d5 [CLEANUP] owl: remove useless dependencies (package.json) 2019-05-27 12:10:30 +02:00
Aaron Bohy 050694414c [REF] move animations tests into their own file 2019-05-27 11:50:21 +02:00
Aaron Bohy 639908366a [IMP] allow to combine t-transition and t-widget
Closes #94
2019-05-27 11:50:21 +02:00
Aaron Bohy 59f401303a [REF] transitions: remove create hook 2019-05-27 11:50:20 +02:00
Aaron Bohy 649e20b956 [IMP] improve tests of transition directive 2019-05-27 11:49:09 +02:00
Géry Debongnie c2280ff1bb [REF] qweb: small cleanup 2019-05-23 23:33:15 +02:00
Aaron Bohy 8a32d823cd [IMP] support modifiers with t-on directive
Supported modifiers are stop, prevent and self.

Closes #115.
2019-05-23 23:33:09 +02:00
Géry Debongnie 13b31458da [DOC] owl: add message when setting mode in 'prod' 2019-05-23 13:44:14 +02:00
Géry Debongnie 92b3ab32e2 [REM] playground: remove benchmarks app
It is kind of redundant with the main benchmarks app, does not bring
much extra value, and is out of date.
2019-05-22 12:29:53 +02:00
Géry Debongnie 4ca0a157e3 [IMP] playground: set owl mode to 'dev'; 2019-05-21 18:08:32 +02:00
Géry Debongnie 1dec8df715 [IMP] owl: introduce dev mode
This commit adds a static key 'dev' on QWeb (which acts as a central
point of access in owl internal code), and a 'mode' key on the value
exported by owl to let external code manipulate it.

closes #117
2019-05-21 14:11:40 +02:00
Géry Debongnie 8f29cfc996 [FIX] playground: add missing t-key in template 2019-05-21 14:11:20 +02:00
Géry Debongnie da275e74fd [REF] owl: move metadata into __info__
This differentiate better metadata and owl exported values.  Also, and
this is the goal, it gives a space to add extra keys in the future.
2019-05-21 13:53:16 +02:00
Géry Debongnie 3d9f4e028c [DOC] utils: remove patch/unpatch references 2019-05-19 08:21:22 +02:00
Géry Debongnie 13577997bc [ADD] extras: add owl 0.11.0 to list of benchmarks 2019-05-17 23:46:42 +02:00
Géry Debongnie 671965026d [REL] bump to v0.11.0 2019-05-17 23:34:14 +02:00
Géry Debongnie bc7fe9023d [REM] utils: remove patch/unpatch
They are out of the scope for Owl.
2019-05-17 23:26:42 +02:00
Géry Debongnie c2c7997df3 [IMP] owl: add extras:watch task
closes #118
2019-05-17 23:22:54 +02:00
Géry Debongnie a1d7e6c987 [FIX] qweb: support #{} syntax in attribute string interpolation
closes #113
2019-05-17 16:20:25 +02:00
Géry Debongnie a1e982aba5 [REF] tests: rename makeTestWEnv to makeTestEnv 2019-05-17 15:52:16 +02:00
Géry Debongnie 2ce027a0a6 [REF] component: remove isStarted key 2019-05-17 15:50:55 +02:00
Géry Debongnie 61f21511a5 [DOC] component: add detailed explanation for t-widget 2019-05-17 10:49:04 +02:00
Géry Debongnie 5682577870 [REF] component: yet another simplification for t-widget 2019-05-17 09:59:02 +02:00
Géry Debongnie 25b633cc63 [REF] component: simplify again t-widget code 2019-05-16 16:25:39 +02:00
Géry Debongnie f16b267931 [REF] component: simplify the t-widget directive
a little bit...
2019-05-16 15:29:40 +02:00
Géry Debongnie 30ec952588 [FIX] playground: keep separate sessions for each tab
also, small refactoring

closes #103
2019-05-16 13:00:24 +02:00
Géry Debongnie 46ba77d0cc [REF] playground: use t-foreach to reduce duplication 2019-05-16 12:04:50 +02:00
Géry Debongnie 042e376c2b [IMP] playground: debounce some handlers 2019-05-16 11:58:04 +02:00
Géry Debongnie b9f1af2ad5 [REF] playground: small refactoring 2019-05-16 11:57:52 +02:00
Géry Debongnie 7df0fdcc0a [DOC] qweb: add some documentation on owl qweb extensions 2019-05-16 10:23:18 +02:00
Géry Debongnie 73d743a1c3 [FIX] observer: newly observed object/arrays have higher rev
Some people apparently believe that the framework should magically
solves all problems from the programmers, shielding him from thinking.

It is not possible, and maybe a bad idea, because it will only delay the
inevitable...  If one does weird stuff without knowing what is going on,
someone will get hurt.

However, in this specific case, something can be done.

closes #104
2019-05-15 17:30:01 +02:00
Géry Debongnie 8758dfcedf [IMP] component: better error if cannot find widget
closes #54
2019-05-15 17:17:39 +02:00
Géry Debongnie 0a10bbc023 [IMP] component: remove support for inlineTemplate
closes #93
2019-05-15 15:54:18 +02:00
Géry Debongnie 9c1d369e94 [FIX] qweb/component: fix scoping issue with list of widgets
In a t-foreach loop, there was a bad interaction between variables
defined with the `var` keyword and asynchronous code.

closes #108
2019-05-15 15:42:45 +02:00
Géry Debongnie 9556696fa8 [REF] qweb: rename loadTemplates into addTemplates 2019-05-15 11:04:22 +02:00
Géry Debongnie 04eb720619 [IMP] qweb: add default template in QWeb 2019-05-15 10:55:17 +02:00
Géry Debongnie 8e098e8ed6 [REF] benchmarks: use new system for finding templates 2019-05-15 10:40:23 +02:00
Géry Debongnie c836cead58 [IMP] playground: remove explicit template keys 2019-05-15 10:40:23 +02:00
Géry Debongnie 361ecbe90b [IMP] component: deduce template name from component name
closes #102
2019-05-15 10:40:23 +02:00
Géry Debongnie ae8d7d3be2 [REF] qweb_core: move context after QWeb 2019-05-15 10:40:23 +02:00
Géry Debongnie ed4f92211c [DOC] component: add section on async rendering 2019-05-11 12:11:00 +02:00
Géry Debongnie f8804d6501 [REF] playground: use t-mounted directive in todo example 2019-05-11 00:03:26 +02:00
Géry Debongnie de7c680387 [ADD] extras: add owl 0.10.0 to list of benchmarks 2019-05-11 00:03:26 +02:00
Géry Debongnie 6dd7391cdc [DOC] utils: add some basic information 2019-05-10 21:04:58 +02:00
Géry Debongnie dfa7d5932d [REM] utils: remove memoize, parseXML function 2019-05-10 20:51:34 +02:00
Géry Debongnie 53911de00a [FIX] component: make t-widget work with t-elif
closes #97
2019-05-10 19:36:44 +02:00
Aaron Bohy 1760d0d336 [FIX] allow to combine directives using node hooks
e.g. t-ref and t-transition, or t-mounted and t-transition.
2019-05-10 19:31:09 +02:00
Aaron Bohy 0aba9748c9 [IMP] add t-mounted directive
closes #45
2019-05-10 19:31:09 +02:00
Aaron Bohy 8ee0973dab [REF] autoformat some files 2019-05-10 19:31:09 +02:00
Géry Debongnie e04c5b1c6b [REL] bump to v0.10.0 2019-05-10 12:19:25 +02:00
Géry Debongnie f52a15d7f6 [REF] store: make getters functions instead of properties 2019-05-10 12:10:52 +02:00
Alexandre Kühn 147f6fced7 [IMP] store: getters 2019-05-10 12:10:52 +02:00
Géry Debongnie d928927da8 [DOC] store: add some basic documentation 2019-05-10 12:10:52 +02:00
Géry Debongnie 29cc94d567 [REF] qweb: use nodeId instead of ctx.parentNode 2019-05-10 11:53:24 +02:00
Géry Debongnie 7f33f9b68e [FIX] component: call patch between willpatch and patched
closes #91
2019-05-09 15:22:59 +02:00
Géry Debongnie 80ffa37773 [TODO] fix separate issue. need a test 2019-05-09 13:12:26 +02:00
Géry Debongnie 2f70a7a352 [DOC] component: add a section on semantics
closes #89
2019-05-08 15:25:54 +02:00
Géry Debongnie f7f8c34e1c [DOC] owl: add generic file level documentation 2019-05-08 11:23:48 +02:00
Géry Debongnie edc7d2b635 [IMP] playground: improve responsive example
close #83
2019-05-07 16:26:20 +02:00
Géry Debongnie 7f0b236747 [FIX] store: properly call patch on connected components
A previous refactoring broke it by adding a [] arguments to updateprops.
2019-05-07 14:43:23 +02:00
Géry Debongnie b7860a95b0 [REF] store: typecheck code
closes #87
closes #39
2019-05-07 11:47:09 +02:00
Géry Debongnie f7495dc897 [FIX] store: correct update order for child/parents
Not happy about the test, there was a bug in Discuss that is solved with this
commit, but I could not reproduce it in a test.

closes #85
2019-05-07 11:22:00 +02:00
Géry Debongnie ba506be58d [FIX] component: fix issue with crash caused by async rendering
This may (or may not?) closes #85
2019-05-06 14:23:29 +02:00
Géry Debongnie 91896942dd [FIX] component: prevent rendering if not mounted 2019-05-06 13:45:50 +02:00
Géry Debongnie dfab8c7333 [DOC] component: fix invalid xml in examples 2019-05-06 13:42:53 +02:00
Géry Debongnie bd29e4f761 [REF] qweb: split code into 3 files
closes #84
2019-05-06 13:00:46 +02:00
Géry Debongnie b9591cfecd [IMP] component: add support for dynamic css on t-widget
closes #80
2019-05-06 11:19:18 +02:00
Géry Debongnie 51320204f9 [IMP] component: add static css support for sub components
part of issue #80
2019-05-06 10:22:53 +02:00
Alexandre Kühn ec0bafaa8e [DOC] component: remove misleading order on willUnmount
Some hooks call order are clearly defined: `[willX]` hooks are
called first on parent, then on children, and `[Xed]` are called in
the reverse order: first children, then parent.

This is also true for `willUnmount`: first on parent, then on
children.
2019-05-04 22:54:20 +02:00
Géry Debongnie eb508b7660 [FIX] component: capture ref key in closure
This is what commit d3197e9865 should have
done. Many changes should be done on normal nodes and on components!

closes #77
2019-05-04 22:48:50 +02:00
Géry Debongnie 7c8fc323e1 [DOC] extras: update readme and server.py doc 2019-05-03 16:38:24 +02:00
Géry Debongnie ff2393f5df [DOC] doc: update qweb.md 2019-05-03 16:19:33 +02:00
Géry Debongnie ab2a98426e [IMP] playground: slightly decrease font size 2019-05-03 14:33:34 +02:00
Géry Debongnie 84b3cc42cf [FIX] qweb: make transition code much more robust
part of #66
2019-05-03 14:15:25 +02:00
Géry Debongnie d28b854e8d [IMP] playground: display promise errors in right pane 2019-05-03 13:26:25 +02:00
Géry Debongnie 6c8c69affa [ADD] extras: add benchmarks for 0.9.0 2019-05-03 12:40:12 +02:00
Géry Debongnie faec7d4ad9 [FIX] readme: fix broken links 2019-05-03 12:34:00 +02:00
Géry Debongnie 5b9abb6785 [REL] bump to v0.9.0 2019-05-03 12:05:46 +02:00
Géry Debongnie eb4ca0a8d5 [ADD] extras: add animation example to playground 2019-05-03 12:04:15 +02:00
Géry Debongnie 641adc6e5c [IMP] extras: properly indent js playground samples
closes #75
2019-05-03 11:59:51 +02:00
Géry Debongnie 10ab97e3c6 [REF] extras: improve code 2019-05-03 11:39:01 +02:00
Géry Debongnie e060130655 [REF] extras: move benchmarks and playground into extras
closes #76
closes #73
2019-05-03 10:56:43 +02:00
Géry Debongnie 4e982f5460 [IMP] qweb: add warning if t-key is missing in some cases
closes #71
2019-05-03 10:22:57 +02:00
Géry Debongnie d3197e9865 [FIX] qweb: capture ref key in closure, to avoid scoping issue
closes #77
2019-05-03 09:43:27 +02:00
Géry Debongnie 0da44033ac [IMP] qweb: add preliminary support for transitions
Still very naive...

Part of #66
2019-05-03 09:35:35 +02:00
Géry Debongnie 6350d9598d [REF] qweb, component: small code refactoring 2019-05-02 10:58:47 +02:00
Géry Debongnie 9df6c0aede [DOC] readme: add a tag line, improve readme 2019-05-01 11:02:32 +02:00
Géry Debongnie 896efca43f [DOC] qweb: add info on root nodes 2019-05-01 10:50:04 +02:00
Géry Debongnie efe82b6cd0 [DOC] doc: add some info on t-key directive 2019-04-30 10:41:21 +02:00
Géry Debongnie eb910193d7 [ADD] benchmarks: add benchmarks in main branch
this will make it easier to compare various situations.
2019-04-29 23:09:13 +02:00
Géry Debongnie 40e486a9eb [REF] component: remove updateProps
it is actually now a private method
2019-04-29 16:50:49 +02:00
Géry Debongnie e56580efb2 [FIX] component: call willPatch/patched hooks properly
Each component called its hooks properly individually, however the issue
was that it was done component by component.  However, in practice, we
want the willPatch hooks to be done before ANY patch is actually
performed, and the patched should be called AFTER every patch is
applied.

The trick is to propagate a list of patched components across various
function calls.

closes #64
2019-04-29 15:45:15 +02:00
Géry Debongnie 46e05f1c96 [DOC] qweb: add some documentation 2019-04-29 14:15:19 +02:00
Géry Debongnie 4a748d2ea4 [IMP] qweb: add t-debug and t-log directives 2019-04-29 14:07:08 +02:00
Géry Debongnie 8f388e712e [DOC] doc: add info on hook call order in documentation 2019-04-29 12:07:20 +02:00
Géry Debongnie 0a5b6aa0ec [DOC] doc: use loadJS in code example 2019-04-29 11:21:02 +02:00
Géry Debongnie fc1ea10243 [DOC] readme: add explanation on why OWL is different 2019-04-29 09:28:35 +02:00
Géry Debongnie d52177560b [DOC] doc: add some qweb documentation 2019-04-27 19:14:40 +02:00
Géry Debongnie 1701d5aa86 [REM] utils: remove findInTree and htmlTrim
They were not used and are not in the scope of this project.
2019-04-27 11:44:37 +02:00
Géry Debongnie b08e876136 [FIX] component: call mounted hooks in subcomponent properly
order was not correct in some cases.  Also, this commit is a pretty
significant optimization.
2019-04-27 11:35:02 +02:00
Géry Debongnie 005b727328 [FIX] component: hooks mounted/willUnmount called in correct order
The issue was with parent/child relationship.  It is not intuitive to
me, but the mounted hook should be called first on the children, and
then on the parent.  willUnmount hooks is the opposite.

closes #63
2019-04-26 17:23:50 +02:00
Géry Debongnie b44f274e37 [FIX] component: do not call willPatch/patched if not in DOM
closes #62
2019-04-26 15:30:59 +02:00
Géry Debongnie b6bd0f92a7 [ADD] utils: add whenReady function 2019-04-26 14:22:43 +02:00
Géry Debongnie 78108e8d2c [IMP] utils: add loadJS function
Very useful to lazy load libraries in owl applications
2019-04-26 13:28:30 +02:00
Géry Debongnie c405dadc1b [DOC] doc: improve qweb documentation 2019-04-26 09:55:17 +02:00
Géry Debongnie 2bd0719b9a [REF] component, vdom: small cleanup 2019-04-25 17:10:36 +02:00
Géry Debongnie 9544034e6f [DOC] doc: update component.md to add info on t-widget 2019-04-25 17:10:07 +02:00
Géry Debongnie cf47f8459a [REF] utils: remove id generator 2019-04-25 16:45:09 +02:00
Géry Debongnie 8f7d06a5bd [DOC] readme: add link to project page 2019-04-25 16:00:02 +02:00
Géry Debongnie d1708fc252 [IMP] doc: change main doc page title 2019-04-25 15:57:13 +02:00
Géry Debongnie f23a26426d [DOC] doc: add observer doc 2019-04-25 15:47:02 +02:00
Géry Debongnie 40613e0a76 [IMP] observer: add observer to exported objects 2019-04-25 15:47:01 +02:00
Géry Debongnie aa11229641 [DOC] doc: slightly improve readme.md 2019-04-25 14:55:08 +02:00
Géry Debongnie 754272b436 [IMP] component: give snapshot from 'willPatch' to 'patched' 2019-04-25 14:46:04 +02:00
Géry Debongnie d509373228 [DOC] doc: rewrite component/quick start documentation 2019-04-25 13:55:40 +02:00
Alexandre Kühn 379cd2a90f [FIX] component: t-refs are bound/unbound at proper timing
With this commit, we make sure that bound references are removed when a
widget is removed from the DOM.

closes #59
2019-04-25 10:40:45 +02:00
Géry Debongnie 4c2115d365 [DOC] readme: improve example 2019-04-24 10:32:17 +02:00
Géry Debongnie 94b48cb389 [DOC] readme: udpate links to playground 2019-04-24 10:29:10 +02:00
Géry Debongnie 3ecb772a56 [DOC] fix download link 2019-04-24 10:20:21 +02:00
Géry Debongnie b14d264718 [REL] bump to v0.8.0 2019-04-24 10:11:32 +02:00
Géry Debongnie 1a778922af [DOC] doc: update a lot of the documentation 2019-04-24 10:10:04 +02:00
Géry Debongnie 79b97c6d24 [FIX] owl: correct path for build script
This is a critical error, the build script was not updated to the
correct path...
2019-04-23 14:37:59 +02:00
Géry Debongnie a8e919f382 [DOC] update main readme.md 2019-04-23 11:47:19 +02:00
Géry Debongnie 20b33f50fa [FIX] component: bind t-ref widgets at correct moment
closes #51
2019-04-23 11:28:30 +02:00
Géry Debongnie 9170882010 [MERGE] fork snabbdom
With a custom version of snabbdom, we are now free to optimize owl a
little bit more.  We can for example remove unused hooks.

closes #8
2019-04-23 11:02:46 +02:00
Géry Debongnie ae36cca2ef [ADD] vdom: readd original snabbdom tests 2019-04-23 10:58:37 +02:00
Géry Debongnie f5ce05c81e [FIX] vdom: fix typing issues, small cleanup 2019-04-22 21:22:21 +02:00
Géry Debongnie 2fbf4f2c22 [REM] snabbdom: remove library 2019-04-20 09:35:18 +02:00
Géry Debongnie 8a4fd5015a [REF] vdom: fork snabbdom and use custom version 2019-04-20 09:34:51 +02:00
Géry Debongnie de04ed2339 [MISC] update a few dependencies in package.json 2019-04-18 22:44:00 +02:00
Géry Debongnie ae263730d9 [ADD] utils: add loadTemplates function 2019-04-18 22:42:37 +02:00
Géry Debongnie 85418043f4 [MISC] update .gitignore and package.json 2019-04-18 18:15:25 +02:00
Géry Debongnie 4fb2733321 [FIX] observer: better handling of reassigning state
closes #50
2019-04-18 13:14:10 +02:00
Géry Debongnie d9d109c9a2 [REF] owl: rename Lab into Library
closes #25
2019-04-18 10:18:53 +02:00
Géry Debongnie 4ee39282ca [IMP] component: add 'set' method to allow extending state
closes #49
2019-04-18 10:15:50 +02:00
Géry Debongnie 3b3fd8a6c9 [REF] component: make observer and state optional 2019-04-18 10:11:16 +02:00
Géry Debongnie 29111a5c10 [IMP] component: disable mutations in render phase
closes #48
2019-04-18 10:11:04 +02:00
Géry Debongnie 4b30d0b412 [FIX] observer: protect observed state against changes 2019-04-18 07:59:30 +02:00
Géry Debongnie d07f396578 [REF] move jest.config.js into package.json 2019-04-18 07:40:56 +02:00
Géry Debongnie 2c218c4463 [REM] examples: remove benchmarks app
This will be moved in a different branch

closes #44
2019-04-17 16:22:33 +02:00
Géry Debongnie af83a8249e [REM] examples: remove todoapp
It now is available on the playground
2019-04-17 15:37:04 +02:00
Géry Debongnie 4807389012 [REL] bump to v0.7.0 2019-04-17 11:00:29 +02:00
Géry Debongnie 7a479baf63 [DOC] doc: remove references to updateState 2019-04-17 10:59:03 +02:00
Géry Debongnie ce87dd705e [FIX] examples: update benchmarks/todoapp to new code 2019-04-17 10:59:03 +02:00
Géry Debongnie 94ed6ebe60 [IMP] component: remove updateState method 2019-04-17 10:59:03 +02:00
Géry Debongnie 619e455dd5 [IMP] component: observe the state and rerender if it changes
closes #35
2019-04-17 10:58:54 +02:00
Géry Debongnie 94e7d9aa39 [REF] observer: move batch code out of store, add notifycb 2019-04-17 09:16:48 +02:00
Géry Debongnie c47c4ccc60 [REF] observer: turn the observer into a class 2019-04-16 22:34:26 +02:00
Géry Debongnie b89327c831 [IMP] qweb: log a warning if a t-foreach is used without t-key
closes #40
2019-04-16 17:49:33 +02:00
Géry Debongnie e19540fb04 [FIX] examples: update benchmarks code to new structure 2019-04-16 17:25:43 +02:00
Géry Debongnie c67ab3d712 [IMP] owl: add github project url to exported object 2019-04-16 17:23:31 +02:00
Géry Debongnie 8163e2b0e4 [REM] component: remove PureComponent 2019-04-16 17:20:32 +02:00
Géry Debongnie e5e6c50fff [FIX] examples: adapt todoapp to new owl structure 2019-04-16 17:20:32 +02:00
Géry Debongnie a22dcdaddf [REF] owl: reorganize exports, remove registry, remove web example
closes #38
2019-04-16 17:20:23 +02:00
Géry Debongnie eac49562fa [REF] owl: export owl elements in one object 2019-04-16 16:26:06 +02:00
Géry Debongnie 460ae4bb34 [REF] qweb: add missing semicolon to compiled template 2019-04-16 16:16:08 +02:00
Géry Debongnie c52e86feaf [FIX] qweb: t-set should reuse variable if possible
closes #41
2019-04-16 16:04:44 +02:00
Géry Debongnie cef12acfe0 [REF] observer: create sub array prototype only once
and reuse it whenever necessary.  This should speed up the observer.
2019-04-16 15:17:36 +02:00
Géry Debongnie 515b91fe8a [FIX] examples: add missing t-key attribute in todoapp 2019-04-16 14:59:55 +02:00
Géry Debongnie 0ca4cc1596 [IMP] qweb: make t-key directive dynamic
instead of having t-key and t-att-key.

closes #36
2019-04-16 14:38:55 +02:00
Géry Debongnie 7092f5e142 [REF] observer: move observer out of store 2019-04-16 14:24:19 +02:00
Géry Debongnie 6640644d34 [FIX] qweb/component: make widgets work with t-else=""
closes #37
2019-04-16 14:17:02 +02:00
Géry Debongnie 7974ce4963 [IMP] qweb: crash if t-on directive is used with no event
closes #33
2019-04-16 14:07:51 +02:00
Géry Debongnie 9dd8a36b28 [REF] examples: improve todoapp 2019-04-16 10:09:24 +02:00
Géry Debongnie ed326d34fd [FIX] qweb: add t-debug to list of valid directives
With a previous commit, qweb crashes when an unknown directive is
encountered.  However, t-debug was not on the list of valid directives.
2019-04-16 09:57:58 +02:00
Géry Debongnie 480de10ff3 [FIX] store: properly compare values on store updates
Before this commit, we tried to use a hash function for non observable
values, but this was not correct, since some changes could be done that
would compensate each other.

With this commit, we properly compare each non observable value.
2019-04-16 09:47:03 +02:00
Alexandre Kühn 73fb8f8998 [FIX] store: connected component deeply reactive with undefined, null and string props
Revision on https://github.com/odoo/owl/commit/9f77344c3a19592d4a37df43b65f9e647fe41f24

Deeply reactive version of fix above.
2019-04-15 16:54:02 +02:00
Géry Debongnie 559c51a717 [FIX] store: change default hash function to better see changes 2019-04-15 16:50:07 +02:00
Alexandre Kühn 9f77344c3a [FIX] store: connected component with undefined, null and string props 2019-04-15 15:36:18 +02:00
Géry Debongnie 85eb30626d [FIX] qweb: t-set expressions are evaluated only once
closes #23
2019-04-15 14:38:08 +02:00
Géry Debongnie 3d18359dd8 [IMP] store: add 'deep' param to connect options 2019-04-15 11:51:18 +02:00
Alexandre Kühn e005090296 [IMP] store: return data from committing a mutation
closes #29
2019-04-15 10:53:59 +02:00
Alexandre Kühn 7e7226213a [IMP] store: commit a mutation in a mutation 2019-04-15 10:51:54 +02:00
Géry Debongnie 9ee85e220b [FIX] store: unobserve detached objects
closes #27
2019-04-15 10:43:50 +02:00
Géry Debongnie 7b87470760 [IMP] store: connect function takes hash function in param
With this commit, we can now decides precisely if a component should be
rerendered, by using a hash function.

By default, the hash function will deep observe each store element
coming from the result of the mapStateToProps.

closes #24
2019-04-15 10:43:35 +02:00
Géry Debongnie f5bbf25d4f [IMP] store: add deep tracking for changes
This is only at the level of the store currently. To be useful, we need
to work on the 'connect' function.
2019-04-14 21:24:54 +02:00
Géry Debongnie 4ea0875fd9 [REF] store: namespace rev under __owl__ name 2019-04-14 11:27:02 +02:00
Géry Debongnie 3733734ae5 [REF] component: rename t-keep-alive to t-keepalive
This is useful to preserve the following nice property: when we have an
attribute t-something-someotherthing, we can get the directive name by
removing 't-' at the front, and splitting on '-'.
2019-04-14 10:44:29 +02:00
Géry Debongnie d7bed96667 [IMP] qweb: crashes if unknown directive
closes #22
2019-04-14 10:43:27 +02:00
Géry Debongnie a0f0a24d1d [REF] component: use __owl__ as metadata key 2019-04-13 14:14:34 +02:00
Géry Debongnie caed076f2a [FIX] store: properly handle null values 2019-04-12 21:07:12 +02:00
Géry Debongnie 2ea01455cb [FIX] qweb: fix issue with expression formatting
closes #21
2019-04-12 15:27:44 +02:00
Géry Debongnie f300e921d6 [REF] qweb: small cleanup 2019-04-12 14:22:42 +02:00
Géry Debongnie bba9e5fb20 [FIX] examples: update store example 2019-04-12 13:10:23 +02:00
Géry Debongnie 4f1d976206 [FIX] store: properly observe all array methods 2019-04-12 13:03:25 +02:00
Géry Debongnie 8ca806eb28 [IMP] store: make sure set function works with arrays 2019-04-12 12:45:44 +02:00
Géry Debongnie e0608aa7fd [IMP] store: propagate 'set' function to commit parameters 2019-04-12 12:42:14 +02:00
Géry Debongnie 111080fdbf [FIX] store: observer array values recursively 2019-04-12 12:25:22 +02:00
Géry Debongnie ab12ac8a9f [IMP] store: properly handle already observed state 2019-04-12 12:17:16 +02:00
Géry Debongnie 63069d96a5 fix: properly observe recursively new values 2019-04-12 12:08:31 +02:00
Géry Debongnie f1cc32de8f imp: prevent store state change outside a mutation 2019-04-12 12:05:06 +02:00
Géry Debongnie 03511ce9ea ref: reorganize store (based on different principles) 2019-04-12 11:57:29 +02:00
Géry Debongnie d49f5670fe ref: better store internal organization 2019-04-11 13:02:32 +02:00
Géry Debongnie afc94c51a8 bump to v0.6.0 2019-04-11 10:24:37 +02:00
Géry Debongnie 90f6808f57 ref: rename _start to _prepare 2019-04-10 10:45:27 +02:00
Géry Debongnie f960149ba2 rem: remove destroyed hook 2019-04-10 09:35:20 +02:00
Géry Debongnie 74ce6a671e fix: properly destroy widget in some cases
when widget was (props)updated, then removed from DOM, it was not
destroyed.

closes #19
2019-04-09 15:31:03 +02:00
Géry Debongnie bc07c49a5f imp: add willUpdateProps hook to components 2019-04-09 13:55:13 +02:00
Géry Debongnie 816ffe1b44 imp: store dispatch functions can be synchronized 2019-04-09 13:16:22 +02:00
Géry Debongnie 94c33af8e9 ref: rename 'detach' method to 'unmount' 2019-04-09 12:57:34 +02:00
Géry Debongnie 6e0ef0fd5c ref: rename updated hook to 'patched' 2019-04-09 10:37:53 +02:00
Géry Debongnie 370a92b67e imp: t-ref directive is now dynamic
closes #11
2019-04-09 10:33:08 +02:00
Géry Debongnie c10b84cd99 ref: move magify function from utils to store 2019-04-09 10:09:29 +02:00
Géry Debongnie 7ea782bd60 fix: prevent issue in store with existing values in array 2019-04-09 10:08:37 +02:00
Géry Debongnie bf4cbaea33 imp: unskip test, add new test 2019-04-09 09:14:22 +02:00
Alexandre Kühn cde85269fd imp: make store reactive (observe state and react to changes)
This is a pretty big change, yet still not complete.
2019-04-08 23:11:38 +02:00
Alexandre Kühn 3340401f54 imp: give reference to dispatch function in actions 2019-04-08 23:11:32 +02:00
Alexandre Kühn 7027ff1eb6 imp: add env to store dispatch
This is useful to allow actions to use specific environment methods.
For example, one might want to add a rpc method to the environment.
2019-04-08 23:04:27 +02:00
Géry Debongnie d10426c720 update component doc 2019-04-05 23:44:07 +02:00
Géry Debongnie a951c484be ref: rename componentDidUpdate hook into 'updated'
closes #16
2019-04-05 23:29:16 +02:00
Géry Debongnie 14d3eb83eb imp: add willPatch hook 2019-04-05 23:23:00 +02:00
Géry Debongnie ca73ed07a6 doc: add link to github.io page 2019-04-05 15:13:18 +02:00
Géry Debongnie f2fc20f8e3 fix: connected components should recompute store props properly 2019-04-04 16:01:09 +02:00
Géry Debongnie 8badcbd21e doc: update readme 2019-04-04 16:01:00 +02:00
Géry Debongnie 5a75e5ec19 bump to v0.5.0 2019-04-04 14:19:40 +02:00
Géry Debongnie 3e8682b741 ref: adapt qweb to output code closer to es5 2019-04-04 14:14:02 +02:00
Géry Debongnie fd26775a0f imp: adapt build scripts to allow ES5 output 2019-04-04 13:55:46 +02:00
Géry Debongnie a86d0b5b02 imp: store connect: mapStateToProps receive ownProps 2019-04-02 14:23:40 +02:00
Géry Debongnie 7ebea5a486 imp: better error message when evaluating/compiling templates
fixes #3
2019-04-02 11:03:04 +02:00
Géry Debongnie 56be87f26e fix: allow t-attf- attributes to combine with regular attrs
fixes #10
2019-04-02 09:22:37 +02:00
Géry Debongnie 990a08dc04 imp: add componentDidUpdate hook 2019-04-01 16:00:57 +02:00
Alexandre Kühn e7a4ad99de [FIX] connected child components with custom hooks 2019-04-01 14:44:53 +02:00
Géry Debongnie d6e61c2203 imp: qweb engine can be initialized with templates 2019-03-29 16:40:59 +01:00
Géry Debongnie e6b0d06e3e fix: make sure qweb throw error if invalid templates 2019-03-29 15:37:42 +01:00
Géry Debongnie 5cd45b59af fix: properly destroy/detach widgets in some cases
Sometimes, widgets were not properly destroyed/detached. This was caused
by the fact that we used the hook remove, when we sometimes need to use
the hook destroy as well.
2019-03-29 12:50:45 +01:00
Géry Debongnie 1e58c7b12b fix: update component snapshots 2019-03-29 12:39:00 +01:00
2103 changed files with 138588 additions and 139921 deletions
+47
View File
@@ -0,0 +1,47 @@
{
"env": {
"browser": true,
"node": true,
"es2022": true
},
"parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint"],
"parserOptions": {
"sourceType": "module"
},
"root": true,
"rules": {
"no-restricted-globals": ["error", "event", "self"],
"no-const-assign": ["error"],
"no-debugger": ["error"],
"no-dupe-class-members": ["error"],
"no-dupe-keys": ["error"],
"no-dupe-args": ["error"],
"no-dupe-else-if": ["error"],
"no-unsafe-negation": ["error"],
"no-duplicate-imports": ["error"],
"valid-typeof": ["error"],
"@typescript-eslint/no-unused-vars": ["error", { "vars": "all", "args": "none", "ignoreRestSiblings": false, "caughtErrors": "all" }],
"no-restricted-syntax": [
"error",
{
"selector": "MemberExpression[object.name='test'][property.name='only']",
"message": "test.only(...) is forbidden",
},
{
"selector": "MemberExpression[object.name='describe'][property.name='only']",
"message": "describe.only(...) is forbidden",
}
],
},
"globals": {
"describe": true,
"expect": true,
"test": true,
"beforeEach": true,
"beforeAll": true,
"afterEach": true,
"afterAll": true,
"jest": true,
},
}
+29
View File
@@ -0,0 +1,29 @@
# This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions
name: Node.js CI
on:
pull_request:
branches: [ master ]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [12.x, 14.x, 16.x]
steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- run: npm ci
- run: npm run test
- run: npm run check-formatting
- run: npm run lint
- run: npm run build
+20 -2
View File
@@ -1,5 +1,6 @@
/node_modules
/dist
npm-debug.log
# misc
@@ -13,5 +14,22 @@ npm-debug.log*
yarn-debug.log*
yarn-error.log*
package-lock.json
.vscode
#ide's
**/.vscode/*
.idea
node_modules
release-notes.md
.rpt2_cache
# useful in some cases
/temp
# owl-vision
*/owl-vision/out/
*/owl-vision/.vs/
**/*.vsix
!*/owl-vision/.vscode/launch.json
!*/owl-vision/.vscode/tasks.json
+766
View File
@@ -0,0 +1,766 @@
# Changelog
This document contains an overview of all changes between Owl 1.x and
Owl 2.x, with some pointers on how to update the code.
Note that some of these changes can be magically implemented (for example, by
patching the `setup` method of `Component` to auto register all the lifecycle
methods as hooks). This will be done for the transition period, but will be
removed after.
## From Owl 1.x to Owl 2.0
All changes are documented here in no particular order.
**Components**
- components can now have empty content or multiple root nodes (htmlelement or text) ([details](#31-components-can-now-have-arbitrary-content))
- breaking: component.el is removed ([details](#9-componentel-is-removed))
- new `useEffect` hook ([doc](doc/reference/hooks.md#useeffect))
- new `onWillDestroy`, `onWillRender` and `onRendered` hooks ([doc](doc/reference/component.md#lifecycle))
- breaking: lifecycle methods are removed ([details](#1-component-lifecycle-methods-are-removed))
- breaking: can no longer be mounted on detached DOM ([details](#2-components-can-no-longer-be-mounted-in-a-detached-dom-element))
- breaking: standalone `mount` method API is simpler ([details](#4-mount-method-api-is-simpler))
- breaking: components can no longer be instantiated and mounted by hand ([details](#5-components-can-no-longer-be-instantiated-and-mounted-by-hand))
- breaking: components can no longer be unmounted/remounted ([details](#6-components-can-no-longer-be-unmountedremounted))
- breaking: template name is no longer inferred from the class name ([details](#7-template-name-is-no-longer-inferred-from-the-class-name))
- breaking: components no longer have a `shouldUpdate` method ([details](#8-components-no-longer-have-a-shouldupdate-method))
- breaking: components can no longer be mounted with position=self ([details](#11-components-can-no-longer-be-mounted-with-positionself))
- breaking: `render` method does not return a promise anymore ([details](#35-render-method-does-not-return-a-promise-anymore))
- breaking: `catchError` method is replaced by `onError` hook ([details](#36-catcherror-method-is-replaced-by-onerror-hook))
- breaking: Support for inline css (`css` tag and static `style`) has been removed ([details](#37-support-for-inline-css-css-tag-and-static-style-has-been-removed))
- new: prop validation system can now describe that additional props are allowed (with `*`) ([doc](doc/reference/props.md#props-validation))
- breaking: prop validation system does not allow default prop on a mandatory (not optional) prop ([doc](doc/reference/props.md#props-validation))
- breaking: rendering a component does not necessarily render child components ([details](#40-rendering-a-component-does-not-necessarily-render-child-components))
**Templates**
- breaking: `t-foreach` should always have a corresponding `t-key` ([details](#20-t-foreach-should-always-have-a-corresponding-t-key))
- breaking: `t-ref` does not work on components ([details](#29-t-ref-does-not-work-on-component))
- breaking: `t-raw` directive has been removed (replaced by `t-out`) ([details](#38-t-raw-directive-has-been-removed-replaced-by-t-out))
- new: add support for synthetic events ([doc](doc/reference/event_handling.md#synthetic-events))
- breaking: style/class on components are now regular props ([details](#10-styleclass-on-components-are-now-regular-props))
- new: components can use the `.bind` suffix to bind function props ([doc](doc/reference/props.md#binding-function-props))
- breaking: `t-on` does not accept expressions, only functions ([details](#30-t-on-does-not-accept-expressions-only-functions))
- new: an error is thrown if an handler defined in a `t-on-` directive is not a function (failed silently previously in some cases)
- breaking: `t-component` no longer accepts strings ([details](#17-t-component-no-longer-accepts-strings))
- new: the `this` variable in template expressions is now bound to the component
**Reactivity**
- finer grained reactivity: owl 2 tracks change per key/component
- finer grained reactivity: sub components can reobserve state ([doc](doc/reference/reactivity.md))
- new: `reactive` function: create reactive state (without being linked to a component) ([doc](doc/reference/reactivity.md#reactive))
- new: `markRaw` function: mark an object or array so that it is ignored by the reactivity system ([doc](doc/reference/reactivity.md#markraw))
- new: `toRaw` function: given a reactive objet, return the raw (non reactive) underlying object ([doc](doc/reference/reactivity.md#toraw))
**Slots**
- breaking: `t-set` does not define a slot any more ([details](#3-t-set-will-no-longer-work-to-define-a-slot))
- slots capabilities have been improved ([doc](doc/reference/slots.md))
- params can be give to slot content (to pass information from slot owner to slot user)
- slots are given as a `prop` (and can be manipulated/propagated to sub components )
- slots can define scopes (to pass information from slot user to slot owner)
**Portal**
- Portal are now defined with `t-portal` ([details](#33-portal-are-now-defined-with-t-portal))
- portals can now have arbitrary content (no longer restricted to one single child)
- breaking: does no longer transfer dom events ([details](#13-portal-does-no-longer-transfer-dom-events))
- breaking: does render as an empty text node instead of `<portal/>` ([details](#14-portal-does-render-as-an-empty-text-node-instead-of-portal))
**Miscellaneous**
- improved performance
- much simpler code
- new App class to encapsulate a root Owl component (with the config for that application) ([doc](doc/reference/app.md))
- new `useEffect` hook ([doc](doc/reference/hooks.md#useeffect))
- breaking: `Context` is removed ([details](#15-context-is-removed))
- breaking: `env` is now totally empty ([details](#16-env-is-now-totally-empty))
- breaking: `env` is now frozen ([details](#28-env-is-now-frozen))
- new hook: `useChildSubEnv` (only applies to child components) ([details](#27-usechildsubenv-only-applies-to-child-components))
- breaking: most exports are exported at top level ([details](#18-most-exports-are-exported-at-top-level))
- breaking: properties are no longer set as attributes ([details](#19-properties-are-no-longer-set-as-attributes))
- breaking: `EventBus` api changed: it is now an `EventTarget` ([details](#21-eventbus-api-changed-it-is-now-an-eventtarget))
- breaking: `Store` is removed ([details](#22-store-is-removed))
- breaking: `Router` is removed ([details](#23-router-is-removed))
- breaking: transition system is removed ([details](#24-transition-system-is-removed))
- breaking: no more global components or templates ([details](#25-no-more-global-components-or-templates))
- breaking: `AsyncRoot` utility component is removed ([details](#26-asyncroot-utility-component-is-removed))
- breaking: `renderToString` function on qweb has been removed ([details](#32-rendertostring-on-qweb-has-been-removed))
- breaking: `debounce` utility function has been removed ([details](#34-debounce-utility-function-has-been-removed))
- breaking: `browser` object has been removed ([details](#39-browser-object-has-been-removed))
## Details/Rationale/Migration
All changes are listed in no particular order.
### 1. component lifecycle methods are removed
There was two ways to define hooks: the component methods (`willStart`, `mounted`, ...) and the hooks (`onWillStart`, `onMounted`, ...). In Owl 2, the component methods have been removed.
Rationale: it makes the implementation simpler and slightly faster. Hooks are more composable
than component methods. It enforces a single entry point to check all the useful lifecycle
calls (instead of it being scattered in the component definition). It feels more "modern".
Migration: lifecycle methods should be defined in the `setup`:
```js
class MyComponent extends Component {
mounted() {
// do something
}
}
```
should become:
```js
class MyComponent extends Component {
setup() {
onMounted(() => {
// do something
});
}
}
```
Documentation: [Component Lifecycle](doc/reference/component.md#lifecycle)
### 2. components can no longer be mounted in a detached dom element
Nor document fragment.
Rationale: it is actually very difficult to do it: this implies that a component
can be mounted more than once, that we need to check every time different status,
that some elements is in the dom, and was a cause for bugs. Also, we don't use it
in practice. Removing this means that we have a much simpler mental model of what
happens.
Migration: well, not really easy. The code needs to be refactored in a different way.
### 3. **`t-set` will no longer work to define a slot**
The `t-set` directive cannot define a slot anymore. Only the `t-set-slot` directive
can do it.
Rationale: it was left for compatibility reason, but was deprecated anyway.
Migration: `t-set` should be changed to `t-set-slot` (when defining a slot)
Example:
```xml
<SideBar><t t-set="content">content</t></SideBar>
```
should become:
```xml
<SideBar><t t-set-slot="content">content</t></SideBar>
```
### 4. `mount` method API is simpler
Before, the `mount` method was used like this:
```js
await mount(Root, { target: document.body });
```
It is now simpler and takes the root component and a target argument:
```js
await mount(Root, document.body);
```
Rationale: the `mount` method is only useful anyway for small toy examples,
because real applications will need to configure the templates, the translations,
and other stuff. All complex usecases need to go through the new `App` class,
that encapsulates the root of an owl application.
Documentation: [Mounting a component](doc/reference/app.md#mount-helper)
### 5. components can no longer be instantiated and mounted by hand
In Owl 1, it was possible to instantiate a component by hand:
```js
const root = new Root();
await root.mount(document.body);
```
Now, it is no longer possible. All component instantiations should be done by
the owl framework itself.
Rationale: the `mount` method does not make sense for all non root components.
Also, the fact that it was possible for a component to be sometimes root,
sometimes a child made for a weird constructor signature. This changes makes it
simpler.
Migration: all code doing that should use either the `mount` method (if the use
case is simple enough, or the `App` class):
```js
const app = new App(Root);
app.configure({ templates: ..., ...});
await app.mount(document.body);
```
### 6. components can no longer be unmounted/remounted
Rationale: this is a very difficult feature to implement (it adds a lot of possible
state transitions), compared to its benefit.
Migration: all code using it should find a way to export and reimport the state
### 7. template name is no longer inferred from the class name
Before, it was possible to define a component without specifying its template:
```js
class Blabla extends Component {
// no static template here!
}
```
with the `Blabla` template. It also worked with subclasses. But then, this means
that the code had to look up all the super classes names to find the correct
template.
Rationale: in practice, it is not really useful, since all templates are usually
namespaced: `web.SomeComponent` anyway. All the trouble to do that was just not
worth it.
Migration: simply explicitely defines the template key everytime:
```js
class Blabla extends Component {}
Blabla.template = "Blabla";
```
### 8. components no longer have a `shouldUpdate` method
Rationale: `shouldUpdate` is a dangerous method to use, that may cause a lot of
issues. Vue does not have such a mechanism (see https://github.com/vuejs/vue/issues/4255),
because the reactivity system in Vue is smart enough to only rerender the minimal
subset of components that is subscribed to a piece of state. Now, Owl 2 features
a much more powerful reactivity system, so the same rationale applies: in a way,
it's like each Owl 2 component has a `shouldUpdate` method that precisely tracks
every value used by the component.
Migration code: remove the `shouldUpdate` methods, and it should work as well
as before.
### 9. component.el is removed
This comes from the fact that Owl 2 supports fragments (arbitrary content).
Migration: if one need a reference to the root htmlelement of a template, it is
suggested to simply add a `ref` on it, and access the reference as needed.
Documentation: [Refs](doc/reference/refs.md)
### 10. style/class on components are now regular props
Before, it was possible to do this in a template:
```xml
<Child style="..." class="..."/>
```
(or with `t-att-style` and `t-att-class`). This does no longer work, as they are
now considered normal props.
Rationale: with the move to fragments, the semantics of where the style/class
attribute should be set is unclear. Also, it is actually very hard to implement
properly, in particular with higher order components. And another issue is that
it (slightly) breaks the encapsulation of behaviour from the `Child` component
perspective.
Migration: each component that wishes to be customized should explicitely add
the `class` and `style` attributes in its template. Also, the parent component
should be aware that since we are talking about props, it should be a javascript expression:
In parent:
```xml
<Child class="'o_my_god'"/>
```
and in child:
```xml
<div t-att-class="props.class">
...
</div>
```
### 11. components can no longer be mounted with position=self
Rationale: this is due to the implementation of owl 2 virtual dom. The hack
necessary to support position=self does not work. This position also is not
compatible with the fact that a component can have a root `<div>` then later,
change it to something else, or even a text node.
Migration: no real way to do the same. Owl application needs to be appended or
prepended in something, maybe a `div`. Remember that you the root component
can have multiple roots
Documentation:
- [Fragments](doc/reference/templates.md#fragments)
- [Mounting a component](doc/reference/app.md#mount-helper)
### 13. Portal does no longer transfer DOM events
In Owl 1, a Portal component would listen to events emitted on its portalled
child, and redispatch them on itself. It no longer works.
Rationale: Portal now supports an arbitrary content (so, more than one child,
and potentially no html element), so it is already unclear what it should listen
to. Also, redispatching events was an hack. And this changes allows the portal
to render itself as a text node, which is nice. This is also in line with the
fact that modern Owl moves toward using callback instead of `t-on` for communication.
Migration: use callback if possible to communicate. Otherwise, use a sub env.
### 14. Portal does render as an empty text node instead of `<portal/>`
That is pretty nice. No real migration needed.
### 15. Context is removed
Context was an abstraction in Owl that was used to define some reactive state
and to let some components subscribe to it, then only them would be rerendered
if the context was updated. This has been removed.
Rationale: first, the Context api and code was kind of awkward, which is a sign
that the abstraction is not well thought. But the good news is that it is actually
completely replaced by the new reactivity system, which is even more powerful,
since it can tracks changes key by key.
Migration: replace all uses of Context with the new reactivity system.
```js
// somewhere, maybe in a service, or in the global env
const context = observe({some: "state"})
// in a component that would previously get a reference to the context:
setup() {
this.context = useState(context);
// now the component is subscribed to the context and will react to any
// change for any key read by the component, and only those changes
}
```
### 16. `env` is now totally empty
In Owl 1, the `env` object had to contain a QWeb instance. This was the way
components would get a reference to their template function. It no longer works
that way: the `env` object is now totally empty (from the perspective of Owl).
It is now a user space concept, useful for the application.
Rationale: first, there is no longer a QWeb class. Also, this changes simplifies
the way components works internally.
Migration: there is no proper way to get an equivalent. The closest is to get
a reference to the root App using `this.__owl__.app`. If you need to do this,
let us know. If this is a legitimate usecase, we may add a `useApp` hook.
Documentation: [Environment](doc/reference/environment.md)
### 17. `t-component` no longer accepts strings
In owl 1, we could write this:
```xml
<t t-component="Coucou"/>
```
This meant that Owl would look for the component class like this: `components["Coucou"]`,
so, essentially equivalent to `<Coucou/>`. In Owl 2, the `t-component` directive
is assumed to be an expression evaluating to a component class:
```js
class Parent extends Component {
static template = xml`<t t-component="Child"/>`;
Child = Child;
}
```
Rationale: it simply seems more consistent with the way directive works. Also,
the implementation is slightly simpler.
Migration: simply using `constructor.components.Coucou` instead of `Coucou` will
do the trick.
Documentation: [Component](doc/reference/component.md#dynamic-sub-components)
### 18. most exports are exported at top level
Most exports are flattened: for ex, `onMounted` is in owl, not in `owl.hooks`.
Rationale: this makes it easier to work with, instead of importing stuff from
`owl`, then `owl.hooks` and `owl.tags` for example.
Migration: all import code simply need to be slightly adapted.
### 19. Properties are no longer set as attributes
Formerly, html properties `<input type="checkbox" t-att-checked="blah"/>` were
set as property and as attribute, so, they would be visible in the DOM:
`<input type="checkbox" checked="blah"/>`. Now, they are treated as property only:
`<input type="checkbox"/>`.
Rationale: this is actually simple to do, is faster, and makes more sense to me.
### 20. `t-foreach` should always have a corresponding `t-key`
It was possible in Owl 1 to write a `t-foreach` without a `t-key`. In that case,
the index was used as key. Since it was clearly a possible bug, Owl 1 had a
warning in some cases, when it could detect that there was definitely not a `t-key`.
However, this was imperfect, and in some cases no warning was displayed. In Owl 2,
the tag with a `t-foreach` has to have a corresponding `t-key`.
Rationale: this makes it easier to avoid bugs.
Migration: simply move the `t-key` to the tag with the `t-foreach`. If this is
a situation where there is really not a need for a `t-key`, you can still add
it with the `_index` suffix:
```xml
<div t-foreach="items" t-as="item" t-key="item_index">
...
</div>
```
### 21. `EventBus` api changed: it is now an `EventTarget`
In Owl 1, the `EventBus` class was done manually, with a custom API. In Owl 2,
it simply extends `EventTarget` (the native Dom class), so its implementation
is basically only 5 lines long. This means that it has now the usual DOM interface:
```js
bus.addEventListener('event-name', callback);
```
Rationale: it makes it easier to have just one interface to remember, it makes
the code simpler
Migration: most bus methods need to be adapted. So, `bus.on("event-type", owner, (info) => {...})` has to be
rewritten like this: `bus.addEventListener("event-type", (({detail: info}) => {...}).bind(owner))`.
Do not forget to similarly replace `bus.off(...)` by `bus.removeEventListener(...)`
Documentation: [EventBus](doc/reference/utils.md#eventbus)
### 22. `Store` is removed
The Store system had been abandoned in owl 2.
Rationale: first, it was complicated to maintain. Second, it was not really
used in Odoo. Finally, the new reactivity system seems to be a pretty good basis
to write a store, and it should not take much work. Also, this can be done in
user space (so, not necessarily at the framework level). Another point is that
the store API was invented before the hooks, then was still a little awkward.
Migration:
- rewrite the code not to use a store
- probably use the reactivity system instead and build a store class and a few
hooks on top of it.
### 23. `Router` is removed
Rationale: Router was not used that much, and it felt like it did not fit in Owl 2.
Its API needs to be reworked, and we are not confident that it is a good
experience to use it. Also, it can be done in userspace (it does not need specific
integration at the framework level)
Migration: reimport all missing piece from the code in Owl 1.
### 24. transition system is removed
Rationale: this was a high ratio cost/value, with a lot of potential for bugs.
We feel like there should be a way to reimplement in userspace the simple cases.
Maybe something like: add a `t-ref` in the template, and define a hook `useFadeOut`
that takes the ref, and add a fadeout class at initial render, then in mounted,
wait for a micro tick and remove it.
Migration: try to reimplement it manually.
### 25. no more global components or templates
It was possible in Owl 1 to register globally a component or a template. This is
no longer the case in Owl 2.
Rationale: first, this was a tradeoff: ease of use was gained, but at the cost
of a higher complexity. Users had to know that there was a magic mechanism. Also,
it was not used much in practice, and the cost of having to import manually components
is low. Finally, this can be mostly done in user space (for example, by subclassing
`Component`).
Migration: import manually all required global components, or find a way to organize
the code to do it.
### 26. `AsyncRoot` utility component is removed
Rationale: it was difficult to understand, never used, and not really useful.
It seems better to control the asynchrony of an application by simply controlling
how/when the state is updated, and how each component is loading/updating itself.
Migration: remove the `AsyncRoot` component, then possibly, reorganize the code
to fetch data in a higher order component, and using a `t-if/t-else` to display
either a fallback when the data is not ready, or the actual component with data
as props. If there is no escape, and `AsyncRoot` is needed, please reach out to
us so we can study this usecase.
### 27. `useChildSubEnv` (only applies to child components)
In Owl, a call to `useSubEnv` would define a new environment for the children
AND the component. It is very useful, but in some cases, one only need to update
the children component environment. This can now be done with a new hook:
[`useChildSubEnv`](doc/reference/hooks.md#usesubenv-and-usechildsubenv)
### 28. `env` is now frozen
In Owl 2, the `env` object is frozen. It can no longer be modified (structurally)
arbitrarily.
Rationale: it seems like the `env` object purpose is to have a global channel of
communication between components. It is however scary if anyone can add something
to it. The usual use case is to add something to the environment for some child
components. This use case still works with `useSubEnv`.
Migration: use `useSubEnv` instead of writing directly to the env. Also, note
that the environment given to the App can initially contain anything.
Documentation: [Environment](doc/reference/environment.md)
### 29. `t-ref` does not work on component
Before, `t-ref` could be used to get a reference to a child component. It no
longer works.
Rationale: the possibility of having a ref to a child component breaks the
encapsulation provided by Owl components: a child component now has a private
and a public interface. Another issue is that it may be unclear when the ref
should be set: is the component active on setup, or on mounted? Also, it is
kind of awkward to implement.
Migration: the `env` and `props` should provide a communication channel wide enough:
the sub component can expose its public API by calling a callback at the proper
timing, or by triggering an event.
### 30. `t-on` does not accept expressions, only functions
In Owl 1, it was possible to define simple expressions inline, in a template:
```xml
<button t-on-click="state.value = state.value + 1">blabla</button>
<button t-on-click="someFunction(someVar)">blabla</button>
```
This does not work anymore. Now, the `t-on` directive assumes that what it get is
a function.
Rationale: the fact that owl 1 had to support expressions meant that it was not
possible to properly inject the event in general. With this restriction, Owl 2
can support more general use cases. Also, the examples above can simply be
wrapped in a lambda function.
Migration: use lambda functions. For example, the two examples above can be
adapted like this:
```xml
<button t-on-click="() => state.value = state.value + 1">blabla</button>
<button t-on-click="() => this.someFunction(someVar)">blabla</button>
```
Documentation: [Event Handling](doc/reference/event_handling.md)
### 31. components can now have arbitrary content
Before Owl 2, components had to limit themselves to one single htmlelement as
root. Now, the content is arbitrary: it can be empty, or multiple html elements.
So, the following template works for components:
```xml
<div>1</div>
<div>2</div>
hello
```
Documentation: [Fragments](doc/reference/templates.md#fragments)
### 32. `renderToString` on QWeb has been removed
Rationale: the `renderToString` function was a qweb method, which made sense because
the qweb instance knew all templates. But now, the closest analogy is the `App`
class, but it is not as convenient, since the `app` instance is no longer visible
to components (while before, `qweb` was in the environment).
Also, this can easily be done in userspace, by mounting a component in a div. For example:
```js
export async function renderToString(template, context) {
class C extends Component {
static template = template;
setup () {
Object.assign(this, context);
}
}
const div = document.createElement('div');
document.body.appendChild(div);
const app = new App(C);
await app.mount(div);
const result = div.innerHTML;
app.destroy();
div.remove();
return result;
}
```
The function above works for most cases, but is asynchronous. An alternative
function could look like this:
```js
const { App, blockDom } = owl;
const app = new App(Component); // act as a template repository
function renderToString(template, context = {}) {
app.addTemplate(template, template, { allowDuplicate: true });
const templateFn = app.getTemplate(template);
const bdom = templateFn(context, {});
const div = document.createElement('div')
blockDom.mount(bdom, div);
return div.innerHTML;
}
```
This is a synchronous function, so it will not work with components, but it should
be useful for most simple templates.
Also note that these two examples do not translate their templates. To do that,
they need to be modified to pass the proper translate function to the `App`
configuration.
### 33. Portal are now defined with `t-portal`
Before Owl 2, one could use the `Portal` component by importing it and using it.
Now, it is no longer available. Instead, we can simply use the `t-portal` directive:
```xml
<div>
some content
<span t-portal="'body'">
portalled content
</span>
<div>
```
Rationale: it makes it slightly simpler to use (just need the directive, instead
of having to import and use a sub component), it makes the implementation slightly
simpler as well. Also, it prevents subclassing the Portal component, which could
be dangerous, since it is really doing weird stuff under the hood, and could
easily be broken inadvertendly.
### 34. `debounce` utility function has been removed
Rationale: it did not really help that much, is available as utility function
elsewhere, so, we decided to have a smaller footprint by focusing Owl on what
it does best.
### 35. `render` method does not return a promise anymore
Rationale: using the `render` method directly and waiting for it to complete
was slightly un-declarative. Also, it can be done using the lifecycle hooks
any way.
Migration: if necessary, one can use the lifecycle hooks to execute code after
the next mounted/patched operation.
### 36. `catchError` method is replaced by `onError` hook
The `catchError` method was used to provide a way to components to handle errors
occurring during the component lifecycle. This has been replaced by a `onError`
hook, with a similar API.
Rationale: `catchError` felt a little big awkward, when most of the way we
interact with componentss is via hooks. Using hooks felt more natural and
consistent.
Migration: mostly replace all `catchError` methods by `onError` hooks in the
`setup` method.
Documentation: [Error Handling](doc/reference/error_handling.md)
## 37. Support for inline css (`css` tag and static `style`) has been removed
Rationale: Owl tries to focus on what it does best, and supporting inline css
was not a priority. It used to support some simplified scss language, but it
was feared that it would cause more trouble than it was worth. Also, it seems
like it can be done in userspace.
Migration: it seems possible to implement an equivalent solution using hooks. A
simple implementation could look like this:
```js
let cache = {};
function useStyle(css) {
if (!css in cache) {
const sheet = document.createElement("style");
sheet.innerHTML = css;
cache[css] = sheet;
document.head.appendChild(sheet);
}
}
```
## 38. `t-raw` directive has been removed (replaced by `t-out`)
To match the Odoo qweb server implementation, Owl does no longer implement `t-raw`.
It is replaced by the `t-out` directive, which is safer: it requires the data
to be marked explicitely as markup if it is to be inserted without escaping.
Otherwise, it will be escaped (just like `t-esc`).
Migration: replace all `t-raw` uses by `t-out`, and uses the `markup` function
to mark all the js values.
Documentation: [Outputting data](doc/reference/templates.md#outputting-data)
## 39. `browser` object has been removed
Rationale: the `browser` object caused more trouble than it was worth. Also, it
seems like this should be done in user space, not at the framework level.
Migration: code should just be adapted to either use another browser object,
or to use native browser function (and then, just mock them directly).
## 40. Rendering a component does not necessarily render child components
Before, if one had the following component tree:
```mermaid
graph TD;
A-->B;
A-->C;
```
when `A` would render, it would also render `B` and `C`. Now, in Owl 2, it will
(shallow) compare the before and after props, and `B` or `C` will only be rerendered
if their props have changed.
Now, the question is what happens if the props have changed, but in a deeper way?
In that case, Owl will know, because each props are now reactive. So, if some
inner value read by `B` was changed, then only `B` will be updated.
Rationale: This was just not possible in Owl 1, but it now possible. This is
due to the rewriteof the underlying rendering engine and the reactivity
system. The goal is to have a big performance boost in large screen with many
components: now Owl only rerender what is strictly useful.
+14
View File
@@ -0,0 +1,14 @@
Most of the files are
Copyright (c) 2004-2015 Odoo S.A.
Many files also contain contributions from third
parties. In this case the original copyright of
the contributions can be traced through the
history of the source version control system.
When that is not the case, the files contain a prominent
notice stating the original copyright and applicable
license, or come with their own dedicated COPYRIGHT
and/or LICENSE file.
+2 -5
View File
@@ -1,12 +1,9 @@
For copyright information, please see the COPYRIGHT file.
Odoo is published under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3
OWL is published under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3
(LGPLv3), as included below. Since the LGPL is a set of additional
permissions on top of the GPL, the text of the GPL is included at the
bottom as well.
Some external libraries and contributions bundled with Odoo may be published
Some external libraries and contributions bundled with OWL may be published
under other GPL-compatible licenses. For these, please refer to the relevant
source files and/or license files, in the source code tree.
+121 -91
View File
@@ -1,119 +1,149 @@
<h1 align="center">🦉 Odoo Web Lab 🦉</h1>
<h1 align="center">🦉 <a href="https://odoo.github.io/owl/">Owl Framework</a> 🦉</h1>
[![License: LGPL v3](https://img.shields.io/badge/License-LGPL%20v3-blue.svg)](https://www.gnu.org/licenses/lgpl-3.0)
[![npm version](https://badge.fury.io/js/@odoo%2Fowl.svg)](https://badge.fury.io/js/@odoo%2Fowl)
[![Downloads](https://img.shields.io/npm/dm/@odoo%2Fowl.svg)](https://www.npmjs.com/package/@odoo/owl)
_Class based components with hooks, reactive state and concurrent mode_
**Try it online!** you can experiment with the Owl framework in an online [playground](https://odoo.github.io/owl/playground).
## Project Overview
Odoo Web Lab (OWL) is a project to collect some useful, reusable, (hopefully)
well designed building blocks for building web applications. However, since this is the basis for the Odoo web client, we will not hesitate
to design the code here to better match the Odoo architecture/design principles.
The Odoo Web Library (Owl) is a smallish (~<20kb gzipped) UI framework built by
[Odoo](https://www.odoo.com/) for its products. Owl is a modern
framework, written in Typescript, taking the best ideas from React and Vue in a
simple and consistent way. Owl's main features are:
The most important element of this repository is certainly the component system.
It is designed to be:
- a declarative component system,
- a fine grained reactivity system similar to Vue,
- hooks
- fragments
- asynchronous rendering
1. **declarative:** the user interface should be described in term of the state
of the application, not as a sequence of imperative steps.
Owl components are defined with ES6 classes and xml templates, uses an
underlying virtual DOM, integrates beautifully with hooks, and the rendering is
asynchronous.
2. **composable:** each widget can seamlessly be created in a parent widget by
a simple directive in its template.
Quick links:
3. **asynchronous rendering:** the framework will transparently wait for each
subwidgets to be ready before applying the rendering. It uses native promises
under the hood.
- [documentation](#documentation),
- [changelog](CHANGELOG.md) (from Owl 1.x to 2.x),
- [playground](https://odoo.github.io/owl/playground)
4. **uses QWeb as a template system:** the templates are described in XML
and follow the QWeb specification. This is a requirement for Odoo.
## Example
5. **with an imperative escape hatch:** if necessary, sub widgets can easily be
manually created/destroyed.
Here is a short example to illustrate interactive components:
Note: the code is written in typescript. This does not mean that the main web
client will ever be converted to typescript (even though I would really like it).
```javascript
const { Component, useState, mount, xml } = owl;
## Installing/Building
class Counter extends Component {
static template = xml`
<button t-on-click="() => state.value = state.value + props.increment">
Click Me! [<t t-esc="state.value"/>]
</button>`;
Some npm scripts are available:
state = useState({ value: 0 });
}
| Command | Description |
| ------------------ | -------------------------------------------------- |
| npm install | install every dependency required for this project |
| npm run build | build a bundle of _owl_ in the _/dist/_ folder |
| npm run minify | minify the prebuilt owl.js file |
| npm run test | run all tests |
| npm run test:watch | run all tests, and keep a watcher |
class Root extends Component {
static template = xml`
<span>Hello Owl</span>
<Counter increment="2"/>`;
static components = { Counter };
}
mount(Root, document.body);
```
Note that the counter component is made reactive with the [`useState` hook](doc/reference/hooks.md#usestate).
Also, all examples here uses the [`xml` helper](doc/reference/templates.md#inline-templates) to define inline templates.
But this is not mandatory, many applications will load templates separately.
More interesting examples can be found on the
[playground](https://odoo.github.io/owl/playground) application.
## Documentation
The complete documentation can be found [here](doc/readme.md). The most important sections are:
### Learning Owl
- [Quick Start](doc/quick_start.md)
- [Tutorial](doc/tutorial.md)
- [Component](doc/component.md)
- [QWeb](doc/qweb.md)
Are you new to Owl? This is the place to start!
# Examples
- [Tutorial: create a TodoList application](doc/learning/tutorial_todoapp.md)
- [How to start an Owl project](doc/learning/quick_start.md)
- [How to test Components](doc/learning/how_to_test.md)
Here is a minimal Hello World example:
### Reference
```javascript
class HelloWorld extends owl.core.Component {
inlineTemplate = `<div>Hello <t t-esc="props.name"/></div>`;
}
- [Overview](doc/readme.md)
- [App](doc/reference/app.md)
- [Component](doc/reference/component.md)
- [Component Lifecycle](doc/reference/component.md#lifecycle)
- [Concurrency Model](doc/reference/concurrency_model.md)
- [Dev mode](doc/reference/app.md#dev-mode)
- [Dynamic sub components](doc/reference/component.md#dynamic-sub-components)
- [Environment](doc/reference/environment.md)
- [Error Handling](doc/reference/error_handling.md)
- [Event Handling](doc/reference/event_handling.md)
- [Form Input Bindings](doc/reference/input_bindings.md)
- [Fragments](doc/reference/templates.md#fragments)
- [Hooks](doc/reference/hooks.md)
- [Loading Templates](doc/reference/app.md#loading-templates)
- [Mounting a component](doc/reference/app.md#mount-helper)
- [Portal](doc/reference/portal.md)
- [Precompiling templates](doc/reference/precompiling_templates.md)
- [Props](doc/reference/props.md)
- [Props Validation](doc/reference/props.md#props-validation)
- [Reactivity](doc/reference/reactivity.md)
- [Rendering SVG](doc/reference/templates.md#rendering-svg)
- [Refs](doc/reference/refs.md)
- [Slots](doc/reference/slots.md)
- [Sub components](doc/reference/component.md#sub-components)
- [Sub templates](doc/reference/templates.md#sub-templates)
- [Templates (Qweb)](doc/reference/templates.md)
- [Translations](doc/reference/translations.md)
- [Utils](doc/reference/utils.md)
const env = {
qweb: new owl.core.QWeb()
};
### Other Topics
- [Notes On Owl Architecture](doc/miscellaneous/architecture.md)
- [Comparison with React/Vue](doc/miscellaneous/comparison.md)
- [Why did Odoo build Owl?](doc/miscellaneous/why_owl.md)
- [Changelog (from owl 1.x to 2.x)](CHANGELOG.md)
- [Notes on compiled templates](doc/miscellaneous/compiled_template.md)
- [Owl devtools extension](doc/tools/devtools.md)
## Installing Owl
Owl is available on `npm` and can be installed with the following command:
const hello = new HelloWorld(env, { name: "World" });
hello.mount(document.body);
```
The next example show how interactive widgets can be created and how widget
composition works:
```javascript
class Counter extends owl.core.Component {
inlineTemplate = `
<div>
<button t-on-click="increment(-1)">-</button>
<span style="font-weight:bold">Value: <t t-esc="state.value"/></span>
<button t-on-click="increment(1)">+</button>
</div>`;
constructor(parent, props) {
super(parent, props);
this.state = {
value: props.initialState || 0
};
}
increment(delta) {
this.updateState({ value: this.state.value + delta });
}
}
class App extends owl.core.Component {
inlineTemplate = `
<div>
<t t-widget="Counter" t-props="{initialState: 1}"/>
<t t-widget="Counter" t-props="{initialState: 42}"/>
</div>`;
widgets = { Counter };
}
const env = {
qweb: new owl.core.QWeb()
};
const app = new App(env);
app.mount(document.body);
npm install @odoo/owl
```
If you want to use a simple `<script>` tag, the last release can be downloaded here:
More interesting examples on how to work with this web framework can be found in the _examples/_ folder:
- [owl](https://github.com/odoo/owl/releases/latest)
- [Todo Application](examples/readme.md#todo-app)
- [Web Client](examples/readme.md#web-client-example)
- [Benchmarks](examples/readme.md#benchmarks)
## Installing Owl devtools
The Owl devtools browser extension is also available in the [release](https://github.com/odoo/owl/releases/latest):
Unzip the owl-devtools.zip file and follow the instructions depending on your browser:
### Chrome
Go to your chrome extensions admin panel, activate developer mode and click on `Load unpacked`.
Select the devtools-chrome folder and that's it, your extension is active!
There is a convenient refresh button on the extension card (still on the same admin page) to update your code.
Do note that if you got some problems, you may need to completly remove and reload the extension to completly refresh the extension.
### Firefox
Go to the address about:debugging#/runtime/this-firefox and click on `Load temporary Add-on...`.
Select any file in the devtools-firefox folder and that's it, your extension is active!
Here, you can use the reload button to refresh the extension.
Note that you may have to open another window or reload your tab to see the extension working.
Also note that the extension will only be active on pages that have a sufficient version of owl.
## License
React is [GPL licensed](./LICENSE).
-30
View File
@@ -1,30 +0,0 @@
# Component
Components are the reusable, composable widgets. They are designed to be low
level, to be declarative, and with asynchronous rendering.
For example:
```javascript
export class Counter extends Component {
inlineTemplate = `
<div t-name="counter">
<button t-on-click="increment(-1)">-</button>
<span style="font-weight:bold">Value: <t t-esc="state.counter"/></span>
<button t-on-click="increment(1)">+</button>
</div>`;
state = {
counter: 0
};
constructor(parent, props) {
super(parent, props);
this.state.counter = props.initialState || 0;
}
increment(delta) {
this.updateState({ counter: this.state.counter + delta });
}
}
```
+95
View File
@@ -0,0 +1,95 @@
# 🦉 How to test Components 🦉
## Content
- [Overview](#overview)
- [Unit Tests](#unit-tests)
## Overview
It is a good practice to test applications and components to ensure that they
behave as expected. There are many ways to test a user interface: manual
testing, integration testing, unit testing, ...
In this section, we will discuss how to write unit tests for components.
## Unit Tests
Writing unit tests for Owl components really depends on the testing framework
used in a project. But usually, it involves the following steps:
- create a test file: for example `SomeComponent.test.js`,
- in that file, import the code for `SomeComponent`,
- add a test case:
- create a real DOM element to use as test fixture,
- create a test environment
- create an instance of `SomeComponent`, mount it to the fixture
- interact with the component and assert some properties.
To help with this, it is useful to have a `helper.js` file that contains some
common utility functions:
```js
let lastFixture = null;
export function makeTestFixture() {
let fixture = document.createElement("div");
document.body.appendChild(fixture);
if (lastFixture) {
lastFixture.remove();
}
lastFixture = fixture;
return fixture;
}
export async function nextTick() {
await new Promise((resolve) => setTimeout(resolve));
await new Promise((resolve) => requestAnimationFrame(resolve));
}
```
With such a file, a typical test suite for Jest will look like this:
```js
// in SomeComponent.test.js
import { SomeComponent } from "../../src/ui/SomeComponent";
import { nextTick, makeTestFixture } from '../helpers';
//------------------------------------------------------------------------------
// Setup
//------------------------------------------------------------------------------
let fixture: HTMLElement;
let env: Env;
beforeEach(() => {
fixture = makeTestFixture();
});
afterEach(() => {
fixture.remove();
});
//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
describe("SomeComponent", () => {
test("component behaves as expected", async () => {
const props = {...}; // depends on the component
const comp = await mount(SomeComponent, fixture, { props });
// do some assertions
expect(...).toBe(...);
fixture.querySelector('button').click();
await nextTick();
// some other assertions
expect(...).toBe(...);
});
});
```
Note that Owl does wait for the next animation frame to actually update the DOM.
This is why it is necessary to wait with the `nextTick` (or other methods) to
make sure that the DOM is up-to-date.
+399
View File
@@ -0,0 +1,399 @@
# 🦉 How to start an Owl project 🦉
## Content
- [Overview](#overview)
- [Simple html file](#simple-html-file)
- [With a static server](#with-a-static-server)
- [Standard Javascript project](#standard-javascript-project)
## Overview
Each software project has its specific needs. Many of these needs can be solved
with some tooling: `webpack`, `gulp`, css preprocessor, bundlers, transpilers, ...
Because of that, it is usually not simple to just start a project. Some
frameworks provide their own tooling to help with that. But then, you have to
integrate and learn how these applications work.
Owl is designed to be used with no tooling at all. Because of that, Owl can
"easily" be integrated in a modern build toolchain. In this section, we will
discuss a few different setups to start a project. Each of these setups has
advantages and disadvantages in different situations.
## Simple html file
The simplest possible setup is the following: a simple javascript file with your
code. To do that, let us create the following file structure:
```
hello_owl/
index.html
owl.js
app.js
```
The file `owl.js` can be downloaded from the last release published at
[https://github.com/odoo/owl/releases](https://github.com/odoo/owl/releases). It
is a single javascript file which export all Owl into the global `owl` object.
Note that there are multiple files, and in this case, we need one of the two
files suffixed with `.iife`: they are built to be directly used in a browser.
Now, `index.html` should contain the following:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello Owl</title>
<script src="owl.js"></script>
</head>
<body>
<script src="app.js"></script>
</body>
</html>
```
And `app.js` should look like this:
```js
const { Component, mount, xml } = owl;
// Owl Components
class Root extends Component {
static template = xml`<div>Hello Owl</div>`;
}
mount(Root, document.body);
```
Now, simply loading this html file in a browser should display a welcome message.
This setup is not fancy, but it is extremely simple. There are no tooling at
all required. It can be slightly optimized by using the minified build of Owl.
## With a static server
The previous setup has a big disadvantage: the application code is located in a
single file. Obviously, we could split it in several files and add multiple
`<script>` tags in the html page, but then we need to make sure the script are
inserted in the proper order, we need to export each file content in global
variables and we lose autocompletion across files.
There is a low tech solution to this issue: using native javascript modules.
This however has a requirement: for security reasons, browsers will not accept
modules on content served through the `file` protocol. This means that we need
to use a static server.
Let us start a new project with the following file structure:
```
hello_owl/
src/
index.html
main.js
owl.js
root.js
```
As previously, the file `owl.js` can be downloaded from the last release published at
[https://github.com/odoo/owl/releases](https://github.com/odoo/owl/releases).
Note that there are multiple files, and in this case, we need one of the two
files suffixed with `.iife`: they are built to be directly used in a browser.
Now, `index.html` should contain the following:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello Owl</title>
<script src="owl.js"></script>
</head>
<body>
<script src="main.js" type="module"></script>
</body>
</html>
```
Not that the `main.js` script tag has the `type="module"` attribute. This means
that the browser will parse the script as a module, and load all its dependencies.
Here is the content of `root.js` and `main.js`:
```js
// root.js ----------------------------------------------------------------------
const { Component, mount, xml } = owl;
export class Root extends Component {
static template = xml`<div>Hello Owl</div>`;
}
// main.js ---------------------------------------------------------------------
import { Root } from "./root.js";
mount(Root, document.body);
```
The `main.js` file imports the `root.js` file. Note that the import statement has
a `.js` suffix, which is important. Most text editor can understand this syntax
and will provide autocompletion.
Now, to execute this code, we need to serve the `src` folder statically. A low
tech way to do that is to use for example the python `SimpleHTTPServer` feature:
```
$ cd src
$ python -m SimpleHTTPServer 8022 # now content is available at localhost:8022
```
Another more "javascripty" way to do it is to create a `npm` application. To do
that, we can add the following `package.json` file at the root of the project:
```json
{
"name": "hello_owl",
"version": "0.1.0",
"description": "Starting Owl app",
"main": "src/index.html",
"scripts": {
"serve": "serve src"
},
"author": "John",
"license": "ISC",
"devDependencies": {
"serve": "^11.3.0"
}
}
```
We can now install the `serve` tool with the command `npm install`, and then,
start a static server with the simple `npm run serve` command.
## Standard Javascript project
The previous setup works, and is certainly good for some usecases, including
quick prototyping. However, it lacks some useful features, such as livereload,
a test suite, or bundling the code in a single file.
Each of these features, and many others, can be done in many different ways.
Since it is really not trivial to configure such a project, we provide here an
example that can be used as a starting point.
Our standard Owl project has the following file structure:
```
hello_owl/
public/
index.html
src/
components/
Root.js
main.js
tests/
components/
Root.test.js
helpers.js
.gitignore
package.json
webpack.config.js
```
This project as a `public` folder, meant to contain all static assets, such as
images and styles. The `src` folder has the javascript source code, and finally,
`tests` contains the test suite.
Here is the content of `index.html`:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello Owl</title>
</head>
<body></body>
</html>
```
Note that there are no `<script>` tag here. They will be injected by webpack.
Now, let's have a look at the javascript files:
```js
// src/components/Root.js -------------------------------------------------------
import { Component, xml, useState } from "@odoo/owl";
export class Root extends Component {
static template = xml`
<div t-on-click="update">
Hello <t t-esc="state.text"/>
</div>`;
state = useState({ text: "Owl" });
update() {
this.state.text = this.state.text === "Owl" ? "World" : "Owl";
}
}
// src/main.js -----------------------------------------------------------------
import { utils, mount } from "@odoo/owl";
import { Root } from "./components/Root";
mount(Root, document.body);
// tests/components/Root.test.js ------------------------------------------------
import { Root } from "../../src/components/Root";
import { makeTestFixture, nextTick, click } from "../helpers";
import { mount } from "@odoo/owl";
let fixture;
beforeEach(() => {
fixture = makeTestFixture();
});
afterEach(() => {
fixture.remove();
});
describe("Root", () => {
test("Works as expected...", async () => {
await mount(Root, fixture);
expect(fixture.innerHTML).toBe("<div>Hello Owl</div>");
click(fixture, "div");
await nextTick();
expect(fixture.innerHTML).toBe("<div>Hello World</div>");
});
});
// tests/helpers.js ------------------------------------------------------------
import { Component } from "@odoo/owl";
import "regenerator-runtime/runtime";
export async function nextTick() {
await new Promise((resolve) => setTimeout(resolve));
await new Promise((resolve) => requestAnimationFrame(resolve));
}
export function makeTestFixture() {
let fixture = document.createElement("div");
document.body.appendChild(fixture);
return fixture;
}
export function click(elem, selector) {
elem.querySelector(selector).dispatchEvent(new Event("click"));
}
```
Finally, here is the configuration files `.gitignore`, `package.json` and
`webpack.config.js`:
```
node_modules/
package-lock.json
dist/
```
```json
{
"name": "hello_owl",
"version": "0.1.0",
"description": "Demo app",
"main": "src/index.html",
"scripts": {
"test": "jest",
"build": "webpack --mode production",
"dev": "webpack-dev-server --mode development"
},
"author": "Someone",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.8.4",
"@babel/plugin-proposal-class-properties": "^7.8.3",
"babel-jest": "^25.1.0",
"babel-loader": "^8.0.6",
"babel-plugin-transform-es2015-modules-commonjs": "^6.26.2",
"html-webpack-plugin": "^3.2.0",
"jest": "^25.1.0",
"regenerator-runtime": "^0.13.3",
"serve": "^11.3.0",
"webpack": "^4.41.5",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.10.2"
},
"dependencies": {
"@odoo/owl": "^1.0.4"
},
"babel": {
"plugins": ["@babel/plugin-proposal-class-properties"],
"env": {
"test": {
"plugins": ["transform-es2015-modules-commonjs"]
}
}
},
"jest": {
"verbose": false,
"testRegex": "(/tests/.*(test|spec))\\.js?$",
"moduleFileExtensions": ["js"],
"transform": {
"^.+\\.[t|j]sx?$": "babel-jest"
}
}
}
```
```js
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const host = process.env.HOST || "localhost";
module.exports = function (env, argv) {
const mode = argv.mode || "development";
return {
mode: mode,
entry: "./src/main.js",
output: {
filename: "main.js",
path: path.resolve(__dirname, "dist"),
},
module: {
rules: [
{
test: /\.jsx?$/,
loader: "babel-loader",
exclude: /node_modules/,
},
],
},
resolve: {
extensions: [".js", ".jsx"],
},
devServer: {
contentBase: path.resolve(__dirname, "public/index.html"),
compress: true,
hot: true,
host,
port: 3000,
publicPath: "/",
},
plugins: [
new HtmlWebpackPlugin({
inject: true,
template: path.resolve(__dirname, "public/index.html"),
}),
],
};
};
```
With this setup, we can now use the following script commands:
```
npm run build # build the full application in prod mode in dist/
npm run dev # start a dev server with livereload
npm run test # run the jest test suite
```
+997
View File
@@ -0,0 +1,997 @@
# 🦉 OWL Tutorial: TodoApp 🦉
For this tutorial, we will build a very simple Todo list application. The app
should satisfy the following requirements:
- let the user create and remove tasks
- tasks can be marked as completed
- tasks can be filtered to display active/completed tasks
This project will be an opportunity to discover and learn some important Owl
concepts, such as components, store, and how to organize an application.
## Content
1. [Setting up the project](#1-setting-up-the-project)
2. [Adding a first component](#2-adding-a-first-component)
3. [Displaying a list of tasks](#3-displaying-a-list-of-tasks)
4. [Layout: some basic css](#4-layout-some-basic-css)
5. [Extracting Task as a subcomponent](#5-extracting-task-as-a-subcomponent)
6. [Adding tasks (part 1)](#6-adding-tasks-part-1)
7. [Adding tasks (part 2)](#7-adding-tasks-part-2)
8. [Toggling tasks](#8-toggling-tasks)
9. [Deleting tasks](#9-deleting-tasks)
10. [Using a store](#10-using-a-store)
11. [Saving tasks in local storage](#11-saving-tasks-in-local-storage)
12. [Filtering tasks](#12-filtering-tasks)
13. [The Final Touch](#13-the-final-touch)
14. [Final Code](#final-code)
## 1. Setting up the project
For this tutorial, we will do a very simple project, with static files and
no additional tooling. The first step is to create the following file structure:
```
todoapp/
index.html
app.css
app.js
owl.js
```
The entry point for this application is the file `index.html`, which should have
the following content:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>OWL Todo App</title>
<link rel="stylesheet" href="app.css" />
</head>
<body>
<script src="owl.js"></script>
<script src="app.js"></script>
</body>
</html>
```
Then, `app.css` can be left empty for now. It will be useful later on to style
our application. `app.js` is where we will write all our code. For now, let's
just put the following code:
```js
(function () {
console.log("hello owl", owl.__info__.version);
})();
```
Note that we put everything inside an immediately executed function to avoid leaking
anything to the global scope.
Finally, `owl.js` should be the last version downloaded from the Owl repository (you can use `owl.min.js` if you prefer). Be aware that you should download the `owl.iife.js` or `owl.iife.min.js`, because these files
are built to run directly on the browser, and rename it `owl.js` (other files such as `owl.cjs.js` are
built to be bundled by other tools).
Now, the project should be ready. Loading the `index.html` file into a browser
should show an empty page, with the title `Owl Todo App`, and it should log a
message such as `hello owl 2.x.y` in the console.
## 2. Adding a first component
An Owl application is made out of [components](../reference/component.md), with
a single root component. Let us start by defining a `Root` component. Replace the
content of the function in `app.js` by the following code:
```js
const { Component, mount, xml } = owl;
// Owl Components
class Root extends Component {
static template = xml`<div>todo app</div>`;
}
mount(Root, document.body);
```
Now, reloading the page in a browser should display a message.
The code is pretty simple: we define a component with an inline template, then
mount it in the document body.
Note 1: in a larger project, we would split the code in multiple files, with
components in a sub folder, and a main file that would initialize the application.
However, this is a very small project, and we want to keep it as simple as possible.
Note 2: this tutorial uses the static class field syntax. This is not yet
supported by all browsers. Most real projects will transpile their code, so this
is not a problem, but for this tutorial, if you need the code to work on every
browser, you will need to translate each `static` keyword to an assignation to
the class:
```js
class App extends Component {}
App.template = xml`<div>todo app</div>`;
```
Note 3: writing inline templates with the [`xml` helper](../reference/templates.md#inline-templates)
is nice, but there is no syntax highlighting, and this makes it very easy to
have malformed xml. Some editors support syntax highlighting for this situation.
For example, VS Code has an addon `Comment tagged template`, which, if installed,
will properly display tagged templates:
```js
static template = xml /* xml */`<div>todo app</div>`;
```
Note 4: Large applications will probably want to be able to translate templates.
Using inline templates makes it slightly harder, since we need additional tooling
to extract the xml from the code, and to replace it with the translated values.
## 3. Displaying a list of tasks
Now that the basics are done, it is time to start thinking about tasks. To
accomplish what we need, we will keep track of the tasks as an array of objects
with the following keys:
- `id`: a number. It is extremely useful to have a way to uniquely identify
tasks. Since the title is something created/edited by the user, it offers
no guarantee that it is unique. So, we will generate a unique `id` number for
each task.
- `text`: a string, to explain what the task is about.
- `isCompleted`: a boolean, to keep track of the status of the task
Now that we decided on the internal format of the state, let us add some demo
data and a template to the `App` component:
```js
class Root extends Component {
static template = xml/* xml */ `
<div class="task-list">
<t t-foreach="tasks" t-as="task" t-key="task.id">
<div class="task">
<input type="checkbox" t-att-checked="task.isCompleted"/>
<span><t t-esc="task.text"/></span>
</div>
</t>
</div>`;
tasks = [
{
id: 1,
text: "buy milk",
isCompleted: true,
},
{
id: 2,
text: "clean house",
isCompleted: false,
},
];
}
```
The template contains a [`t-foreach`](../reference/templates.md#loops) loop to iterate
through the tasks. It can find the `tasks` list from the component, since the rendering
context contains the properties of the component. Note that we use the `id` of each task
as a `t-key`, which is very common. There are two css classes: `task-list` and `task`,
that we will use in the next section.
Finally, notice the use of the `t-att-checked` attribute:
prefixing an attribute by [`t-att`](../reference/templates.md#dynamic-attributes) makes
it dynamic. Owl will evaluate the expression and set it as the value of the
attribute.
## 4. Layout: some basic css
So far, our task list looks quite bad. Let us add the following to `app.css`:
```css
.task-list {
width: 300px;
margin: 50px auto;
background: aliceblue;
padding: 10px;
}
.task {
font-size: 18px;
color: #111111;
}
```
This is better. Now, let us add an extra feature: completed tasks should be
styled a little differently, to make it clearer that they are not as important.
To do that, we will add a dynamic css class on each task:
```xml
<div class="task" t-att-class="task.isCompleted ? 'done' : ''">
```
```css
.task.done {
opacity: 0.7;
}
```
Notice that we have here another use of a dynamic attribute.
## 5. Extracting Task as a subcomponent
It is now clear that there should be a `Task` component to encapsulate the look
and behavior of a task.
This `Task` component will display a task, but it cannot _own_ the state of the
task: a piece of data should only have one owner. Doing otherwise is asking for
trouble. So, the `Task` component will get its data as a `prop`. This means that
the data is still owned by the `App` component, but can be used by the `Task`
component (without modifying it).
Since we are moving code around, it is a good opportunity to refactor the code
a little bit:
```js
// -------------------------------------------------------------------------
// Task Component
// -------------------------------------------------------------------------
class Task extends Component {
static template = xml /* xml */`
<div class="task" t-att-class="props.task.isCompleted ? 'done' : ''">
<input type="checkbox" t-att-checked="props.task.isCompleted"/>
<span><t t-esc="props.task.text"/></span>
</div>`;
static props = ["task"];
}
// -------------------------------------------------------------------------
// Root Component
// -------------------------------------------------------------------------
class Root extends Component {
static template = xml /* xml */`
<div class="task-list">
<t t-foreach="tasks" t-as="task" t-key="task.id">
<Task task="task"/>
</t>
</div>`;
static components = { Task };
tasks = [
...
];
}
// -------------------------------------------------------------------------
// Setup
// -------------------------------------------------------------------------
mount(Root, document.body, {dev: true});
```
A lot of stuff happened here:
- first, we have now a sub component `Task`, defined on top of the file,
- whenever we define a sub component, it needs to be added to the static
[`components`](../reference/component.md#static-properties)
key of its parent, so Owl can get a reference to it,
- the `Task` component has a `props` key: this is only useful for validation
purpose. It says that each `Task` should be given exactly one prop, named
`task`. If this is not the case, Owl will throw an
[error](../reference/props.md#props-validation). This is extremely
useful when refactoring components
- finally, to activate the props validation, we need to set Owl's
[mode](../reference/app.md#configuration) to `dev`. This is done in the last argument
of the `mount` function. Note that this should be removed when an app is used in a real
production environment, since `dev` mode is slightly slower, due to extra
checks and validations.
## 6. Adding tasks (part 1)
We still use a list of hardcoded tasks. It's really time to give the user a way
to add tasks himself. The first step is to add an input to the `Root` component.
But this input will be outside of the task list, so we need to adapt `Root`
template, js, and css:
```xml
<div class="todo-app">
<input placeholder="Enter a new task" t-on-keyup="addTask"/>
<div class="task-list">
<t t-foreach="tasks" t-as="task" t-key="task.id">
<Task task="task"/>
</t>
</div>
</div>
```
```js
addTask(ev) {
// 13 is keycode for ENTER
if (ev.keyCode === 13) {
const text = ev.target.value.trim();
ev.target.value = "";
console.log('adding task', text);
// todo
}
}
```
```css
.todo-app {
width: 300px;
margin: 50px auto;
background: aliceblue;
padding: 10px;
}
.todo-app > input {
display: block;
margin: auto;
}
.task-list {
margin-top: 8px;
}
```
We now have a working input, which log to the console whenever the user adds a
task. Notice that when you load the page, the input is not focused. But adding
tasks is a core feature of a task list, so let us make it as fast as possible by
focusing the input.
We need to execute code when the `Root` component is ready (mounted). Let's do
that using the `onMounted` hook. We will also need to get a reference to the
input, by using the `t-ref` directive with the [`useRef`](../reference/hooks.md#useref) hook:
```xml
<input placeholder="Enter a new task" t-on-keyup="addTask" t-ref="add-input"/>
```
```js
// on top of file:
const { Component, mount, xml, useRef, onMounted } = owl;
```
```js
// in App
setup() {
const inputRef = useRef("add-input");
onMounted(() => inputRef.el.focus());
}
```
This is a very common situation: whenever we need to perform some actions depending
on the lifecycle of a component, we need to do it in the `setup` method, by using
one of the lifecycle hook. Here, we first get a reference to the `inputRef`,
then in the `onMounted` hook, we simply focus the html element.
## 7. Adding tasks (part 2)
In the previous section, we did everything except implement the code that actually
create tasks! So, let us do that now.
We need a way to generate unique `id` numbers. To do that, we will simply add a
`nextId` number in `App`. At the same time, let us remove the demo tasks in `App`:
```js
nextId = 1;
tasks = [];
```
Now, the `addTask` method can be implemented:
```js
addTask(ev) {
// 13 is keycode for ENTER
if (ev.keyCode === 13) {
const text = ev.target.value.trim();
ev.target.value = "";
if (text) {
const newTask = {
id: this.nextId++,
text: text,
isCompleted: false,
};
this.tasks.push(newTask);
}
}
}
```
This almost works, but if you test it, you will notice that no new task is ever
displayed when the user press `Enter`. But if you add a `debugger` or a
`console.log` statement, you will see that the code is actually running as
expected. The problem is that Owl has no way of knowing that it needs to rerender
the user interface. We can fix the issue by making `tasks` reactive, with the
[`useState`](../reference/hooks.md#usestate) hook:
```js
// on top of the file
const { Component, mount, xml, useRef, onMounted, useState } = owl;
// replace the task definition in App with the following:
tasks = useState([]);
```
It now works as expected!
## 8. Toggling tasks
If you tried to mark a task as completed, you may have noticed that the text
did not change in opacity. This is because there is no code to modify the
`isCompleted` flag.
Now, this is an interesting situation: the task is displayed by the `Task`
component, but it is not the owner of its state, so ideally, it should not modify it.
However, for now, that's what we will do (this will be improved in a later step).
In `Task`, change the `input` to:
```xml
<input type="checkbox" t-att-checked="props.task.isCompleted" t-on-click="toggleTask"/>
```
and add the `toggleTask` method:
```js
toggleTask() {
this.props.task.isCompleted = !this.props.task.isCompleted;
}
```
## 9. Deleting tasks
Let us now add the possibility do delete tasks. This is different from the previous
feature: deleting task has to be done on the task itself, but the actual operation
need to be done on the task list. So, we need to communicate the request to the
`Root` component. This is usually done by providing a callback in a prop.
First, let us update the `Task` template, css and js:
```xml
<div class="task" t-att-class="props.task.isCompleted ? 'done' : ''">
<input type="checkbox" t-att-checked="props.task.isCompleted" t-on-click="toggleTask"/>
<span><t t-esc="props.task.text"/></span>
<span class="delete" t-on-click="deleteTask">🗑</span>
</div>
```
```css
.task {
font-size: 18px;
color: #111111;
display: grid;
grid-template-columns: 30px auto 30px;
}
.task > input {
margin: auto;
}
.delete {
opacity: 0;
cursor: pointer;
text-align: center;
}
.task:hover .delete {
opacity: 1;
}
```
```js
static props = ["task", "onDelete"];
deleteTask() {
this.props.onDelete(this.props.task);
}
```
And now, we need to provide the `onDelete` callback to each tasks in the `Root`
component:
```xml
<Task task="task" onDelete.bind="deleteTask"/>
```
```js
deleteTask(task) {
const index = this.tasks.findIndex(t => t.id === task.id);
this.tasks.splice(index, 1);
}
```
Notice that the `onDelete` prop is defined with a `.bind` suffix: this is a special
suffix that makes sure the function callback is bound to the component.
Notice also that we have two functions named `deleteTask`. The one in the Task
component just delegates the work to the Root component that owns the task list
via the `onDelete` property.
## 10. Using a store
Looking at the code, it is apparent that all the code handling tasks is scattered
all around the application. Also, it mixes UI code and business logic
code. Owl does not provide any high level abstraction to manage business logic,
but it is easy to do it with the basic reactivity primitives (`useState` and `reactive`).
Let us use it in our application to implement a central store. This is a pretty
large refactoring (for our application), since it involves extracting all task
related code out of the components. Here is the new content of the `app.js` file:
```js
const { Component, mount, xml, useRef, onMounted, useState, reactive, useEnv } = owl;
// -------------------------------------------------------------------------
// Store
// -------------------------------------------------------------------------
function useStore() {
const env = useEnv();
return useState(env.store);
}
// -------------------------------------------------------------------------
// TaskList
// -------------------------------------------------------------------------
class TaskList {
nextId = 1;
tasks = [];
addTask(text) {
text = text.trim();
if (text) {
const task = {
id: this.nextId++,
text: text,
isCompleted: false,
};
this.tasks.push(task);
}
}
toggleTask(task) {
task.isCompleted = !task.isCompleted;
}
deleteTask(task) {
const index = this.tasks.findIndex((t) => t.id === task.id);
this.tasks.splice(index, 1);
}
}
function createTaskStore() {
return reactive(new TaskList());
}
// -------------------------------------------------------------------------
// Task Component
// -------------------------------------------------------------------------
class Task extends Component {
static template = xml/* xml */ `
<div class="task" t-att-class="props.task.isCompleted ? 'done' : ''">
<input type="checkbox" t-att-checked="props.task.isCompleted" t-on-click="() => store.toggleTask(props.task)"/>
<span><t t-esc="props.task.text"/></span>
<span class="delete" t-on-click="() => store.deleteTask(props.task)">🗑</span>
</div>`;
static props = ["task"];
setup() {
this.store = useStore();
}
}
// -------------------------------------------------------------------------
// Root Component
// -------------------------------------------------------------------------
class Root extends Component {
static template = xml/* xml */ `
<div class="todo-app">
<input placeholder="Enter a new task" t-on-keyup="addTask" t-ref="add-input"/>
<div class="task-list">
<t t-foreach="store.tasks" t-as="task" t-key="task.id">
<Task task="task"/>
</t>
</div>
</div>`;
static components = { Task };
setup() {
const inputRef = useRef("add-input");
onMounted(() => inputRef.el.focus());
this.store = useStore();
}
addTask(ev) {
// 13 is keycode for ENTER
if (ev.keyCode === 13) {
this.store.addTask(ev.target.value);
ev.target.value = "";
}
}
}
// -------------------------------------------------------------------------
// Setup
// -------------------------------------------------------------------------
const env = {
store: createTaskStore(),
};
mount(Root, document.body, { dev: true, env });
```
## 11. Saving tasks in local storage
Now, our TodoApp works great, except if the user closes or refresh the browser!
It is really inconvenient to only keep the state of the application in memory.
To fix this, we will save the tasks in the local storage. With our current
codebase, it is a simple change: we need to save tasks to local storage and
listen to any change.
```js
class TaskList {
constructor(tasks) {
this.tasks = tasks || [];
const taskIds = this.tasks.map((t) => t.id);
this.nextId = taskIds.length ? Math.max(...taskIds) + 1 : 1;
}
// ...
}
function createTaskStore() {
const saveTasks = () => localStorage.setItem("todoapp", JSON.stringify(taskStore.tasks));
const initialTasks = JSON.parse(localStorage.getItem("todoapp") || "[]");
const taskStore = reactive(new TaskList(initialTasks), saveTasks);
saveTasks();
return taskStore;
}
```
The key point is that the `reactive` function takes a callback that will be called
every time an observed value is changed. Note that we need to call the `saveTasks`
method initially to make sure we observe all current values.
## 12. Filtering tasks
We are almost done, we can add/update/delete tasks. The only missing feature is
the possibility to display the task according to their completed status. We will
need to keep track of the state of the filter in `Root`, then filter the visible
tasks according to its value.
```js
class Root extends Component {
static template = xml /* xml */`
<div class="todo-app">
<input placeholder="Enter a new task" t-on-keyup="addTask" t-ref="add-input"/>
<div class="task-list">
<t t-foreach="displayedTasks" t-as="task" t-key="task.id">
<Task task="task"/>
</t>
</div>
<div class="task-panel" t-if="store.tasks.length">
<div class="task-counter">
<t t-esc="displayedTasks.length"/>
<t t-if="displayedTasks.length lt store.tasks.length">
/ <t t-esc="store.tasks.length"/>
</t>
task(s)
</div>
<div>
<span t-foreach="['all', 'active', 'completed']"
t-as="f" t-key="f"
t-att-class="{active: filter.value===f}"
t-on-click="() => this.setFilter(f)"
t-esc="f"/>
</div>
</div>
</div>`;
setup() {
...
this.filter = useState({ value: "all" });
}
get displayedTasks() {
const tasks = this.store.tasks;
switch (this.filter.value) {
case "active": return tasks.filter(t => !t.isCompleted);
case "completed": return tasks.filter(t => t.isCompleted);
case "all": return tasks;
}
}
setFilter(filter) {
this.filter.value = filter;
}
}
```
```css
.task-panel {
color: #0088ff;
margin-top: 8px;
font-size: 14px;
display: flex;
}
.task-panel .task-counter {
flex-grow: 1;
}
.task-panel span {
padding: 5px;
cursor: pointer;
}
.task-panel span.active {
font-weight: bold;
}
```
Notice here that we set dynamically the css class of the filter with the object
syntax.
## 13. The Final Touch
Our list is feature complete. We can still add a few extra details to improve
the user experience.
1. Add a visual feedback when the user mouse is over a task:
```css
.task:hover {
background-color: #def0ff;
}
```
2. Make the text of a task clickable, to toggle its checkbox:
```xml
<input type="checkbox" t-att-checked="props.task.isCompleted"
t-att-id="props.task.id"
t-on-click="() => store.toggleTask(props.task)"/>
<label t-att-for="props.task.id"><t t-esc="props.task.text"/></label>
```
3. Strike the text of completed task:
```css
.task.done label {
text-decoration: line-through;
}
```
## Final code
Our application is now complete. It works, the UI code is well separated from
the business logic code, it is testable, all under 150 lines of code (template
included!).
For reference, here is the final code:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>OWL Todo App</title>
<link rel="stylesheet" href="app.css" />
</head>
<body>
<script src="owl.js"></script>
<script src="app.js"></script>
</body>
</html>
```
```js
(function () {
const { Component, mount, xml, useRef, onMounted, useState, reactive, useEnv } = owl;
// -------------------------------------------------------------------------
// Store
// -------------------------------------------------------------------------
function useStore() {
const env = useEnv();
return useState(env.store);
}
// -------------------------------------------------------------------------
// TaskList
// -------------------------------------------------------------------------
class TaskList {
constructor(tasks) {
this.tasks = tasks || [];
const taskIds = this.tasks.map((t) => t.id);
this.nextId = taskIds.length ? Math.max(...taskIds) + 1 : 1;
}
addTask(text) {
text = text.trim();
if (text) {
const task = {
id: this.nextId++,
text: text,
isCompleted: false,
};
this.tasks.push(task);
}
}
toggleTask(task) {
task.isCompleted = !task.isCompleted;
}
deleteTask(task) {
const index = this.tasks.findIndex((t) => t.id === task.id);
this.tasks.splice(index, 1);
}
}
function createTaskStore() {
const saveTasks = () => localStorage.setItem("todoapp", JSON.stringify(taskStore.tasks));
const initialTasks = JSON.parse(localStorage.getItem("todoapp") || "[]");
const taskStore = reactive(new TaskList(initialTasks), saveTasks);
saveTasks();
return taskStore;
}
// -------------------------------------------------------------------------
// Task Component
// -------------------------------------------------------------------------
class Task extends Component {
static template = xml/* xml */ `
<div class="task" t-att-class="props.task.isCompleted ? 'done' : ''">
<input type="checkbox"
t-att-id="props.task.id"
t-att-checked="props.task.isCompleted"
t-on-click="() => store.toggleTask(props.task)"/>
<label t-att-for="props.task.id"><t t-esc="props.task.text"/></label>
<span class="delete" t-on-click="() => store.deleteTask(props.task)">🗑</span>
</div>`;
static props = ["task"];
setup() {
this.store = useStore();
}
}
// -------------------------------------------------------------------------
// Root Component
// -------------------------------------------------------------------------
class Root extends Component {
static template = xml/* xml */ `
<div class="todo-app">
<input placeholder="Enter a new task" t-on-keyup="addTask" t-ref="add-input"/>
<div class="task-list">
<t t-foreach="displayedTasks" t-as="task" t-key="task.id">
<Task task="task"/>
</t>
</div>
<div class="task-panel" t-if="store.tasks.length">
<div class="task-counter">
<t t-esc="displayedTasks.length"/>
<t t-if="displayedTasks.length lt store.tasks.length">
/ <t t-esc="store.tasks.length"/>
</t>
task(s)
</div>
<div>
<span t-foreach="['all', 'active', 'completed']"
t-as="f" t-key="f"
t-att-class="{active: filter.value===f}"
t-on-click="() => this.setFilter(f)"
t-esc="f"/>
</div>
</div>
</div>`;
static components = { Task };
setup() {
const inputRef = useRef("add-input");
onMounted(() => inputRef.el.focus());
this.store = useStore();
this.filter = useState({ value: "all" });
}
addTask(ev) {
// 13 is keycode for ENTER
if (ev.keyCode === 13) {
this.store.addTask(ev.target.value);
ev.target.value = "";
}
}
get displayedTasks() {
const tasks = this.store.tasks;
switch (this.filter.value) {
case "active":
return tasks.filter((t) => !t.isCompleted);
case "completed":
return tasks.filter((t) => t.isCompleted);
case "all":
return tasks;
}
}
setFilter(filter) {
this.filter.value = filter;
}
}
// -------------------------------------------------------------------------
// Setup
// -------------------------------------------------------------------------
const env = { store: createTaskStore() };
mount(Root, document.body, { dev: true, env });
})();
```
```css
.todo-app {
width: 300px;
margin: 50px auto;
background: aliceblue;
padding: 10px;
}
.todo-app > input {
display: block;
margin: auto;
}
.task-list {
margin-top: 8px;
}
.task {
font-size: 18px;
color: #111111;
display: grid;
grid-template-columns: 30px auto 30px;
}
.task:hover {
background-color: #def0ff;
}
.task > input {
margin: auto;
}
.delete {
opacity: 0;
cursor: pointer;
text-align: center;
}
.task:hover .delete {
opacity: 1;
}
.task.done {
opacity: 0.7;
}
.task.done label {
text-decoration: line-through;
}
.task-panel {
color: #0088ff;
margin-top: 8px;
font-size: 14px;
display: flex;
}
.task-panel .task-counter {
flex-grow: 1;
}
.task-panel span {
padding: 5px;
cursor: pointer;
}
.task-panel span.active {
font-weight: bold;
}
```
+68
View File
@@ -0,0 +1,68 @@
# 🦉 Notes On Owl Architecture 🦉
We explain here how Owl is designed
Warning: these notes are technical by nature, and intended for people working
on Owl (or interested in understanding its design).
## Overview
Roughly speaking, Owl has 5 main parts:
- a virtual dom system (in `src/blockdom`)
- a component system (in `src/component`)
- a template compiler (located in the `src/compiler` folder)
- a small runtime code to tie them together (in `src/app`)
- a reactivity system (in `src/reactivity.ts`)
There are some other files, but the core of Owl can be understood with these
five main parts.
The virtual dom is an optimized virtual dom based on blocks, which supports
multi blocks (for fragments). Everything that owl renders is internally
represented by a virtual node. The job of the virtual dom is to efficiently
represent the current state of the application, and to build an actual DOM
representation when needed, or update the DOM whenever it is needed.
- some other helpers/smaller scale stuff
A rendering occurs in two phases:
- virtual rendering: this generates the virtual dom in memory, asynchronously
- patch: applies a virtual tree to the screen (synchronously)
There are several classes involved in a rendering:
- components
- a scheduler
- fibers: small objects containing some metadata, associated with a rendering of
a specific component
Components are organized in a dynamic component tree, visible in the user
interface. Whenever a rendering is initiated in a component `C`:
- a fiber is created on `C` with the rendering props information
- the virtual rendering phase starts on C (will asynchronously render all the
child components)
- the fiber is added to the scheduler, which will poll continuously, every
animation frame, if the fiber is done
- once it is done, the scheduler will call the task callback, which will apply
the patch (if it was not cancelled in the meantime).
# 🦉 VDom 🦉
Owl is a declarative component system: we declare the structure of the component
tree, and Owl will translate that to a list of imperative operations. This
translation is done by a virtual dom. This is the low level layer of Owl, most
developer will not need to call directly the virtual dom functions.
The main idea behind a virtual dom is to keep a in-memory representation of the
DOM (called a virtual node), and whenever some change is needed, to regenerate
a new representation, compute the difference between the old and the new, then
apply the changes.
`vdom` exports two functions:
- `h`: create a new virtual node
- `patch`: compare two virtual nodes, and apply the difference.
Note: Owl's virtual dom is a fork of [snabbdom](https://github.com/snabbdom/snabbdom).
+255
View File
@@ -0,0 +1,255 @@
# Comparison with Vue/React
OWL, React and Vue have the same main feature: they allow developers to build
declarative user interfaces. To do that, all these frameworks uses a virtual dom. However, there are still obviously many differences.
In this page, we try to highlight some of these differences. Obviously, a lot of
effort was put to be fair. However, if you disagree with some of the points
discussed, feel free to open an issue/submit a PR to correct this text.
## Content
- [Size](#size)
- [Class Based](#class-based)
- [Tooling/Build Step](#toolingbuild-step)
- [Templating](#templating)
- [Asynchronous rendering](#asynchronous-rendering)
- [Reactivity](#reactivity)
- [Hooks](#hooks)
## Size
OWL is intended to be small and to work at a slightly lower level of abstraction
than React and Vue. Also, jQuery is not the same kind of framework, but it is interesting to compare.
| Framework | Size (minified, gzipped) |
| ------------------------ | ------------------------ |
| OWL | 18kb |
| Vue + VueX | 30kb |
| Vue + VueX + Vue Router | 39kb |
| React + ReactDOM + Redux | 40kb |
| jQuery | 30kb |
Note that those comparisons are not entirely fair, because we do not compare
the same exact set of features. For example, VueX and Vue Router support more
advanced use cases.
## Class Based
Both React and Vue moved away from defining components with classes. They prefer
a more functional approach, in particular, with the new `hooks` mechanisms.
This has some advantages and disadvantages. But the end result is that React
and Vue both offers multiple different ways of defining new components. In
contrast, Owl has only one mechanism: class-based components. We believe that Owl
components are fast enough for all our usecases, and making it as simple as
possible for developers is more valuable (for us).
Also, functions or class based components are more than just syntax. Functions
come with a mindset of composition and class are about inheritance. Clearly,
both of these are important mechanisms for reusing code. Also, one does not
exclude the other.
It certainly looks like the world of UI frameworks is moving toward composition,
for many very good reasons. Owl is still good at composition (for example,
Owl supports slots, which is the primary mechanism to make generic reusable
components). But it can also use inheritance (and this is very important since
templates can also be inherited with `xpaths` transformations).
## Tooling/Build step
OWL is designed to be easy to use in a standalone way. For various reasons,
Odoo does not want to rely on standard web tools (such as webpack), and OWL can
be used by simply adding a script tag to a page.
```html
<script src="owl.min.js" />
```
In comparison, React encourages using JSX, which necessitate a build step, and
most Vue applications uses single file components, which also necessitate a build step.
On the flipside, external tooling may make it harder to use in some case, but it
also brings a lot of benefits. And React/Vue have both a large ecosystem.
Note that since Owl is not dependant on any external tool nor libraries, it is
very easy to integrate into any build toolchain. Also, since we cannot rely on
additional tools, we made a lot of effort to make the most of the web platform.
For example, Owl uses the standard `xml` parser that comes with every browser.
Because of that, Owl did not have to write its own template parser. Another
example is the [`xml`](../reference/templates.md#inline-templates) tag helper function, which makes use of
native template literals to allow in a natural way to write `xml` templates
directly in the javascript code. This can be easily integrated with editor
plugins to have autocompletion inside the template.
## Templating
OWL uses its own QWeb engine, which compiles templates on the
frontend, as they are needed. This is extremely convenient for our use case, in
particular because templates are described in XML files, and can be modified by
XPaths. Since Odoo is at its heart a modular application, this is an important
feature for us.
```xml
<div>
<button t-on-click="increment">Click Me! [<t t-esc="state.value"/>]</button>
</div>
```
Vue is actually kind of similar. Its template language is kind of close to QWeb,
with the `v` replaced by the `t`. However, it is also more fully featured. For
example, Vue templates have slots, or event modifiers. A large difference is that
most Vue applications will need to be built ahead of time, to compile the templates
into javascript functions. Note that Vue has a separate build which includes the
template compiler.
In contrast, most React applications do not use a templating language, but write
some JSX code, which is precompiled into plain JavaScript by a build step. This
example is done with the (kind of outdated) React class system:
```jsx
class Clock extends React.Component {
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.props.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
```
This has the advantage of having the full power of Javascript, but is less
structured than a template language. Note that the tooling is quite impressive:
there is a syntax highlighter for jsx here on github!
By comparison, here is the equivalent Owl component, written with the
[`xml`](../reference/templates.md#inline-templates) tag helper:
```js
class Clock extends Component {
static template = xml`
<div>
<h1>Hello, world!</h1>
<h2>It is {props.date.toLocaleTimeString()}.</h2>
</div>
`;
}
```
## Asynchronous Rendering
This is actually a big difference between OWL and React/Vue: components in OWL
are totally asynchronous. They have two asynchronous hooks in their lifecycle:
- `willStart` (before the component starts rendering)
- `willUpdateProps` (before new props are set)
Both these methods can be implemented and return a promise. The rendering will
then wait for these promises to be completed before patching the DOM. This is
useful for some use cases: for example, a component may want to fetch an external
library (a calendar component may need a specialized calendar rendering library),
in its willStart hook.
```javascript
class MyCalendarComponent extends owl.Component {
...
willStart() {
return utils.lazyLoad('static/libs/fullcalendar/fullcalendar.js');
}
...
}
```
This may be dangerous (to stop the rendering waiting for the network), but it is
extremely powerful as well, as demonstrated by the Odoo Web Client.
Lazy loading static libraries can obviously be done with React/Vue, but it is
more convoluted. For example, in Vue, you need to use a dynamic import keyword
that needs to be transpiled at build time in order for the component to be loaded
asynchronously (see [the documentation](https://vuejs.org/v2/guide/components-dynamic-async.html#Async-Components)).
## Reactivity
React has a simple model: whenever the state changes, it is
replaced with a new state (via the `setState` method). Then, the DOM is patched.
This is simple, efficient, and a little bit awkward to write.
Vue is a little bit different: it replace magically the properties in the state
by getters/setters. With that, it can notify components whenever the state that
they read was changed.
Owl is closer to vue: it also tracks magically the state properties, but it does
only increment an internal counter whenever it changes. Note that it is done
with a `Proxy`, which means that it is totally transparent to the developers.
Adding new keys is supported. Once any part of the state has been changed, a
rendering is scheduled in the next microtask tick (promise queue).
## Hooks
[Hooks](https://reactjs.org/docs/hooks-intro.html#motivation) recently took over
the React world. They solve a lot of seemingly unconnected problems: attach
reusable behavior to a component, in a composable way, extract stateful logic
from a component or reuse stateful logic between component, without changing your
component hierarchy.
Here is an example of the React `useState` hook:
```js
import React, { useState } from "react";
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
```
Because of the way React designed the hooks API, they only work for functional
components. But in that case, they really are powerful. Every major React library
is in the process of redesigning their API with hooks (for example,
[Redux](https://react-redux.js.org/next/api/hooks)).
Vue 2 does not have hooks, but the Vue project is working on its next version,
which will feature its new [composition API](https://vue-composition-api-rfc.netlify.com/).
This work is based on the new ideas introduced by React hooks.
From the way React and Vue introduce their hooks, it may look like hooks are not
compatible with class components. However, this is not the case, as shown by
Owl [hooks](../reference/hooks.md). They are inspired by both React and Vue. For example,
the `useState` hook is named after React, but its API is closer to the `reactive`
Vue hook.
Here is what the `Counter` example above look like in Owl:
```js
import { Component, Owl } from "owl";
import { xml } from "owl/tags";
class Example extends Component {
static template = xml`
<div>
<p>You clicked {count.value} times</p>
<button t-on-click="increment">Click me</button>
</div>`;
count = useState({ value: 0 });
increment() {
this.state.value++;
}
}
```
Since the Owl framework had hooks from early in its life, its main APIs
are designed to be interacted with hooks from the start. For example, the
`Context` abstraction.
+98
View File
@@ -0,0 +1,98 @@
# 🦉 Notes On Owl Compiled Templates 🦉
This page will explain what an Owl compiled template look like. This is a
technical document intended for developers interested in understanding how Owl
works internally.
Broadly speaking, Owl compiles templates into a javascript function (a closure)
that returns a function (the "render" function). The point of the closure is to
have a place to store all values specific to the template (in particular, "blocks").
Once a template is compiled, its closure function is called once to get the
render function, and from then on, only the render function is used.
The render function takes some context (and some additional information) and
return a virtual dom representation of the rendered template, as a block tree.
A block tree is a very light weight representation that only contains the dynamic
part of the template, and its structure. It is actually independant of the
static part of the templates (which are contained in the blocks captured by the
closure). This means that the work performed at render time is only to collect
dynamic data, and to describe the block structure of the result.
It looks like this, in pseudo code:
```js
function closure(bdom, helpers) {
// here is some place to put stuff specific to the template, such as
// blocks
...
return function render(context, node, key) {
// only build here all dynamic parts of the template
// build a block tree
return tree;
}
}
```
Now, let us see an example. Consider the following template:
```xml
<div class="some-class">
<div class="blabla">
<span><t t-esc="state.value"/></span>
</div>
<t t-if="state.info">
<p class="info" t-att-class="someAttribute">
<t t-esc="state.info"/>
</p>
</t>
<SomeComponent value="value"/>
</div>
```
If you look carefully, there are 5 dynamic things:
- a text value (the first `t-esc`),
- a sub block (the `t-if`),
- a dynamic attribute (the `t-att-class` attribute),
- another text value (the second `t-esc`),
- and finally, a sub component
Here is the compiled code for this template:
```js
function closure(bdom, helpers) {
let { text, createBlock, list, multi, html, toggler, component, comment } = bdom;
let block1 = createBlock(
`<div class="some-class"><div class="blabla"><span><block-text-0/></span></div><block-child-0/><block-child-1/></div>`
);
let block2 = createBlock(`<p class="info" block-attribute-0="class"><block-text-1/></p>`);
return function render(ctx, node, key = "") {
let b2, b3;
let txt1 = ctx["state"].value;
if (ctx["state"].info) {
let attr1 = ctx["someAttribute"];
let txt2 = ctx["state"].info;
b2 = block2([attr1, txt2]);
}
b3 = component(`SomeComponent`, { value: ctx["value"] }, key + `__1`, node, ctx);
return block1([txt1], [b2, b3]);
};
}
```
The values captured in the closure capture the static part of the template: we
define here two blocks (which contains a template node, that can be deep cloned
whenever a block is mounted). Then the render function only describes the block
tree structure of the result, depending on the context. This means that we
minimize the amount of work done at render time.
Then, when we want to patch the dom, Owl will uses the `patch` function from
blockdom, which then will diff the block tree, and deep clone new blocks whenever
a new block is inserted, keep track of dynamic parts of each block, and update
them accordingly.
With this design, the cost of rendering a template is proportional to the number
of dynamic values, and not to the size of the template.
+180
View File
@@ -0,0 +1,180 @@
# 🦉 Why Owl ? 🦉
The common wisdom is that one should not reinvent the wheel, because that would
waste effort and resources. It is certainly true in many cases. A javascript
framework is a considerable investment, so it is quite logical to ask the question:
why did Odoo decide to make OWL instead of using a standard/well known framework,
such as React or Vue?
As you might expect, the answer to that question is not simple. But most of the
reasons discussed in this page are a consequence from a single fact: Odoo is
extremely modular.
This means, for example, that the core parts of Odoo are not aware, before runtime,
of what files will be loaded/executed, or what will be the state of the UI. Because
of that, Odoo cannot rely on a standard build toolchain. Also, this implies that
the core parts of Odoo need to be extremely generic. In other words, Odoo is not
really an application with a user interface. It is an application which generates
a dynamic user interface. And most frameworks are not up to the task.
Betting on Owl was not an easy choice to make, because there certainly are a lot
of conflicting needs that we want to carefully balance. Choosing anything other
than a well known framework is bound to be controversial. This page will explain
some of the reason why we still believe that building Owl is a worthwile
endeavour.
## Strategy
It is true that we want to keep control of our technology, in the sense that we
do not want to depend on Facebook or Google, or any other large (or small)
company. If they decide to change their license, or to go in a direction that
will not work for us, this may be a problem. This is even more true because
Odoo is not a conventional javascript application, and our needs are probably
quite different as most other applications.
## Class components
It is clear that the biggest frameworks are moving away from class components.
There is an implicit assumption that class components are terrible, and that
functional programming is the way to go. React even goes as far as to say that
classes are confusing for developers.
While there is some truth to that, and to the fact that composition is certainly
a good mechanism for code reuse, we believe that classes and inheritance are
important tools.
Sharing code between generic components with inheritance is the way Odoo built
its web client. And it is clear that inheritance is not the root of all evils.
It is often a perfectly simple and appropriate solution. What matter most is
the architectural decisions.
Also, Odoo has another specific use out of class components: each method of a
class provides an extension point for addons. This may not be a clean architecture
pattern, but it is a pragmatic decision that served Odoo well: classes are
sometimes monkey-patched to add behaviour from the outside. A little bit like
mixins, but from the outside.
Using React or Vue would make it significantly harder to monkey patch components,
because a lot of the state is hidden in their internals.
## Tooling
React or Vue have a huge community, and a lot of effort have been made into their
tooling. This is wonderful, but at the same time, a pretty big issue for Odoo:
since the assets are totally dynamic (and could change whenever the user installs
or removes an addon), we need to have all that kind of tooling on the production
servers. This is certainly not ideal.
Also, this makes it very complicated to setup Vue or React tools: Odoo code is
not a simple file that import other files. It changes all the time, assets
are bundled differently in different contexts. This is the reason why Odoo has
its own module system, which are resolved at runtime, by the browser. The
dynamic nature of Odoo means that we often need to delay work as late as possible
(in other word, we want a JIT user interface!)
Our ideal framework has minimal (mandatory) tooling, which makes it easier to
deploy. Using React without JSX, or Vue without vue file is not very appealing.
At the same time, Owl is designed to solve this issue: it compiles templates
by the browser, it doesn't need much code for that, since we use the XML parser
built into each browser. Owl works with or without any additional tooling. It
can use template strings to write single file components, and is easy to integrate
in any html page, with a simple `<script>` tag.
## Template based
Odoo stores templates as XML documents in a database. This is very powerful, since
this allow the use of xpaths to customize other templates. This is a very
important feature of odoo, and one of the key to Odoo modularity.
Because of that, we still expect to write our templates in an XML document.
Weirdly enough, no major framework uses XML to store templates, even though it
is extremely convenient.
So, using React or Vue means that we need to make a template compiler. For React,
that would be a compiler that would take a QWeb template, and convert it to a
React render function. For Vue, it would convert it to a Vue template. Then
we need to bundle the vue template compiler as well.
Not only this would be complex (compiling a templating language into another is
not an easy task), but it would negatively impact the developer experience as
well. Writing Vue or React components in a QWeb template would certainly be
awkward, and very confusing.
## Developer Experience
This brings us to the following point: developer experience. We see this choice
as an investment for the future, and we want to make onboarding developers as
easy as possible.
While many javascript professionals clearly think that react/vue is not difficult
(which is true to some extent), it is alsy true that many non js specialists are
overwhelmed with the frontend world: functional components, hooks, and many other
fancy words. Also, what is available in the compilation context may be difficult,
there is a lot of black magic going on in pretty much every framework. Vue
somehow join various namespaces into one, under the hood, and add various internal
keys. Svelte transform the code. React require that state transformations are
deep, and not shallow.
Owl is trying very hard to have a simple and familiar API. It uses classes. Its
reactivity system is explicit, not implicit. The scoping rules are obvious. In
case of doubt, we err on the side of not implementing a feature.
It is certainly different from React or Vue, but at the same time, kind of
familiar for experienced developers.
## JIT compilation
There is also a clear trend in the frontend world to compile code
as much as possible ahead of time. Most frameworks will compile templates ahead
of time. And now Svelte is trying to compile the JS code away, so it can remove
itself from the bundle.
This is certainly reasonable for many usecases. However, this is not what Odoo
needs: Odoo will fetch templates from the database and need to compile them only
at the last possible moment, so we can apply all necessary xpaths.
Even more: Odoo needs to be able to generate (and compile) templates at runtime.
Currently, Odoo form views interpret an xml description. But the form view code
then needs to do a lot of complicated operations. With Owl, we will be able to
transform a view description into a QWeb template, then compile that and use it
immediately.
## Reactivity
There are other design choices that we feel are not optimal in other frameworks.
For example, the reactivity system. We like the way Vue did it, but it has a
flaw: it is not really optional. There is actually a way to opt out of the reactivity
system by freezing the state, but then, it is freezed.
And there certainly are situations where we need a state, which is not read-only,
and not observed. For example, imagine a spreadsheet component. It may have a
very large internal state, and it knows exactly when it needs to be rendered
(basically, whenever the user performs some action). Then, observing its state
is a net performance loss, both for the CPU and the memory.
## Concurrency
Many applications are happy to simply display a spinner whenever a new asynchronous
action is performed, but Odoo wants a different user experience: most asynchronous
state changes are not displayed until ready. This is sometimes called a concurrent
mode: the UI is rendered in memory, and displayed only when it is ready (and
only if it has not been cancelled by subsequent user actions).
React has now an experimental concurrent mode, but it was not ready when Owl
started. Vue has not really an equivalent API (suspense is not what we need).
Also, React concurrent mode is complex to use. Concurrency was one of the rare
strong point of the former Odoo js framework (widgets), and we feel that Owl has
now a very strong concurrent mode, which is simple and powerful at the same time.
## Conclusion
This lengthy discussion showed that there are many small and not so small reasons
that current standard frameworks are not tailored to our needs. It is perfectly
fine, because they each chose a different set of tradeoffs.
However, we feel that there is still room in the framework world for something
that is different. For a framework that makes choices compatible with Odoo.
And that is why we built Owl 🦉.
-61
View File
@@ -1,61 +0,0 @@
# Quick Start
To build an application (or a sub-part of an application), we need two things:
- an environment
- a root widget
Here are a few steps that may be useful to get started:
- get the templates
- create a qweb engine, with the templates
- create an environment
- create an instance of the root widget
- mount the root widget to a DOM element
## Simple example
In a oversimplified example, here is what it could look like:
```javascript
const templates = await loadTemplates();
const qweb = new QWeb();
qweb.loadTemplates(templates);
const env = {
qweb: qweb
};
const root = new RootWidget(env, { initialState: 17 });
const target = document.getElementById("app");
root.mount(target);
```
## Managing state
The environment is propagated to each subchildren. So, it is convenient to use
to give a reference to some global object. This is potentially very useful
in a redux-like architecture:
```javascript
...
const store = new Store();
const env = {
qweb: qweb,
store: store,
};
const state = store.getState()
const root = new RootWidget(env, state);
store.on('state_change', nextState => {
root.updateProps(nextState);
});
const target = document.getElementById('app');
root.mount(target);
```
-35
View File
@@ -1,35 +0,0 @@
# QWeb
QWeb is a template specification. The QWeb class in this repository is:
- an implementation of the QWeb specification
- which outputs a virtual dom instead of a string
- and extended with a few extra directives
## QWeb Specification
add here a full description of what QWeb is supposed to be, with some examples
## QWeb Implementation
```javascript
var qweb = new QWeb();
qweb.addTemplate("sometemplate", '<div>hello <t t-esc="name"/></div>');
// result is a vnode which represent <div>hello world</div>
result = qweb.render("sometemplate", { name: "world" });
```
## QWeb extensions
- t-on directive
- t-widget, t-props, t-key
- t-ref
## Note on white spaces
White spaces in a templates are handled in a special way:
- consecutive whitespaces are always condensed to a single whitespace
- if a whitespace-only text node contains a linebreak, it is ignored
- the previous rules do not apply if we are in a `<pre>` tag
+44 -17
View File
@@ -1,22 +1,49 @@
# Odoo Web Lab Documentation
# 🦉 Owl overview 🦉
Currently, this repository contains:
Here is a list of everything exported by the Owl library:
1. **core**
Main entities:
- an implementation/extension of the QWeb template engine that outputs a virtual
dom (using the snabbdom library)
- a Component class, which uses the QWeb engine as its underlying rendering
mechanism. The component class is designed to be declarative, with
asynchronous rendering. Also, it uses snabbdom as the virtual dom library.
- some utility functions/classes
- [`App`](reference/app.md): represent an Owl application (mainly a root component,a set of templates, and a config)
- [`Component`](reference/component.md): the main class to define a concrete Owl component
- [`mount`](reference/app.md#mount-helper): main entry point for most application: mount a component to a target
- [`xml`](reference/templates.md#inline-templates): helper to define an inline template
2. **extras**
- a Store class and a connect function, to help manage the state of an application (like react-redux)
- a Registry: this is a simple key/store mapping
Reactivity
- [Quick Start](quick_start.md)
- [Tutorial](tutorial.md)
- [Component](component.md)
- [QWeb](qweb.md)
- [State Management](state_management.md)
- [`useState`](reference/reactivity.md#usestate): create a reactive object (hook, linked to a specific component)
- [`reactive`](reference/reactivity.md#reactive): create a reactive object (not linked to any component)
- [`markRaw`](reference/reactivity.md#markraw): mark an object or array so that it is ignored by the reactivity system
- [`toRaw`](reference/reactivity.md#toraw): given a reactive objet, return the raw (non reactive) underlying object
Lifecycle hooks:
- [`onWillStart`](reference/component.md#willstart): hook to define asynchronous code that should be executed before component is rendered
- [`onMounted`](reference/component.md#mounted): hook to define code that should be executed when component is mounted
- [`onWillPatch`](reference/component.md#willpatch): hook to define code that should be executed before component is patched
- [`onWillUpdateProps`](reference/component.md#willupdateprops): hook to define code that should be executed before component is updated
- [`onPatched`](reference/component.md#patched): hook to define code that should be executed when component is patched
- [`onWillRender`](reference/component.md#willrender): hook to define code that should be executed before component is rendered
- [`onRendered`](reference/component.md#rendered): hook to define code that should be executed after component is rendered
- [`onWillUnmount`](reference/component.md#willunmount): hook to define code that should be executed before component is unmounted
- [`onWillDestroy`](reference/component.md#willdestroy): hook to define code that should be executed before component is destroyed
- [`onError`](reference/component.md#onerror): hook to define a Owl error handler
Other hooks:
- [`useComponent`](reference/hooks.md#usecomponent): return a reference to the current component (useful to create derived hooks)
- [`useEffect`](reference/hooks.md#useeffect): define an effect with its dependencies
- [`useEnv`](reference/hooks.md#useenv): return a reference to the current env
- [`useExternalListener`](reference/hooks.md#useexternallistener): add a listener outside of a component DOM
- [`useRef`](reference/hooks.md#useref): get an object representing a reference (`t-ref`)
- [`useChildSubEnv`](reference/hooks.md#usesubenv-and-usechildsubenv): extend the current env with additional information (for child components)
- [`useSubEnv`](reference/hooks.md#usesubenv-and-usechildsubenv): extend the current env with additional information (for current component and child components)
Utility/helpers:
- [`EventBus`](reference/utils.md#eventbus): a simple event bus
- [`loadFile`](reference/utils.md#loadfile): an helper to load a file from the server
- [`markup`](reference/templates.md#outputting-data): utility function to define strings that represent html (should not be escaped)
- [`status`](reference/component.md#status-helper): utility function to get the status of a component (new, mounted or destroyed)
- [`validate`](reference/utils.md#validate): validates if an object satisfies a specified schema
- [`whenReady`](reference/utils.md#whenready): utility function to execute code when DOM is ready
+125
View File
@@ -0,0 +1,125 @@
# 🦉 App 🦉
## Content
- [Overview](#overview)
- [API](#api)
- [Configuration](#configuration)
- [`mount` helper](#mount-helper)
- [Loading templates](#loading-templates)
## Overview
Every Owl application has a root element, a set of templates, an environment and
possibly a few other settings. The `App` class is a simple class that represents
all of these elements. Here is an example:
```js
const {Component, App } = owl;
class MyComponent extends Component { ... }
const app = new App(MyComponent, { props: {...}, templates: "..."});
app.mount(document.body);
```
The basic workflow is: create an `App` instance configured with the root
component, the templates, and possibly other settings. Then, we mount that
instance somewhere in the DOM.
## API
- **`constructor(Root[, config])`**: first argument should be a component class (not
an instance), and the optional second argument is a configuration object (see below).
- **`mount(target, options)`**: first argument is an html element, and the optional
second argument is an object with mounting options (see below). Mount the app
to a target in the DOM. Note that this is an asynchronous operation: the `mount`
method returns a promise that resolves to the component instance whenever it
is complete.
The `option` object is an object with the following keys:
- **`position (string)`**: either `first-child` or `last-child`. This option determines
the position of the application in the target: either first or last child.
- **`destroy()`**: destroys the application
## Configuration
The `config` object is an object with some of the following keys:
- **`env (object)`**: if given, this will be the shared `env` given to each component
- **`props (object)`**: the props given to the root component
- **`dev (boolean, default=false)`**: if `true`, the application is rendered in
[`dev` mode](#dev-mode);
- **`test (boolean, default=false)`**: `test` mode is the same as `dev` mode, except
that Owl will not log a message to warn that Owl is in `dev` mode.
- **`translatableAttributes (string[])`**: a list of additional attributes that should
be translated (see [translations](translations.md))
- **`translateFn (function)`**: a function that will be called by owl to translate
templates (see [translations](translations.md))
- **`templates (string | xml document)`**: all the templates that will be used by
the components created by the application.
- **`getTemplate ((s: string) => Element | Function | string | void)`**: a function that will be called by owl when it
needs a template. If undefined is returned, owl looks into the app templates.
- **`warnIfNoStaticProps (boolean, default=false)`**: if true, Owl will log a warning
whenever it encounters a component that does not provide a [static props description](props.md#props-validation).
## `mount` helper
Note that there is a `mount` helper to do that in just a line:
```js
const { mount, Component } = owl;
class MyComponent extends Component {
...
}
mount(MyComponent, document.body, { props: {...}, templates: "..."});
```
Here is the `mount` function signature:
**`mount(Component, target, config)`** with the following arguments:
- **`Component`**: a component class (Root component of the app)
- **`target`**: an html element, where the component will be mounted as last child
- **`config (optional)`**: a config object (the same as the App config object)
Most of the time, the `mount` helper is more convenient, but whenever one needs
a reference to the actual Owl App, then using the `App` class directly is
possible.
## Loading templates
Most applications will need to load templates whenever they start. Here is
what it could look like in practice:
```js
// in the main js file:
const { loadFile, mount } = owl;
// async, so we can use async/await
(async function setup() {
const templates = await loadFile(`/some/endpoint/that/return/templates`);
const env = {
_t: someTranslateFn,
templates,
// possibly other stuff
};
mount(Root, document.body, { env });
})();
```
## Dev mode
Dev mode activates some additional checks and developer amenities:
- [Props validation](./props.md#props-validation) is performed
- [t-foreach](./templates.md#loops) loops check for key unicity
- Lifecycle hooks are wrapped to report their errors in a more developer-friendly way
- onWillStart and onWillUpdateProps will emit a warning in the console when they
take longer than 3 seconds in an effort to ease debugging the presence of deadlocks
+456
View File
@@ -0,0 +1,456 @@
# 🦉 Owl Component 🦉
## Content
- [Overview](#overview)
- [Properties and methods](#properties-and-methods)
- [Static Properties](#static-properties)
- [Lifecycle](#lifecycle)
- [`setup`](#setup)
- [`willStart`](#willstart)
- [`willRender`](#willrender)
- [`rendered`](#rendered)
- [`mounted`](#mounted)
- [`willUpdateProps`](#willupdateprops)
- [`willPatch`](#willpatch)
- [`patched`](#patched)
- [`willUnmount`](#willunmount)
- [`willDestroy`](#willdestroy)
- [`onError`](#onerror)
- [Sub components](#sub-components)
- [Dynamic Sub components](#dynamic-sub-components)
- [`status` helper](#status-helper)
## Overview
An Owl component is a small class which represents some part of the user interface.
It is part of a component tree, and has an [environment](environment.md) (`env`),
which is propagated from a parent to its children.
OWL components are defined by subclassing the `Component` class. For example,
here is how a `Counter` component could be implemented:
```javascript
const { Component, xml, useState } = owl;
class Counter extends Component {
static template = xml`
<button t-on-click="increment">
Click Me! [<t t-esc="state.value"/>]
</button>`;
state = useState({ value: 0 });
increment() {
this.state.value++;
}
}
```
In this example, we use the `xml` helper to define inline templates, and the
`useState` hook, which returns a reactive version of its argument (see the page
on reactivity).
## Properties and methods
The `Component` class has a very small API.
- **`env (object)`**: the component [environment](environment.md)
- **`props (object)`**: this is an object containing all the [props](props.md) given by
the parent to a child component
Note that `props` are owned by the parent, not by the component.
As such, it should not ever be modified by the component (otherwise you risk
unintended effects, since the parent may not be aware of the change)!!
The `props` can be modified dynamically by the parent. In that case, the
component will go through the following lifecycle methods: `willUpdateProps`,
`willPatch` and `patched`.
* **`render(deep[=false])`**: calling this method directly will cause a rerender. Note
that with the reactivity system, this should be rare to have to do it manually.
Also, the rendering operation is asynchronous, so the DOM will only be updated
slightly later (at the next animation frame, if no component delays the
rendering)
By default, the render initiated by this method will stop at each child
component if their props are (shallow) equal. To force a render to update
all child components, one can use the optional `deep` argument. Note that the
value of the `deep` argument needs to be a boolean, not a truthy value.
## Static Properties
- **`template (string)`**: this is the name of the template that
will render the component. Note that there is a helper `xml` to
make it easy to define an inline template.
* **`components (object, optional)`**: if given, this is an object that contains
the classes of any sub components needed by the template.
```js
class ParentComponent extends owl.Component {
static components = { SubComponent };
}
```
* **`props (object, optional)`**: if given, this is an object that describes the
type and shape of the (actual) props given to the component. If Owl mode is
`dev`, this will be used to validate the props each time the component is
created/updated. See [Props Validation](props.md#props-validation) for more information.
```js
class Counter extends owl.Component {
static props = {
initialValue: Number,
optional: true,
};
}
```
- **`defaultProps (object, optional)`**: if given, this object define default
values for (top-level) props. Whenever `props` are given to the object, they
will be altered to add default value (if missing). Note that it does not
change the initial object, a new object will be created instead. See
[default props](props.md#default-props) for more information
```js
class Counter extends owl.Component {
static defaultProps = {
initialValue: 0,
};
}
```
## Lifecycle
A solid and robust component system needs a complete lifecycle system to help
developers write components. Here is a complete description of the lifecycle of
a Owl component:
| Method | Hook | Description |
| --------------------------------------- | ------------------- | ---------------------------------------------------------------------- |
| **[setup](#setup)** | none | setup |
| **[willStart](#willstart)** | `onWillStart` | async, before first rendering |
| **[willRender](#willrender)** | `onWillRender` | just before component is rendered |
| **[rendered](#rendered)** | `onRendered` | just after component is rendered |
| **[mounted](#mounted)** | `onMounted` | just after component is rendered and added to the DOM |
| **[willUpdateProps](#willupdateprops)** | `onWillUpdateProps` | async, before props update |
| **[willPatch](#willpatch)** | `onWillPatch` | just before the DOM is patched |
| **[patched](#patched)** | `onPatched` | just after the DOM is patched |
| **[willUnmount](#willunmount)** | `onWillUnmount` | just before removing component from DOM |
| **[willDestroy](#willdestroy)** | `onWillDestroy` | just before component is destroyed |
| **[error](#onerror)** | `onError` | catch and handle errors (see [error handling page](error_handling.md)) |
### `setup`
_setup_ is run just after the component is constructed. It is a lifecycle method,
very similar to the _constructor_, except that it does not receive any argument.
It is the proper place to call hook functions. Note that one of the main reason to
have the `setup` hook in the component lifecycle is to make it possible to
monkey patch it. It is a common need in the Odoo ecosystem.
```javascript
setup() {
useSetupAutofocus();
}
```
### `willStart`
`willStart` is an asynchronous hook that can be implemented to
perform some (most of the time asynchronous) action before the initial rendering of a component.
It will be called exactly once before the initial rendering. It is useful
in some cases, for example, to load external assets (such as a JS library)
before the component is rendered. Another use case is to load data from a server.
The `onWillStart` hook is used to register a function that will be executed at
this moment:
```javascript
setup() {
onWillStart(async () => {
this.data = await this.loadData()
});
}
```
At this point, the component is not yet rendered. Note that slow `willStart`
code will slow down the rendering of the user interface. Therefore, some care
should be made to make this method as fast as possible.
Note that if there are more than one `onWillStart` registered callback, then they
will all be run in parallel.
### `willRender`
It is uncommon but it may happen that one need to execute code just before a
component is rendered (more precisely, when its compiled template function is executed).
To do that, one can use the `onWillRender` hook:
```javascript
setup() {
onWillRender(() => {
// do something
});
}
```
`willRender` hooks are called just before rendering templates, parent first,
then children.
### `rendered`
It is uncommon but it may happen that one need to execute code just after a
component is rendered (more precisely, when its compiled template function is executed).
To do that, one can use the `onRendered` hook:
```javascript
setup() {
onRendered(() => {
// do something
});
}
```
`rendered` hooks are called just after rendering templates, parent first,
then children. Note that at this moment, the actual DOM may not exist yet (if
it is the first rendering), or is not updated yet. This will be dom in the next
animation frame as soon as all the components are ready.
### `mounted`
The `mounted` hook is called each time a component is attached to the
DOM, after the initial rendering. At this point, the component is considered
_active_. This is a good place to add some listeners, or to interact with the
DOM, if the component needs to perform some measure for example.
It is the opposite of `willUnmount`. If a component has been mounted, it will
always be unmounted at some point in the future.
The mounted method will be called recursively on each of its children. First,
children, then parents.
It is allowed (but not encouraged) to modify the state in the `mounted` hook.
Doing so will cause a rerender, which will not be perceptible by the user, but
will slightly slow down the component.
The `onMounted` hook is used to register a function that will be executed at
this moment:
```javascript
setup() {
onMounted(() => {
// do something here
});
}
```
### `willUpdateProps`
The `willUpdateProps` is an asynchronous hook, called just before new props
are set. This is useful if the component needs to perform an asynchronous task,
depending on the props (for example, assuming that the props are
some record Id, fetching the record data).
The `onWillUpdateProps` hook is used to register a function that will be executed at
this moment:
```javascript
setup() {
onWillUpdateProps(nextProps => {
return this.loadData({id: nextProps.id});
});
}
```
Notice that it receives the next props for the component.
This hook is not called during the first render (but `willStart` is called
and performs a similar job). Also, as most of the hooks, it is called in the
usual order: parents first, then children.
### `willPatch`
The willPatch hook is called just before the DOM patching process starts.
It is not called on the initial render. This is useful to read
information from the DOM. For example, the current position of the
scrollbar.
Note that modifying the state is not allowed here. This method is called just
before an actual DOM patch, and is only intended to be used to save some local
DOM state. Also, it will not be called if the component is not in the DOM.
The `onWillPatch` hook is used to register a function that will be executed at
this moment:
```javascript
setup() {
onWillPatch(() => {
this.scrollState = this.getScrollSTate();
});
}
```
The `willPatch` is called in the usual parent->children order.
### `patched`
This hook is called whenever a component did actually update its DOM (most
likely via a change in its state/props or environment).
This method is not called on the initial render. It is useful to interact
with the DOM (for example, through an external library) whenever the
component was patched. Note that this hook will not be called if the component is
not in the DOM.
The `onPatched` hook is used to register a function that will be executed at
this moment:
```javascript
setup() {
onPatched(() => {
this.scrollState = this.getScrollSTate();
});
}
```
Updating the component state in this hook is possible, but not encouraged.
One needs to be careful, because updates here will create an additional rendering, which in
turn will cause other calls to the `patched` method. So, we need to be particularly
careful at avoiding endless cycles.
Like `mounted`, the `patched` hook is called in the order: children first, then
parent.
### `willUnmount`
`willUnmount` is a hook that is called each time just before a component is
unmounted from the DOM. This is a good place to remove listeners, for example.
The `onWillUnmount` hook is used to register a function that will be executed at
this moment:
```javascript
setup() {
onMounted(() => {
// add some listener
});
onWillUnmount(() => {
// remove listener
});
}
```
This is the opposite method of `mounted`. Note that if a component is destroyed
before being mounted, the `willUnmount` method may not be called.
Parent `willUnmount` hooks will be called before children.
### `willDestroy`
Sometimes, components need to do some action in the `setup` and clean it up when
they are inactive. However, the `willUnmount` hook is not appropriate for the
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 `onWillDestroy` hook is used to register a function that will be executed at
this moment:
```javascript
setup() {
onWillDestroy(() => {
// do some cleanup
});
}
```
The `willDestroy` hooks are first called on children, then on parents.
### `onError`
Sadly, it may happen that components crashes at runtime. This is an unfortunate
reality, and this is why Owl needs to provide a way to handle these errors.
The `onError` hook is useful when we need to intercept and properly react
to errors that occur in some sub components. See the page on
[error handling](error_handling.md) for more detail.
```javascript
setup() {
onError(() => {
// do something
});
}
```
## Sub components
It is convenient to define a component using other (sub) components. This is
called composition, and is very powerful in practice. To do that in Owl, one
can just use a tag starting with a capital letter in its template, and register
the sub component class in its static `components` object:
```js
class Child extends Component {
static template = xml`<div>child component <t t-esc="props.value"/></div>`;
}
class Parent extends Component {
static template = xml`
<div>
<Child value="1"/>
<Child value="2"/>
</div>`;
static components = { Child };
}
```
This example also shows how one can pass information from the parent component
to the child component, as props. See the [props section](props.md)
for more information.
## Dynamic sub components
It is not common, but sometimes we need a dynamic component name. In this case,
the `t-component` directive can also be used to accept dynamic values. This should
be an expression that evaluates to a component class. For example:
```js
class A extends Component {
static template = xml`<div>child a</div>`;
}
class B extends Component {
static template = xml`<span>child b</span>`;
}
class Parent extends Component {
static template = xml`<t t-component="myComponent"/>`;
state = useState({ child: "a" });
get myComponent() {
return this.state.child === "a" ? A : B;
}
}
```
## `status` helper
It is sometimes convenient to have a way to find out in which state a component
is currently. To do that, one can use the `status` helper:
```js
const { status } = owl;
// assume component is an instance of a Component
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
```
+163
View File
@@ -0,0 +1,163 @@
# 🦉 Concurrency Model 🦉
## Content
- [Overview](#overview)
- [Rendering Components](#rendering-components)
- [Semantics](#semantics)
- [Asynchronous Rendering](#asynchronous-rendering)
## Overview
Owl was designed from the very beginning with asynchronous components. This comes
from the `willStart` and the `willUpdateProps` lifecycle hooks. With these
asynchronous hooks, it is possible to build complex highly concurrent applications.
Owl concurrent mode has several benefits: it makes it possible to delay the
rendering until some asynchronous operation is complete, it makes it possible
to lazy load libraries, while keeping the previous screen completely functional.
It is also good for performance reasons: Owl uses it to only apply the result of
many different renderings only once in an animation frame. Owl can cancel
a rendering that is no longer relevant, restart it, reuse it in some cases.
But even though using concurrency is quite simple (and is the default behaviour),
asynchrony is difficult, because it introduces an additional dimension that
vastly increase the complexity of an application. This section will explain
how Owl manages this complexity, how concurrent rendering works in a general way.
## Rendering Components
The word _rendering_ is a little vague, so, let us explain more precisely the
process by which Owl components are displayed on a screen.
When a component is mounted or updated, a new rendering is started. It has
two phases: _virtual rendering_ and _patching_.
### Virtual rendering
This phase represent the process of rendering a template, in memory, which creates
a virtual representation of the desired component html). The output of this phase is a
virtual DOM.
It is asynchronous: each subcomponents needs to either be created (so, `willStart`
will need to be called), or updated (which is done with the `willUpdateProps`
method). This is completely a recursive process: a component is the root of a
component tree, and each sub component needs to be (virtually) rendered.
### Patching
Once a rendering is complete, it will be applied on the next animation frame.
This is done synchronously: the whole component tree is patched to the real
DOM.
## Semantics
We give here an informal description of the way components are created/updated
in an application. Here, ordered lists describe actions that are executed
sequentially, bullet lists describe actions that are executed in parallel.
**Scenario 1: initial rendering** Imagine we want to render the following component tree:
```
A
/ \
B C
/ \
D E
```
Here is what happen whenever we mount the root
component (with some code like `app.mount(document.body)`).
1. `willStart` is called on `A`
2. when it is done, template `A` is rendered.
- component `B` is created
1. `willStart` is called on `B`
2. template `B` is rendered
- component `C` is created
1. `willStart` is called on `C`
2. template `C` is rendered
- component `D` is created
1. `willStart` is called on `D`
2. template `D` is rendered
- component `E` is created
1. `willStart` is called on `E`
2. template `E` is rendered
3. each components are patched into a detached DOM element, in the following order:
`E`, `D`, `C`, `B`, `A`. (so the actual full DOM tree is created
in one pass)
4. the component `A` root element is actually appended to `document.body`
5. The method `mounted` is called recursively on all components in the following
order: `E`, `D`, `C`, `B`, `A`.
**Scenario 2: updating a component**. Now, let's assume that the user clicked on some
button in `C`, and this results in a state update, which is supposed to:
- update `D`,
- remove `E`,
- add new component `F`.
So, the component tree should look like this:
```
A
/ \
B C
/ \
D F
```
Here is what Owl will do:
1. because of a state change, the method `render` is called on `C`
2. template `C` is rendered again
- component `D` is updated:
1. hook `willUpdateProps` is called on `D` (async)
2. template `D` is rerendered
- component `F` is created:
1. hook `willStart` is called on `F` (async)
2. template `F` is rendered
3. `willPatch` hooks are called recursively on components `C`, `D` (not on `F`,
because it is not mounted yet)
4. components `F`, `D` are patched in that order
5. component `C` is patched, which will cause recursively:
1. `willUnmount` hook on `E`
2. destruction of `E`,
6. `mounted` hook is called on `F`, `patched` hooks are called on `D`, `C`
Tags are very small helpers to make it easy to write inline templates. There is
only one currently available tag: `xml`.
### Asynchronous Rendering
Working with asynchronous code always adds a lot of complexity to a system. Whenever
different parts of a system are active at the same time, one needs to think
carefully about all possible interactions. Clearly, this is also true for Owl
components.
There are two different common problems with Owl asynchronous rendering model:
- any component can delay the rendering (initial and subsequent) of the whole
application
- for a given component, there are two independant situations that will trigger an
asynchronous rerendering: a change in the state, or a change in the props.
These changes may be done at different times, and Owl has no way of knowing
how to reconcile the resulting renderings.
Here are a few tips on how to work with asynchronous components:
1. Minimize the use of asynchronous components!
2. Lazy loading external libraries is a good use case for async rendering. This
is mostly fine, because we can assume that it will only takes a fraction of a
second, and only once.
+76
View File
@@ -0,0 +1,76 @@
# 🦉 Environment 🦉
## Content
- [Overview](#overview)
- [Setting an Environment](#setting-an-environment)
- [Using a sub environment](#using-a-sub-environment)
- [Content of an Environment](#content-of-an-environment)
## Overview
An environment is a shared object given to all components in a tree. It is not
used by Owl itself, but it is useful for application developers to provide a
simple communication channel between components (in addition to the props).
The `env` given to the [`App`](app.md) is assigned to the `env` component
property.
```
Root
/ \
A B
```
Also, the `env` object is frozen when the application is started. This is done
to ensure a simpler mental model of what's happening in runtime. Note that it
is only shallowly frozen, so sub objects can be modified.
## Setting an environment
The correct way to customize an environment is to simply give it to the `App`,
whenever it is created.
```js
const env = {
_t: myTranslateFunction,
user: {...},
services: {
...
},
};
new App(Root, { env }).mount(document.body);
// or alternatively
mount(App, document.body, { env });
```
## Using a sub environment
It is sometimes useful to add one (or more) specific keys to the environment,
from the perspective of a specific component and its children. In that case, the
solution presented above will not work, since it sets the global environment.
There are two hooks for this situation: [`useSubEnv` and `useChildSubEnv`](hooks.md#usesubenv-and-usechildsubenv).
```js
class SomeComponent extends Component {
setup() {
useSubEnv({ myKey: someValue }); // myKey is now available for all child components
}
}
```
## Content of an Environment
The `env` object content is totally up to the application developer. However,
some good use cases for additional keys in the environment are:
- some configuration keys,
- session information,
- generic services (such as doing rpcs).
- other utility functions that one want to inject, such as a translation function.
Doing it this way means that components are easily testable: we can simply
create a test environment with mock services.
+75
View File
@@ -0,0 +1,75 @@
# 🦉 Error Handling 🦉
## Content
- [Overview](#overview)
- [Managing Errors](#managing-errors)
- [Example](#example)
## Overview
By default, whenever an error occurs in the rendering of an Owl application, we
destroy the whole application. Otherwise, we cannot offer any guarantee on the
state of the resulting component tree. It might be hopelessly corrupted, but
without any user-visible feedback.
Clearly, it is usually a little bit extreme to destroy the application. This
is why we need a mechanism to handle rendering errors (and errors coming
from lifecycle hooks): the `onError` hook.
The main idea is that the `onError` hook register a function that will be called
with the error. This function need to handle the situation, most of the time by
updating some state and rerendering itself, so the application can return to a
normal state.
## Managing Errors
Whenever the `onError` lifecycle hook is used, all errors coming from
sub components rendering and/or lifecycle method calls will be caught and given
to the `onError` method. This allows us to properly handle the error, and to
not break the application.
There are important things to know:
- If an error that occured in the internal rendering cycle is not caught, then
Owl will destroy the full application. This is done on purpose, because Owl
cannot guarantee that the state is not corrupted from this point on.
- errors coming from event handlers are NOT managed by `onError` or any other
owl mechanism. This is up to the application developer to properly recover
from an error
- if an error handler is unable to properly handle an error, it can just rethrow
an error, and Owl will try looking for another error handler up the component
tree.
## Example
For example, here is how we could implement a generic component `ErrorBoundary`
that render its content, and a fallback if an error happened.
```js
class ErrorBoundary extends Component {
static template = xml`
<t t-if="state.error" t-slot="fallback">An error occurred</t>
<t t-else="" t-slot="default"/>`;
setup() {
this.state = useState({ error: false });
onError(() => (this.state.error = true));
}
}
```
Using the `ErrorBoundary` is then simple simple:
```xml
<ErrorBoundary>
<SomeOtherComponent/>
<t t-set-slot="fallback">Some specific error message</t>
</ErrorBoundary>
```
Note that we need to be careful here: the fallback UI should not throw any
error, otherwise we risk going into an infinite loop (also, see the page on
[slots](slots.md) for more information on the `t-slot` directive).
+119
View File
@@ -0,0 +1,119 @@
# 🦉 Event Handling 🦉
## Content
- [Event Handling](#event-handling)
- [Modifiers](#modifiers)
- [Synthetic Events](#synthetic-events)
- [On Components](#on-components)
## Event Handling
In a component's template, it is useful to be able to register handlers on DOM
elements to some specific events. This is what makes a template _alive_. This
is done with the `t-on` directive. For example:
```xml
<button t-on-click="someMethod">Do something</button>
```
This will be roughly translated in javascript like this:
```js
button.addEventListener("click", component.someMethod.bind(component));
```
The suffix (`click` in this example) is simply the name of the actual DOM
event. The value of the `t-on` expression should be a valid javascript expression
that evaluates to a function in the context of the current component. So, one
can get a reference to the event, or pass some additional arguments. For example,
all the following expressions are valid:
```xml
<button t-on-click="someMethod">Do something</button>
<button t-on-click="() => this.increment(3)">Add 3</button>
<button t-on-click="ev => this.doStuff(ev, 'value')">Do something</button>
```
Notice the use of the `this` keyword in the lambda function: this is the
correct way to call a method on the component in a lambda function.
One could use the following expression:
```xml
<button t-on-click="() => increment(3)">Add 3</button>
```
But then, the increment function may be unbound (unless the component binds it
in its setup function, for example).
## Modifiers
In order to remove the DOM event details from the event handlers (like calls to
`event.preventDefault`) and let them focus on data logic, _modifiers_ can be
specified as additional suffixes of the `t-on` directive.
| Modifier | Description |
| ------------ | ------------------------------------------------------------------------------------------------------------------------ |
| `.stop` | calls `event.stopPropagation()` before calling the method |
| `.prevent` | calls `event.preventDefault()` before calling the method |
| `.self` | calls the method only if the `event.target` is the element itself |
| `.capture` | bind the event handler in [capture](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) mode. |
| `.synthetic` | define a synthetic event handler (see below) |
```xml
<button t-on-click.stop="someMethod">Do something</button>
```
Note that modifiers can be combined (ex: `t-on-click.stop.prevent`), and that
the order may matter. For instance `t-on-click.prevent.self` will prevent all
clicks while `t-on-click.self.prevent` will only prevent clicks on the element
itself.
Finally, empty handlers are tolerated as they could be defined only to apply
modifiers. For example,
```xml
<button t-on-click.stop="">Do something</button>
```
This will simply stop the propagation of the event.
## Synthetic Events
In some cases, attaching an event handler for each element of large lists has
a non trivial cost. Owl provides a way to efficiently improve the performance:
with synthetic event, it actually adds only one handler on the document body,
and will properly call the handler, just as expected.
The only difference with regular events is that the event is caught at the document
body, so it cannot be stopped before it actually gets there. Since it may be
surprising in some cases, it is not enabled by default.
To enable it, one can just use the `.synthetic` suffix:
```xml
<div>
<t t-foreach="largeList" t-as="elem" t-key="elem.id">
<button t-on-click.synthetic="doSomething" ...>
<!-- some content -->
</button>
</t>
</div>
```
## On Components
The `t-on` directive also works on a child component:
```xml
<div>
in some template
<Child t-on-click="dosomething"/>
</div>
```
This will catch all click events on any html element contained in the `Child`
sub component. Note that if the child component is reduced to one (or more) text
nodes, then clicking on it will not call the handler, since the event will be
dispatched by the browser on the parent element (a `div` in this case).
+325
View File
@@ -0,0 +1,325 @@
# 🦉 Hooks 🦉
## Content
- [Overview](#overview)
- [The Hook Rule](#the-hook-rule)
- [Lifecycle hooks](#lifecycle-hooks)
- [Other hooks](#other-hooks)
- [`useState`](#usestate)
- [`useRef`](#useref)
- [`useSubEnv` and `useChildSubEnv`](#usesubenv-and-usechildsubenv)
- [`useExternalListener`](#useexternallistener)
- [`useComponent`](#usecomponent)
- [`useEnv`](#useenv)
- [`useEffect`](#useeffect)
- [Example: Mouse Position](#example-mouse-position)
## Overview
Hooks were popularised by React as a way to solve the following issues:
- help reusing stateful logic between components
- help organizing code by feature in complex components
- use state in functional components, without writing a class.
Owl hooks serve the same purpose, except that they work for class components
(note: React hooks do not work on class components, and maybe because of that,
there seems to be the misconception that hooks are in opposition to class. This
is clearly not true, as shown by Owl hooks).
Hooks work beautifully with Owl components: they solve the problems mentioned
above, and in particular, they are the perfect way to make your component
reactive.
## The Hook Rule
There is only one rule: every hook for a component has to be called in the _setup_ method, or in class fields:
```js
// ok
class SomeComponent extends Component {
state = useState({ value: 0 });
}
// also ok
class SomeComponent extends Component {
setup() {
this.state = useState({ value: 0 });
}
}
// not ok: this is executed after the constructor is called
class SomeComponent extends Component {
async willStart() {
this.state = useState({ value: 0 });
}
}
```
## Lifecycle Hooks
All lifecycle hooks are documented in detail in their specific [section](component.md#lifecycle).
| Hook | Description |
| ----------------------------------------------------- | ---------------------------------------------------------------------- |
| **[onWillStart](component.md#willstart)** | async, before first rendering |
| **[onWillRender](component.md#willrender)** | just before component is rendered |
| **[onRendered](component.md#rendered)** | just after component is rendered |
| **[onMounted](component.md#mounted)** | just after component is rendered and added to the DOM |
| **[onWillUpdateProps](component.md#willupdateprops)** | async, before props update |
| **[onWillPatch](component.md#willpatch)** | just before the DOM is patched |
| **[onPatched](component.md#patched)** | just after the DOM is patched |
| **[onWillUnmount](component.md#willunmount)** | just before removing component from DOM |
| **[onWillDestroy](component.md#willdestroy)** | just before component is destroyed |
| **[onError](component.md#onerror)** | catch and handle errors (see [error handling page](error_handling.md)) |
## Other Hooks
### `useState`
The `useState` hook is certainly the most important hook for Owl components:
this is what allows a component to be reactive, to react to state change.
The `useState` hook has to be given an object or an array, and will return
an observed version of it (using a `Proxy`).
```javascript
const { useState, Component } = owl;
class Counter extends Component {
static template = xml`
<button t-on-click="increment">
Click Me! [<t t-esc="state.value"/>]
</button>`;
state = useState({ value: 0 });
increment() {
this.state.value++;
}
}
```
It is important to remember that `useState` only works with objects or arrays. It
is necessary, since Owl needs to react to a change in state.
### `useRef`
The `useRef` hook is useful when we need a way to interact with some inside part
of a component, rendered by Owl. It only work on a html element tagged by the
`t-ref` directive:
```xml
<div>
<input t-ref="someInput"/>
<span>hello</span>
</div>
```
In this example, the component will be able to access the `input` with the `useRef` hook:
```js
class Parent extends Component {
inputRef = useRef("someInput");
someMethod() {
// here, if component is mounted, refs are active:
// - this.inputRef.el is the input HTMLElement
}
}
```
As shown by the example above, the actual HTMLElement instance is accessed with
the `el` key.
The `t-ref` directive also accepts dynamic values with string interpolation
(like the [`t-attf-`](templates.md#dynamic-attributes) and
`t-component` directives). For example,
```xml
<div t-ref="div_{{someCondition ? '1' : '2'}}"/>
```
Here, the references need to be set like this:
```js
this.ref1 = useRef("div_1");
this.ref2 = useRef("div_2");
```
References are only guaranteed to be active while the parent component is mounted.
If this is not the case, accessing `el` on it will return `null`.
### `useSubEnv` and `useChildSubEnv`
The environment is sometimes useful to share some common information between
all components. But sometimes, we want to _scope_ that knowledge to a subtree.
For example, if we have a form view component, maybe we would like to make some
`model` object available to all sub components, but not to the whole application.
This is where the `useChildSubEnv` hook may be useful: it lets a component add some
information to the environment in a way that only its children
can access it:
```js
class FormComponent extends Component {
setup() {
const model = makeModel();
// model will be available on this.env for this component and all children
useSubEnv({ model });
// someKey will be available on this.env for all children
useChildSubEnv({ someKey: "value" });
}
}
```
The `useSubEnv` and `useChildSubEnv` hooks take one argument: an object which
contains some key/value that will be added to the current environment. These hooks
will create a new env object with the new information:
- `useSubEnv` will assign this new `env` to itself and to all children components
- `useChildSubEnv` will only assign this new `env` to all children components.
As usual in Owl, [environments](environment.md) created with these two hooks are
frozen, to prevent unwanted modifications.
Note that both these hooks can be called an arbitrary number of times. The `env`
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. 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, { capture: true });
```
### `useComponent`
The `useComponent` hook is useful as a building block for some customized hooks,
that may need a reference to the component calling them.
```js
function useSomething() {
const component = useComponent();
// now, component is bound to the instance of the current component
}
```
### `useEnv`
The `useEnv` hook is useful as a building block for some customized hooks,
that may need a reference to the env of the component calling them.
```js
function useSomething() {
const env = useEnv();
// now, env is bound to the env of the current component
}
```
### `useEffect`
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 (only if some dependencies have changed).
It has almost the same API as the React `useEffect` hook, except that the dependencies
are defined by a function instead of just the dependencies.
The `useEffect` hook takes two function: the effect function and the dependency
function. The effect function perform some task and return (optionally) a cleanup
function. The dependency function returns a list of dependencies, these dependencies
are passed as parameters in the effect function . If any of these
dependencies changes, then the current effect will be cleaned up and reexecuted.
Here is an example without any dependencies:
```js
useEffect(
() => {
window.addEventListener("mousemove", someHandler);
return () => window.removeEventListener("mousemove", someHandler);
},
() => []
);
```
In the example above, the dependency list is empty, so the effect is only cleaned
up when the component is unmounted.
If the dependency function is skipped, then the effect will be cleaned up and
rerun at every patch.
Here is another example, of how one could implement a `useAutofocus` hook with
the `useEffect` hook:
```js
function useAutofocus(name) {
let ref = useRef(name);
useEffect(
(el) => el && el.focus(),
() => [ref.el]
);
}
```
This hook takes the name of a valid `t-ref` directive, which should be present
in the template. It then checks whenever the component is mounted or patched if
the reference is not valid, and in this case, it will focus the node element.
This hook can be used like this:
```js
class SomeComponent extends Component {
static template = xml`
<div>
<input />
<input t-ref="myinput"/>
</div>`;
setup() {
useAutofocus("myinput");
}
}
```
## Example: mouse position
Here is the classical example of a non trivial hook to track the mouse position.
```js
const { useState, onWillDestroy, Component } = owl;
// We define here a custom behaviour: this hook tracks the state of the mouse
// position
function useMouse() {
const position = useState({ x: 0, y: 0 });
function update(e) {
position.x = e.clientX;
position.y = e.clientY;
}
window.addEventListener("mousemove", update);
onWillDestroy(() => {
window.removeEventListener("mousemove", update);
});
return position;
}
// Main root component
class Root extends Component {
static template = xml`<div>Mouse: <t t-esc="mouse.x"/>, <t t-esc="mouse.y"/></div>`;
// this hooks is bound to the 'mouse' property.
mouse = useMouse();
}
```
Note that we use the prefix `use` for hooks, just like in React. This is just
a convention.
+92
View File
@@ -0,0 +1,92 @@
# 🦉 Form Input Bindings 🦉
It is very common to need to be able to read the value out of an html `input` (or
`textarea`, or `select`) in order to use it (note: it does not need to be in a
form!). A possible way to do this is to do it by hand:
```js
class Form extends owl.Component {
state = useState({ text: "" });
_updateInputValue(event) {
this.state.text = event.target.value;
}
}
```
```xml
<div>
<input t-on-input="_updateInputValue" />
<span t-esc="state.text" />
</div>
```
This works. However, this requires a little bit of _plumbing_ code. Also, the
plumbing code is slightly different if you need to interact with a checkbox,
or with radio buttons, or with select tags.
To help with this situation, Owl has a builtin directive `t-model`: its value
should be an observed value in the component (usually `state.someValue`). With
the `t-model` directive, we can write a shorter code, equivalent to the previous
example:
```js
class Form extends owl.Component {
state = { text: "" };
}
```
```xml
<div>
<input t-model="state.text" />
<span t-esc="state.text" />
</div>
```
The `t-model` directive works with `<input>`, `<input type="checkbox">`,
`<input type="radio">`, `<textarea>` and `<select>`:
```xml
<div>
<div>Text in an input: <input t-model="state.someVal"/></div>
<div>Textarea: <textarea t-model="state.otherVal"/></div>
<div>Boolean value: <input type="checkbox" t-model="state.someFlag"/></div>
<div>Selection:
<select t-model="state.color">
<option value="">Select a color</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
</select>
</div>
<div>
Selection with radio buttons:
<span>
<input type="radio" name="color" id="red" value="red" t-model="state.color"/>
<label for="red">Red</label>
</span>
<span>
<input type="radio" name="color" id="blue" value="blue" t-model="state.color" />
<label for="blue">Blue</label>
</span>
</div>
</div>
```
Like event handling, the `t-model` directive accepts the following modifiers:
| Modifier | Description |
| --------- | -------------------------------------------------------------------- |
| `.lazy` | update the value on the `change` event (default is on `input` event) |
| `.number` | try to parse the value to a number (using `parseFloat`) |
| `.trim` | trim the resulting value |
For example:
```xml
<input t-model.lazy="state.someVal" />
```
These modifiers can be combined. For instance, `t-model.lazy.number` will only
update a number whenever the change is done.
Note: the online playground has an example to show how it works.
+17
View File
@@ -0,0 +1,17 @@
# 🦉 Portal 🦉
It is sometimes useful to be able to render some content outside the boundaries
of a component. To do that, Owl provides a special directive: `t-portal`:
```js
class SomeComponent extends Component {
static template = xml`
<div>this is inside the component</div>
<div t-portal="'body'">and this is outside</div>
`;
}
```
The `t-portal` directive takes a valid css selector as argument. The content of
the portalled template will be mounted at the corresponding location. Note that
Owl need to insert an empty text node at the location of the portalled content.
+30
View File
@@ -0,0 +1,30 @@
# 🦉 Precompiling templates 🦉
Owl is designed to be used by the Odoo javascript framework. Since Odoo handles
its assets in its own non standard way, it was decided/assumed that Owl would
compile templates at runtime.
However, in some cases, it is not optimal, or even worse, not possible to do that.
For example, browser extensions do not allow javascript code to create a new
function (using the `new Function(...)` syntax).
Therefore, in these cases, it is required to compile templates ahead of time. It
is possible to do that in Owl, but the tooling is still rough. For now, the
process is the following:
1. write your templates in xml files (with a `t-name` directive to declare the name
of the template)
2. Compile them in a `templates.js` file
3. get the `owl.iife.runtime.js` file (which is a owl build without the compiler)
4. bundle `owl.iife.runtime.js` and `template.js` with your assets (owl needs to
be positioned before the templates)
Here is a more detailed explanation on how to compile xml files into a js file:
1. clone the owl repository locally
2. `npm install` to install all the required tooling
3. `npm run build:runtime` to build the `owl.iife.runtime.js` file
4. `npm run build:compiler` to build the template compiler
5. `npm run compile_templates -- path/to/your/templates` will scan your target
folder, find all xml files, get all templates, compile them, and generate a
`templates.js` file.
+320
View File
@@ -0,0 +1,320 @@
# 🦉 Props 🦉
## Content
- [Overview](#overview)
- [Definition](#definition)
- [Props comparison](#props-comparison)
- [Binding function props](#binding-function-props)
- [Dynamic Props](#dynamic-props)
- [Default Props](#default-props)
- [Props validation](#props-validation)
- [Good Practices](#good-practices)
## Overview
In Owl, `props` (short for _properties_) is an object which contains every piece
of data given to a component by its parent.
```js
class Child extends Component {
static template = xml`<div><t t-esc="props.a"/><t t-esc="props.b"/></div>`;
}
class Parent extends Component {
static template = xml`<div><Child a="state.a" b="'string'"/></div>`;
static components = { Child };
state = useState({ a: "fromparent" });
}
```
In this example, the `Child` component receives two props from its parent: `a`
and `b`. They are collected into a `props` object by Owl, with each value being
evaluated in the context of the parent. So, `props.a` is equal to `'fromparent'` and
`props.b` is equal to `'string'`.
Note that `props` is an object that only makes sense from the perspective of the
child component.
## Definition
The `props` object is made of every attributes defined on the template, with the
following exceptions:
- every attribute starting with `t-` are not props (they are QWeb directives),
In the following example:
```xml
<div>
<ComponentA a="state.a" b="'string'"/>
<ComponentB t-if="state.flag" model="model"/>
</div>
```
the `props` object contains the following keys:
- for `ComponentA`: `a` and `b`,
- for `ComponentB`: `model`,
## Props comparison
Whenever Owl encounters a subcomponent in a template, it performs a shallow
comparison of all props. If they are all referentially equal, then the subcomponent
will not even be updated. Otherwise, if at least one props has changed, then
Owl will update it.
However, in some cases, we know that two values are different, but they have the
same effect, and should not be considered different by Owl. For example, anonymous
functions in a template are always different, but most of them should not be
considered different:
```xml
<t t-foreach="todos" t-as="todo" t-key="todo.id">
<Todo todo="todo" onDelete="() => deleteTodo(todo.id)" />
</t>
```
In that case, one can use the `.alike` suffix:
```xml
<t t-foreach="todos" t-as="todo" t-key="todo.id">
<Todo todo="todo" onDelete.alike="() => deleteTodo(todo.id)" />
</t>
```
This tells Owl that this specific prop should always be considered equivalent
(or, in other words, should be removed from the list of comparable props).
Note that even if most anonymous functions should probably be considered `alike`,
it is not necessarily true in all cases. It depends on what values are captured
by the anonymous function. The following example shows a case where it is probably
wrong to use `.alike`.
```xml
<t t-foreach="todos" t-as="todo" t-key="todo.id">
<!-- Probably wrong! todo.isCompleted may change -->
<Todo todo="todo" toggle.alike="() => toggleTodo(todo.isCompleted)" />
</t>
```
## Binding function props
It is common to have the need to pass a callback as a prop. Since Owl components
are class based, the callback frequently needs to be bound to its owner component.
So, one can do this:
```js
class SomeComponent extends Component {
static template = xml`
<div>
<Child callback="doSomething"/>
</div>`;
setup() {
this.doSomething = this.doSomething.bind(this);
}
doSomething() {
// ...
}
}
```
However, this is such a common use case that Owl provides a special suffix to do
just that: `.bind`. This looks like this:
```js
class SomeComponent extends Component {
static template = xml`
<div>
<Child callback.bind="doSomething"/>
</div>`;
doSomething() {
// ...
}
}
```
The `.bind` suffix also implies `.alike`, so these props will not cause additional
renderings.
## Dynamic Props
The `t-props` directive can be used to specify totally dynamic props:
```xml
<div t-name="ParentComponent">
<Child t-props="some.obj"/>
</div>
```
```js
class ParentComponent {
static components = { Child };
some = { obj: { a: 1, b: 2 } };
}
```
## Default Props
If the static `defaultProps` property is defined, it will be used to complete
props received by the parent, if missing.
```js
class Counter extends owl.Component {
static defaultProps = {
initialValue: 0,
};
...
}
```
In the example above, the `initialValue` props is now by default set to 0.
## Props Validation
As an application becomes complex, it may be quite unsafe to define props in an informal way. This leads to two issues:
- hard to tell how a component should be used, by looking at its code.
- unsafe, it is easy to send wrong props into a component, either by refactoring a component, or one of its parents.
A props type system solves both issues, by describing the types and shapes
of the props. Here is how it works in Owl:
- `props` key is a static key (so, different from `this.props` in a component instance)
- it is optional: it is ok for a component to not define a `props` key.
- props are validated whenever a component is created/updated
- props are only validated in `dev` mode (see [how to configure an app](app.md#configuration))
- if a key does not match the description, an error is thrown
- it validates keys defined in (static) `props`. Additional keys given by the
parent will cause an error (unless the special prop `*` is present).
- it is an object or a list of strings
- a list of strings is a simplified props definition, which only lists the name
of the props. Also, if the name ends with `?`, it is considered optional.
- all props are by default required, unless they are defined with `optional: true`
(in that case, it is only done if there is a value)
- valid types are: `Number, String, Boolean, Object, Array, Date, Function`, and all
constructor functions (so, if you have a `Person` class, it can be used as a type)
- arrays are homogeneous (all elements have the same type/shape)
For each key, a `prop` definition is either a boolean, a constructor, a list of constructors, or an object:
- a boolean: indicate that the props exists, and is mandatory.
- a constructor: this should describe the type, for example: `id: Number` describe
the props `id` as a number
- an object describing a value as type. This is done by using the `value` key. For example, `{value: false}` specifies that the corresponding value should be equal to false.
- a list of constructors. In that case, this means that we allow more than one
type. For example, `id: [Number, String]` means that `id` can be either a string
or a number.
- an object. This makes it possible to have more expressive definition. The following sub keys are then allowed (but not mandatory):
- `type`: the main type of the prop being validated
- `element`: if the type was `Array`, then the `element` key describes the type of each element in the array. If it is not set, then we only validate the array, not its elements,
- `shape`: if the type was `Object`, then the `shape` key describes the interface of the object. If it is not set, then we only validate the object, not its elements,
- `values`: if the type was `Object`, then the `values` key describes the interface of values in the object, this allows validating objects that are used as mappings, where keys are not known in advance but the shape of the values is.
- `validate`: this is a function which should return a boolean to determine if
the value is valid or not. Useful for custom validation logic.
- `optional`: if true, the prop is not mandatory
There is a special `*` prop that means that additional prop are allowed. This is
sometimes useful for generic components that will propagate some or all their
props to their child components.
Note that default values cannot be defined for a mandatory props. Doing so will
result in a prop validation error.
Examples:
```js
class ComponentA extends owl.Component {
static props = ['id', 'url'];
...
}
class ComponentB extends owl.Component {
static props = {
count: {type: Number},
messages: {
type: Array,
element: {type: Object, shape: {id: Boolean, text: String }
},
date: Date,
combinedVal: [Number, Boolean],
optionalProp: { type: Number, optional: true }
};
...
}
```
```js
// only the existence of those 3 keys is documented
static props = ['message', 'id', 'date'];
```
```js
// only the existence of those 3 keys is documented. any other key is allowed.
static props = ['message', 'id', 'date', '*'];
```
```js
// size is optional
static props = ['message', 'size?'];
```
```js
static props = {
messageIds: {type: Array, element: Number}, // list of number
otherArr: {type: Array}, // just array. no validation is made on sub elements
otherArr2: Array, // same as otherArr
someObj: {type: Object}, // just an object, no internal validation
someObj2: {
type: Object,
shape: {
id: Number,
name: {type: String, optional: true},
url: String
]}, // object, with keys id (number), name (string, optional) and url (string)
someObj3: {
type: Object,
values: { type: Array, element: String },
}, // object with arbitary keys where values are arrays of strings
someFlag: Boolean, // a boolean, mandatory (even if `false`)
someVal: [Boolean, Date], // either a boolean or a date
otherValue: true, // indicates that it is a prop
kindofsmallnumber: {
type: Number,
validate: n => (0 <= n && n <= 10)
},
size: {
validate: e => ["small", "medium", "large"].includes(e)
},
someId: [Number, {value: false}], // either a number or false
};
```
Note: the props validation code is done by using the [validate utility function](utils.md#validate).
## Good Practices
A `props` object is a collection of values that come from the parent. As such,
they are owned by the parent, and should never be modified by the child:
```js
class MyComponent extends Component {
constructor(parent, props) {
super(parent, props);
props.a.b = 43; // Never do that!!!
}
}
```
Props should be considered readonly, from the perspective of the child component.
If there is a need to modify them, then the request to update them should be
sent to the parent (for example, with an event).
Any value can go in a props. Strings, objects, classes, or even callbacks could
be given to a child component (but then, in the case of callbacks, communicating
with events seems more appropriate).
+395
View File
@@ -0,0 +1,395 @@
# 🦉 Reactivity 🦉
## Content
- [Introduction](#introduction)
- [`useState`](#usestate)
- [`reactive`](#reactive)
- [`Escape hatches`](#escape-hatches)
- [`Advanced usage`](#advanced-usage)
## Introduction
Reactivity is a big topic in javascript frameworks. The goal is to provide a
simple way to manipulate state, in such a way that the interface updates automatically
according to state changes, and to do so in a performant manner.
To this end, Owl provides a proxy-based reactivity system, based on the `reactive` primitive.
The `reactive` function takes an object as a first argument, and an optional callback as its second
argument, it returns a proxy of the object. This proxy tracks what properties are read
through the proxy, and calls the provided callback whenever one of these properties is changed
through any reactive version of the same object. It does so in depth, by returning reactive versions
of the subobjects when they are read.
## `useState`
While the `reactive` primitive is very powerful, its usage in components follow a very standard pattern:
components want to be rerendered when part of the state which they depend on for rendering changes. To
this end, owl provides a standard hook: `useState`. To put it simply, this hook simply calls reactive
with the provided object, and the current component's render function as its callback. This will cause
it to rerender whenever any part of the state object that has been read by this component is modified.
Here is a simple example of how `useState` can be used:
```js
class Counter extends Component {
static template = xml`
<div t-on-click="() => this.state.value++">
<t t-esc="state.value"/>
</div>`;
setup() {
this.state = useState({ value: 0 });
}
}
```
This component reads `state.value` when it renders, subscribing it to changes to that key. Whenever
the value changes, Owl will update the component. Note that there is nothing special about the
`state` property, you can name your state variables whatever you want, and you can have multiple of
them on the same component if it makes sense to do so. This also allows `useState` to be used in custom
hooks that may require state that is specific to that hook.
### Reactive props
Since version 2.0, Owl renders are no longer "deep" by default: a component is only rerendered by its
parent if its props have changed (using a simple equality test). What if the contents of a props have
changed in a deeper property? If that prop is reactive, owl will rerender the child components that
need to be updated automatically, and only those components, it does so by reobserving reactive
objects passed as props to components. Consider the following example:
```js
class Counter extends Component {
static template = xml`
<div t-on-click="() => props.state.value++">
<t t-esc="props.state.value"/>
</div>`;
}
class Parent extends Component {
static template = xml`
<Counter state="this.state"/>
<button t-on-click="() => this.state.value = 0">Reset counter</button>
<button t-on-click="() => this.state.test++" t-esc="this.state.test"/>`;
setup() {
this.state = useState({ value: 0, test: 1 });
}
}
```
When clicking on the counter button, only the Counter rerenders, because the Parent has never read
the "value" key in the state. When clicking on the "Reset Counter" button, the same thing happens:
only the Counter component rerenders. What matters is not _where_ the state is updated, but which
parts of the state are updated, and which components depend on them. This is achieved by Owl by
automatically calling `useState` on reactive objects passed as props to a child component.
When clicking on the last button, the parent is rerendered, but the child does not care about the
`test` key: it has not read it. The props that we give it (`this.state`) have also not changed,
as such, the parent updates but the child doesn't.
For most day-to-day operations, `useState` should cover all of your needs. If
you are curious about more advanced use cases and technical details, read on.
### Debugging subscriptions
Owl provides a way to show which reactive objects and keys a component is subscribed to: you can
look at `component.__owl__.subscriptions`. Note that this is on the internal `__owl__` field, and
should not be used in any type of production code as the name of this property or any of its properties
or methods are subject to change at any point, even in stable versions of Owl, and may become available
only in debug mode in the future.
## `reactive`
The `reactive` function is the basic reactivity primitive. It takes an object
or an array as first argument, and optionally, a function as the second argument.
The function is called whenever any tracked value is updated.
```js
const obj = reactive({ a: 1 }, () => console.log("changed"));
obj.a = 2; // does not log anything: the 'a' key has not been read yet
console.log(obj.a); // logs 2 and reads the 'a' key => it is now tracked
obj.a = 3; // logs 'changed' because we updated a tracked value
```
An important property of reactive objects is that they can be reobserved: this
will create an independent proxy that tracks another set of keys:
```js
const obj1 = reactive({ a: 1, b: 2 }, () => console.log("observer 1"));
const obj2 = reactive(obj1, () => console.log("observer 2"));
console.log(obj1.a); // logs 1, and reads the 'a' key => it is now tracked by observer 1
console.log(obj2.b); // logs 2, and 'b' is now tracked by observer 2
obj2.a = 3; // only logs 'observer1', because observer2 does not track a
obj2.b = 3; // only logs 'observer2', because observer1 does not track b
console.log(obj2.a, obj1.b); // logs 3 and 3, while the object is observed independently, it is still a single object
```
Because `useState` returns a normal reactive object, it is possible to call `reactive` on the result
of a `useState` to observe changes to that object while outside the context of a component, or to
call `useState` on reactive objects created outside of components. In those cases, one needs to be
careful with regards to the lifetime of those reactive objects, as holding references to these
objects may prevent garbage collection of the component and its data even if Owl has destroyed it.
### Subscriptions are ephemereal
Subscription to state changes are ephemereal, whenever an observer is notified that a state object
has changed, all of its subscriptions are cleared, meaning that if it still cares about it, it
should read the properties it cares about again. For example:
```js
const obj = reactive({ a: 1 }, () => console.log("observer called"));
console.log(obj.a); // logs 1, and reads the 'a' key => it is now tracked by the observer
obj.a = 3; // logs 'observer1' and clears the subscriptions of the observer
obj.a = 4; // doesn't log anything, the key is no longer observed
```
This may seem counter-intuitive, but it makes perfect sense in the context of components:
```js
class DoubleCounter extends Component {
static template = xml`
<t t-esc="state.selected + ': ' + state[state.selected].value"/>
<button t-on-click="() => this.state.count1++">increment count 1</button>
<button t-on-click="() => this.state.count2++">increment count 2</button>
<button t-on-click="changeCounter">Switch counter</button>
`;
setup() {
this.state = useState({ selected: "count1", count1: 0, count2: 0 });
}
changeCounter() {
this.state.selected = this.state.selected === "count1" ? "count2" : "count1";
}
}
```
In this component, if we increment the value of the second counter, the component will not rerender,
which makes sense as rerendering will have no effect, as the second counter is not displayed. If we
toggle the component to display the second counter, we now no longer want the component to rerender
when the value of the first counter changes, and this is what happens: a component only rerenders
when there are changes to pieces of state that have been read during or after the previous render.
If a piece of state has not been read in the last render, we know that its value won't influence the
rendered output, and so we can ignore it.
### reactive `Map` and `Set`
The reactivity system has special support built-in for the standard container types `Map` and `Set`.
They behave like one would expect: reading a key subscribes the observer to that key, adding or
removing an item to them notifies observers that have used any of the iterators on that reactive
object, such as `.entries()` or `.keys()`, likewise with clearing them.
## Escape hatches
Sometimes, it is desirable to bypass the reactivity system. Creating proxies when interacting with
reactive objects is expensive, and while on the whole, the performance benefit that we get by
rerendering only the parts of the interface that need it outweighs that cost, in some cases, we want
to be able to opt out of creating them in the first place. This is the purpose of `markRaw`:
### `markRaw`
Marks an object so that it is ignored by the reactivity system, meaning that if this object is ever
part of a of a reactive object, it will be returned as is, and no keys in that object will be
observed.
```js
const someObject = markRaw({ b: 1 });
const state = useState({
a: 1,
obj: someObject,
});
console.log(state.obj.b); // attempt to subscribe to the "b" key in someObject
state.obj.b = 2; // No rerender will occur here
console.log(someObject === state.obj); // true
```
This is useful in some rare cases. One such example would be if you want to use an array of objects
that is potentially large to render a list, but those objects are known to be immutable:
```js
this.items = useState([
{ label: "some text", value: 42 },
// ... 1000 total objects
]);
```
in the template:
```xml
<t t-foreach="items" t-as="item" t-key="item.label" t-esc="item.label + item.value"/>
```
Here, on every render, we go and read one thousand keys from a reactive object, which causes
one thousand reactive objects to be created. If we know that the content of these objects
cannot change, this is wasted work. If instead all of these objects are marked as raw, we avoid
all of this work while keeping the ability to lean on the reactivity to track the presence and
identity of these objects:
```js
this.items = useState([
markRaw({ label: "some text", value: 42 }),
// ... 1000 total objects
]);
```
However, use this function with caution: this is an escape hatch from the reactivity
system, and as such, using it may cause subtle and unintended issues! For example:
```js
// This will cause a rerender
this.items.push(markRaw({ label: "another label", value: 1337 }));
// THIS WILL NOT CAUSE A RENDER!
this.items[17].value = 3;
// The UI is now desynced from component's state until the next render caused by something else
```
In short: only use `markRaw` if your application is slowing down noticeably and profiling reveals
that a lot of time is spent creating useless reactive objects.
### `toRaw`
While `markRaw` marks an object so that it is never made reactive, `toRaw` takes an object and
returns the underlying non-reactive object. It can be useful in some niche cases. In particular,
because the reactivity system returns a proxy, the returned object does not compare equal to the
original object:
```js
const obj = {};
const reactiveObj = reactive(obj);
console.log(obj === reactiveObj); // false
console.log(obj === toRaw(reactiveObj)); // true
```
It can also be useful during debugging, as unfolding proxies recursively in debuggers can be confusing.
## Advanced usage
The following is a collection of small snippets that leverage the reactivity system in
"non-standard" ways to help you understand its power and where using it might make your code simpler.
### Notification manager
Showing notifications is a pretty common need in web applications, you may want to show a
notification from any other component within the application, and the notifications should stack on
top of one another regardless of which component spawned them, here is how we can leverage the
reactivity to accomplish this:
```js
let notificationId = 1;
const notifications = reactive({});
class NotificationContainer extends Component {
static template = xml`
<t t-foreach="notifications" t-as="notification" t-key="notification_key" t-esc="notification"/>
`;
setup() {
this.notifications = useState(notifications);
}
}
export function addNotification(label) {
const id = notificationId++;
notifications[id] = label;
return () => {
delete notifications[id];
};
}
```
Here, the `notifications` variable is a reactive object. Notice how we didn't give `reactive` a
callback: this is because in this case, all we care about is that adding or removing notifications
in the `addNotification` function goes through the reactivity system. The `NotificationContainer`
component reobserves this object with `useState`, and is updated whenever notifications are
added or removed.
### Store
Centralizing application state is a pretty common want/need in web applications. Because of the way
the reactivity system works, you can treat any reactive object as a store, and if you call `useState`
on it, components automatically observe only the part of the store that they're interested in:
```js
export const store = reactive({
list: [],
add(item) {
this.list.push(item);
},
});
export function useStore() {
return useState(store);
}
```
In any component:
```js
import { useStore } from "./store";
class List extends Component {
static template = xml`
<t t-foreach="store.list" t-as="item" t-key="item" t-esc="item"/>
`;
setup() {
this.store = useStore();
}
}
```
Anywhere in the application:
```js
import { store } from "./store";
// Will cause any instance of the List component in the app to update
store.add("New list item!");
```
Notice how we can make objects with methods into reactive objects, and when these methods are used
to mutate the store contents, it works as expected. And while stores are generally one-off objects,
it is entirely possible to make class instances reactive:
```js
class Store {
list = [];
add(item) {
this.list.push(item);
}
}
// Essentially equivalent to the previous code
export const store = reactive(new Store());
```
Which can be useful to unit test the class separately.
### Local storage synchronization
Sometimes, you want to persist some state accross reloads, you can do this by storing it in the
`localStorage`, but what if you want to update the `localStorage` item every time the state changes,
so that you don't have to manually synchronize the states? Well, you can use the reactivity system
to write a custom hook that will do that for you:
```js
function useStoredState(key, initialState) {
const state = JSON.parse(localStorage.getItem(key)) || initialState;
const store = (obj) => localStorage.setItem(key, JSON.stringify(obj));
const reactiveState = reactive(state, () => store(reactiveState));
store(reactiveState);
return useState(state);
}
class MyComponent extends Component {
setup() {
this.state = useStoredState("MyComponent.state", { value: 1 });
}
}
```
One important thing to notice is that both times we call `store`, we call it with `reactiveState`,
not `state`: we need `store` to read the keys through a reactive object for it to correctly
subscribe to state changes. Notice also that we call `store` the first time by hand, as otherwise it
will not be subscribed to anything, and no amount of change in the object will cause the reactive
callback to be invoked.
+37
View File
@@ -0,0 +1,37 @@
# 🦉 References 🦉
The `useRef` hook is useful when we need a way to interact with some inside part
of a component, rendered by Owl. It can work either on a DOM node, or on a component,
targeted by the `t-ref` directive. See the [hooks section](hooks.md#useref) for
more detail.
As a short example, here is how we could set the focus on a given input:
```xml
<div>
<input t-ref="input"/>
<button t-on-click="focusInput">Click</button>
</div>
```
```js
import { useRef } from "owl/hooks";
class SomeComponent extends Component {
inputRef = useRef("input");
focusInput() {
this.inputRef.el.focus();
}
}
```
Be aware that the `el` property will only be set when the target of the `t-ref`
directive is mounted in the DOM. Otherwise, it will be set to `null`.
The `useRef` hook cannot be used to get a reference to an instance of a sub
component.
Note that this example uses the suffix `ref` to name the reference. This
is not mandatory, but it is a useful convention, so we do not forget that it is
a reference object.
+260
View File
@@ -0,0 +1,260 @@
# 🦉 Slots 🦉
## Content
- [Overview](#overview)
- [Named slots](#named-slots)
- [Rendering Context](#rendering-context)
- [Default Slot](#default-slot)
- [Default Content](#default-content)
- [Dynamic slots](#dynamic-slots)
- [Slots and props](#slots-and-props)
- [Slot params](#slot-params)
- [Slot scopes](#slot-scopes)
## Overview
Owl is a template based component system. There is therefore a need to be able
to make generic components. For example, imagine a generic `Navbar`
component, which displays a navbar, but with some customizable content. Since
the specific content is only known to the user of the `Navbar`, it would be nice
to specify it in the template where `Navbar` is used:
```xml
<div>
<Navbar>
<span>Hello Owl</span>
</Navbar>
</div>
```
This is exactly the way slots work! In the example above, the user of the `Navbar`
component specify some content (here, in the default slot). The `Navbar`
component can insert that content in its own template at the appropriate location.
An important information to notice is that the content of the slot is rendered in
the parent context, not in the navbar. As such, it can access values and methods
from the parent component.
Here is how the `Navbar` component could be defined, with the `t-slot` directive:
```xml
<div class="navbar">
<t t-slot="default"/>
<ul>
<!-- rest of the navbar here -->
</ul>
</div>
```
## Named slots
Default slots are very useful, but sometimes, we may need more than one slot.
This is what named slots are for! For example, suppose we implement a component
`InfoBox` that display a title and some specific content. Its template could look
like this:
```xml
<div class="info-box">
<div class="info-box-title">
<t t-slot="title"/>
<span class="info-box-close-button" t-on-click="close">X</span>
</div>
<div class="info-box-content">
<t t-slot="content"/>
</div>
</div>
```
And one could use it with the `t-set-slot` directive:
```xml
<InfoBox>
<t t-set-slot="title">
Specific Title. It could be html also.
</t>
<t t-set-slot="content">
<!-- some template here, with html, events, whatever -->
</t>
</InfoBox>
```
## Rendering context
The content of the slots is actually rendered with the rendering context corresponding
to where it was defined, not where it is positioned. This allows the user to define
event handlers that will be bound to the correct component (usually, the
grandparent of the slot content).
## Default Slot
All elements inside the component which are not a named slot will be treated as
part of the content of the `default` slot. For example:
```xml
<div t-name="Parent">
<Child>
<span>some content</span>
</Child>
</div>
<div t-name="Child">
<t t-slot="default"/>
</div>
```
One can mix default slot and named slots:
```xml
<div>
<Child>
default content
<t t-set-slot="footer">
content for footer slot here
</t>
</Child>
</div>
```
## Default content
Slots can define a default content, in case the parent did not define them:
```xml
<div t-name="Parent">
<Child/>
</div>
<span t-name="Child">
<t t-slot="default">default content</t>
</span>
<!-- will be rendered as: <div><span>default content</span></div> -->
```
## Dynamic Slots
The `t-slot` directive is actually able to use any expressions, using string
interplolation:
```xml
<t t-slot="{{current}}" />
```
This will evaluate the `current` expression, and insert the corresponding slot
at the place of the `t-slot` directive.
## Slots and props
In a sense, slots are almost the same as a prop: they define some information
to pass to the child component. To make it possible to use it, and to pass it
down to sub component, Owl actually define a special prop `slots` that contains
all slot information given to the component. It looks like this:
```js
{ slotName_1: slotInfo_1, ..., slotName_m: slotInfo_m }
```
So, a component can pass its slots to a subcomponent like this:
```xml
<Child slots="props.slots"/>
```
## Slot params
For advanced usecases, it may be necessary to pass additional information to a
slot. This can be done by providing extra key/value pairs to the `t-set-slot`
directive. Then, the generic component can read them in its prop `slots`.
For example, here is how a Notebook component could be implemented (a component
with multiple page, and a tab bar, which only render the current active page,
and each page has a title).
```js
class Notebook extends Component {
static template = xml`
<div class="notebook">
<div class="tabs">
<t t-foreach="tabNames" t-as="tab" t-key="tab_index">
<span t-att-class="{active:tab_index === activeTab}" t-on-click="() => state.activeTab=tab_index">
<t t-esc="props.slots[tab].title"/>
</span>
</t>
</div>
<div class="page">
<t t-slot="{{currentSlot}}"/>
</div>
</div>`;
setup() {
this.state = useState({ activeTab: 0 });
this.tabNames = Object.keys(this.props.slots);
}
get currentSlot() {
return this.tabNames[this.state.activeTab];
}
}
```
Notice how one can read the `title` value for each slots. Here is how one could
use this `Notebook` component:
```xml
<Notebook>
<t t-set-slot="page1" title="'Page 1'">
<div>this is in the page 1</div>
</t>
<t t-set-slot="page2" title="'Page 2'" hidden="somevalue">
<div>this is in the page 2</div>
</t>
</Notebook>
```
Slot params works like normal props, so one can use the `.bind` suffix to
bind a function if needed.
## Slot scopes
For other kinds of advanced use cases, the content of a slot may depends on some
information specific to the generic component. This is the opposite of the slot
params.
To solve this kind of problems, one can use the `t-slot-scope` directive along
with the `t-set-slot`. This defines the name of a variable that can access
everything given by the child component:
```xml
<MyComponent>
<t t-set-slot="foo" t-slot-scope="scope">
content
<t t-esc="scope.bool"/>
<t t-esc="scope.num"/>
</t>
</MyComponent>
```
And the child component that includes the slot can provide values like this:
```xml
<t t-slot="foo" bool="other_var" num="5">
```
or this:
```xml
<t t-slot="foo" t-props="someObject">
```
In the case of the default slot, you may declare the slot scope directly on the
component itself:
```xml
<MyComponent t-slot-scope="scope">
content
<t t-esc="scope.bool"/>
<t t-esc="scope.num"/>
</MyComponent>
```
Slot values works like normal props, so one can use the `.bind` suffix to
bind a function if needed.
+703
View File
@@ -0,0 +1,703 @@
# 🦉 Templates 🦉
## Content
- [Overview](#overview)
- [Directives](#directives)
- [QWeb Template reference](#qweb-template-reference)
- [White Spaces](#white-spaces)
- [Expression Evaluation](#expression-evaluation)
- [Static html Nodes](#static-html-nodes)
- [Outputting Data](#outputting-data)
- [Setting Variables](#setting-variables)
- [Conditionals](#conditionals)
- [Dynamic Attributes](#dynamic-attributes)
- [Dynamic Class Attribute](#dynamic-class-attribute)
- [Dynamic Tag Names](#dynamic-tag-names)
- [Loops](#loops)
- [Sub Templates](#sub-templates)
- [Dynamic Sub Templates](#dynamic-sub-templates)
- [Debugging](#debugging)
- [Fragments](#fragments)
- [Inline templates](#inline-templates)
- [Rendering svg](#rendering-svg)
- [Restrictions](#restrictions)
## Overview
Owl templates are describe using the [QWeb](https://www.odoo.com/documentation/13.0/reference/qweb.html) specification. It is based on the XML format, and used
mostly to generate HTML. In OWL, QWeb templates are compiled into functions that
generate a virtual dom representation of the HTML. Also, since Owl is a live
component system, there are additional directives specific to Owl (such as `t-on`).
```xml
<div>
<span t-if="somecondition">Some string</span>
<ul t-else="">
<li t-foreach="messages" t-as="message">
<t t-esc="message"/>
</li>
</ul>
</div>
```
Template directives are specified as XML attributes prefixed with `t-`, for
instance `t-if` for conditionals, with elements and other attributes being
rendered directly.
To avoid element rendering, a placeholder element `<t>` is also available, which
executes its directive but doesnt generate any output in and of itself.
We present in this section the templating language, including its Owl specific
extensions.
## Directives
For reference, here is a list of all standard QWeb directives:
| Name | Description |
| ------------------------------ | --------------------------------------------------------------- |
| `t-esc` | [Outputting safely a value](#outputting-data) |
| `t-out` | [Outputting value, possibly without escaping](#outputting-data) |
| `t-set`, `t-value` | [Setting variables](#setting-variables) |
| `t-if`, `t-elif`, `t-else`, | [conditionally rendering](#conditionals) |
| `t-foreach`, `t-as` | [Loops](#loops) |
| `t-att`, `t-attf-*`, `t-att-*` | [Dynamic attributes](#dynamic-attributes) |
| `t-call` | [Rendering sub templates](#sub-templates) |
| `t-debug`, `t-log` | [Debugging](#debugging) |
| `t-translation` | [Disabling the translation of a node](translations.md) |
The component system in Owl requires additional directives, to express various
needs. Here is a list of all Owl specific directives:
| Name | Description |
| -------------------------------------- | --------------------------------------------------------------- |
| `t-component`, `t-props` | [Defining a sub component](component.md#sub-components) |
| `t-ref` | [Setting a reference to a dom node or a sub component](refs.md) |
| `t-key` | [Defining a key (to help virtual dom reconciliation)](#loops) |
| `t-on-*` | [Event handling](event_handling.md) |
| `t-portal` | [Portal](portal.md) |
| `t-slot`, `t-set-slot`, `t-slot-scope` | [Rendering a slot](slots.md) |
| `t-model` | [Form input bindings](input_bindings.md) |
| `t-tag` | [Rendering nodes with dynamic tag name](#dynamic-tag-names) |
## QWeb Template Reference
### White Spaces
White spaces in a template are handled in a special way:
- consecutive whitespaces are always condensed to a single whitespace
- if a whitespace-only text node contains a linebreak, it is ignored
- the previous rules do not apply if we are in a `<pre>` tag
### Expression Evaluation
QWeb expressions are strings that will be processed at compile time. Each variable in
the javascript expression will be replaced with a lookup in the context (so, the
component). For example, `a + b.c(d)` will be converted into:
```js
context["a"] + context["b"].c(context["d"]);
```
It is useful to explain the various rules that apply on these expressions:
1. it should be a simple expression which returns a value. It cannot be a statement.
```xml
<div><p t-if="1 + 2 === 3">ok</p></div>
```
is valid, but the following is not valid:
```xml
<div><p t-if="console.log(1)">NOT valid</p></div>
```
2. it can use anything in the rendering context (which typically contains the properties of the component):
```xml
<p t-if="user.birthday === today()">Happy bithday!</p>
```
is valid, and will read the `user` object from the context, and call the
`today` function.
3. it can use a few special operators to avoid using symbols such as `<`, `>`,
`&` or `|`. This is useful to make sure that we still write valid XML.
| Word | replaced with |
| ----- | ------------- |
| `and` | `&&` |
| `or` | `\|\|` |
| `gt` | `>` |
| `gte` | `>=` |
| `lt` | `<` |
| `lte` | `<=` |
So, one can write this:
```xml
<div><p t-if="10 + 2 gt 5">ok</p></div>
```
### Static Html Nodes
Normal, regular html nodes are rendered into themselves:
```xml
<div>hello</div> <!–– rendered as itself ––>
```
### Outputting Data
The `t-esc` directive is necessary whenever you want to add a dynamic text
expression in a template. The text is escaped to avoid security issues.
```xml
<p><t t-esc="value"/></p>
```
rendered with the value `value` set to `42` in the rendering context yields:
```html
<p>42</p>
```
The `t-out` directive is almost the same as `t-esc`, but possibly without the
escaping. The difference is that the value received by the `t-out` directive
will only be not-escaped if it has been marked as such, using the `markup`
utility function:
For example, in the following component:
```js
const { markup, Component, xml } = owl;
class SomeComponent extends Component {
static template = xml`
<t t-out="value1"/>
<t t-out="value2"/>`;
value1 = "<div>some text 1</div>";
value2 = markup("<div>some text 2</div>");
}
```
The first `t-out` will act as a `t-esc` directive, which means that the content
of `value1` will be escaped. However, since `value2` has been tagged as a markup,
this will be injected as html.
### Setting Variables
QWeb allows creating variables from within the template, to memoize a computation (to use it multiple times), give a piece of data a clearer name, ...
This is done via the `t-set` directive, which takes the name of the variable to create. The value to set can be provided in two ways:
1. a `t-value` attribute containing an expression, and the result of its
evaluation will be set:
```xml
<t t-set="foo" t-value="2 + 1"/>
<t t-esc="foo"/>
```
will print `3`. Note that the evaluation is done at rendering time, not at
compilte time.
2. if there is no `t-value` attribute, the nodes body is saved and its value is
set as the variables value:
```xml
<t t-set="foo">
<li>ok</li>
</t>
<t t-esc="foo"/>
```
will generate `&lt;li&gt;ok&lt;/li&gt;` (the content is escaped as we used the `t-esc` directive)
The `t-set` directive acts like a regular variable in most programming language.
It is lexically scoped (inner nodes are sub scopes), can be shadowed, ...
### Conditionals
The `t-if` directive is useful to conditionally render something. It evaluates
the expression given as attribute value, and then acts accordingly.
```xml
<div>
<t t-if="condition">
<p>ok</p>
</t>
</div>
```
The element is rendered if the condition (evaluated with the current rendering
context) is true:
```xml
<div>
<p>ok</p>
</div>
```
but if the condition is false it is removed from the result:
```xml
<div>
</div>
```
The conditional rendering applies to the bearer of the directive, which does not
have to be `<t>`:
```xml
<div>
<p t-if="condition">ok</p>
</div>
```
will give the same results as the previous example.
Extra conditional branching directives `t-elif` and `t-else` are also available:
```xml
<div>
<p t-if="user.birthday == today()">Happy bithday!</p>
<p t-elif="user.login == 'root'">Welcome master!</p>
<p t-else="">Welcome!</p>
</div>
```
### Dynamic Attributes
One can use the `t-att-` directive to add dynamic attributes. Its main use is to
evaluate an expression (at rendering time) and bind an attribute to its result:
For example, if we have `id` set to 32 in the rendering context,
```xml
<div t-att-data-action-id="id"/> <!-- result: <div data-action-id="32"></div> -->
```
If an expression evaluates to a falsy value, it will not be set at all:
```xml
<div t-att-foo="false"/> <!-- result: <div></div> -->
```
It is sometimes convenient to format an attribute with string interpolation. In
that case, the `t-attf-` directive can be used. It is useful when we need to mix
literal and dynamic elements, such as css classes. The dynamic elements can be
specified with either `{{...}}` or `#{...}`:
```xml
<div t-attf-foo="a {{value1}} is #{value2} of {{value3}} ]"/>
<!-- result if values are set to 1,2 and 3: <div foo="a 0 is 1 of 2 ]"></div> -->
```
If we need completely dynamic attribute names, then there is an additional
directive: `t-att`, which takes either an object (with keys mapping to their
values) or a pair `[key, value]`. For example:
```xml
<div t-att="{'a': 1, 'b': 2}"/> <!-- result: <div a="1" b="2"></div> -->
<div t-att="['a', 'b']"/> <!-- <div a="b"></div> -->
```
### Dynamic class attribute
For convenience, Owl supports a special case for the `t-att-class` case: one can
use an object with keys describing the classes, and values boolean value denoting
if the class is or is not present:
```xml
<div t-att-class="{'a': true, 'b': true}"/> <!-- result: <div class="a b"></div> -->
<div t-att-class="{'a b': true, 'c': true}"/> <!-- result: <div class="a b c"></div> -->
```
Note that it can be combined with normal class attribute:
```xml
<div class="a" t-att-class="{'b': true}"/> <!-- result: <div class="a b"></div> -->
```
### Dynamic tag names
When writing generic components or templates, the specific concrete tag for an
HTML element is not known yet. In those situations, the `t-tag` directive is
useful. It simply evaluates dynamically an expression to use as a tag name. The
template:
```xml
<t t-tag="tag">
<span>content</span>
</t>
```
will be rendered as `<div><span>content</span></div>` if the `tag` context key
is set to `div`.
### Loops
QWeb has an iteration directive `t-foreach` which take an expression returning the
collection to iterate on, and a second parameter `t-as` providing the name to use
for the current item of the iteration:
```xml
<t t-foreach="[1, 2, 3]" t-as="i" t-key="i">
<p><t t-esc="i"/></p>
</t>
```
will be rendered as:
```xml
<p>1</p>
<p>2</p>
<p>3</p>
```
Like conditions, `t-foreach` applies to the element bearing the directives attribute, and
```xml
<p t-foreach="[1, 2, 3]" t-as="i" t-key="i">
<t t-esc="i"/>
</p>
```
is equivalent to the previous example.
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 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 useful
variables (note: `$as` will be replaced with the name passed to `t-as`):
- `$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`)
- `$as_last`: whether the current item is the last of the iteration
(equivalent to `$as_index + 1 == $as_size`), requires the iteratees size be
available
These extra variables provided and all new variables created into the `t-foreach`
are only available in the scope of the `t-foreach`. If the variable exists outside
the context of the `t-foreach`, the value is copied at the end of the foreach
into the global context.
```xml
<t t-set="existing_variable" t-value="false"/>
<!-- existing_variable now False -->
<p t-foreach="Array(3)" t-as="i" t-key="i">
<t t-set="existing_variable" t-value="true"/>
<t t-set="new_variable" t-value="true"/>
<!-- existing_variable and new_variable now true -->
</p>
<!-- existing_variable always true -->
<!-- new_variable undefined -->
```
Even though Owl tries to be as declarative as possible, the DOM does not fully
expose its state declaratively in the DOM tree. For example, the scrolling state,
the current user selection, the focused element or the state of an input are not
set as attribute in the DOM tree. This is why we use a virtual dom
algorithm to make sure we keep the actual DOM node instead of replacing it with
a new one.
Consider the following situation: we have a list of two items `[{text: "a"}, {text: "b"}]`
and we render them in this template:
```xml
<p t-foreach="items" t-as="item" t-key="item_index"><t t-esc="item.text"/></p>
```
The result will be two `<p>` tags with text `a` and `b`. Now, if we swap them,
and rerender the template, Owl needs to know what the intent is:
- should Owl actually swap the DOM nodes,
- or should it keep the DOM nodes, but with an updated text content?
This might look trivial, but it actually matters. These two possibilities lead
to different results in some cases. For example, if the user selected the text
of the first `p`, swapping them will keep the selection while updating the
text content will not.
There are many other cases where this is important: `input` tags with their
value, css classes and animations, scroll position...
So, the `t-key` directive is used to give an identity to an element. It allows
Owl to understand if different elements of a list are actually different or not.
The above example could be modified by adding an ID: `[{id: 1, text: "a"}, {id: 2, text: "b"}]`.
Then, the template could look like this:
```xml
<p t-foreach="items" t-as="item" t-key="item.id"><t t-esc="item.text"/></p>
```
The `t-key` directive is useful for lists (`t-foreach`). A key should be
a unique number or string (objects will not work: they will be cast to the
`"[object Object]"` string, which is obviously not unique).
Also, the key can be set on a `t` tag or on its children. The following variations
are all equivalent:
```xml
<p t-foreach="items" t-as="item" t-key="item.id">
<t t-esc="item.text"/>
</p>
<t t-foreach="items" t-as="item" t-key="item.id">
<p t-esc="item.text"/>
</t>
<t t-foreach="items" t-as="item">
<p t-key="item.id" t-esc="item.text"/>
</t>
```
If there is no `t-key` directive, Owl will use the index as a default key.
Note: the `t-foreach` directive only accepts arrays (lists) or objects. It does
not work with other iterables, such as `Set`. However, it is only a matter of
using the `...` javascript operator. For example:
```xml
<t t-foreach="[...items]" t-as="item">...</t>
```
The `...` operator will convert the `Set` (or any other iterables) into a list,
which will work with Owl QWeb.
### Sub Templates
QWeb templates can be used for top level rendering, but they can also be used
from within another template (to avoid duplication or give names to parts of
templates), using the `t-call` directive:
```xml
<div t-name="other-template">
<p><t t-value="var"/></p>
</div>
<div t-name="main-template">
<t t-set="var" t-value="owl"/>
<t t-call="other-template"/>
</div>
```
will be rendered as `<div><p>owl</p></div>`. This example shows that the sub
template is rendered with the execution context of the parent. The sub template
is actually inlined in the main template, but in a sub scope: variables defined
in the sub template do not escape.
Sometimes, one might want to pass information to the sub template. In that case,
the content of the body of the `t-call` directive is available as a special
magic variable `0`:
```xml
<t t-name="other-template">
This template was called with content:
<t t-raw="0"/>
</t>
<div t-name="main-template">
<t t-call="other-template">
<em>content</em>
</t>
</div>
```
will result in :
```xml
<div>
This template was called with content:
<em>content</em>
</div>
```
This can be used to define variables scoped to a sub template:
```xml
<t t-call="other-template">
<t t-set="var" t-value="1"/>
</t>
<!-- "var" does not exist here -->
```
Note: by default, the rendering context for a sub template is simply the current
rendering context. However, it may be useful to be able to specify a specific
object as context. This can be done by using the `t-call-context` directive:
```xml
<t t-call="other-template" t-call-context="obj"/>
```
### Dynamic sub templates
The `t-call` directive can also be used to dynamically call a sub template,
using string interpolation. For example:
```xml
<div t-name="main-template">
<t t-call="{{template}}">
<em>content</em>
</t>
</div>
```
Here, the name of the template is obtained from the `template` value in the
template rendering context.
### Debugging
The javascript QWeb implementation provides two useful debugging directives:
`t-debug` adds a debugger statement during template rendering:
```xml
<t t-if="a_test">
<t t-debug=""/>
</t>
```
will stop execution if the browser dev tools are open.
`t-log` takes an expression parameter, evaluates the expression during rendering and logs its result with console.log:
```xml
<t t-set="foo" t-value="42"/>
<t t-log="foo"/>
```
will print 42 to the console.
## Fragments
Owl 2 supports templates with an arbitrary number of root elements, or even just
a text node. So, the following templates are all valid:
```xml
hello owl. This is just a text node!
```
```xml
<div>hello</div>
```
```xml
<div>hello</div>
<div>ola</div>
```
```xml
<div t-if="someCondition"><SomeChildComponent/></div>
```
```xml
<t t-if="someCondition"><SomeChildComponent/></t>
```
## Inline templates
Most real applications will define their templates in a XML file, to benefit
from the XML ecosystem, and to do some additional processing, such as translating
them. However, in some cases, it is convenient to be able to define a template
inline. To do so, one can use the `xml` helper function:
```js
const { Component, xml } = owl;
class MyComponent extends Component {
static template = xml`
<div>
<span t-if="somecondition">text</span>
<button t-on-click="someMethod">Click</button>
</div>
`;
...
}
mount(MyComponent, document.body);
```
This function simply generates an unique string id, and register the template
under that id in the internals of Owl, then return the id.
## Rendering svg
Owl components can be used to generate dynamic SVG graphs:
```js
class Node extends Component {
static template = xml`
<g>
<circle t-att-cx="props.x" t-att-cy="props.y" r="4" fill="black"/>
<text t-att-x="props.x - 5" t-att-y="props.y + 18"><t t-esc="props.node.label"/></text>
<t t-set="childx" t-value="props.x + 100"/>
<t t-set="height" t-value="props.height/(props.node.children || []).length"/>
<t t-foreach="props.node.children || []" t-as="child">
<t t-set="childy" t-value="props.y + child_index*height"/>
<line t-att-x1="props.x" t-att-y1="props.y" t-att-x2="childx" t-att-y2="childy" stroke="black" />
<Node x="childx" y="childy" node="child" height="height"/>
</t>
</g>
`;
static components = { Node };
}
class RootNode extends Component {
static template = xml`
<svg height="180">
<Node node="graph" x="10" y="20" height="180"/>
</svg>
`;
static components = { Node };
graph = {
label: "a",
children: [
{ label: "b" },
{ label: "c", children: [{ label: "d" }, { label: "e" }] },
{ label: "f", children: [{ label: "g" }] },
],
};
}
```
This `RootNode` component will then display a live SVG representation of the
graph described by the `graph` property. Note that there is a recursive structure
here: the `Node` component uses itself as a subcomponent.
**Important note:** Owl needs to properly set the namespace for each svg elements.
Since Owl compile each template separately, it is not able to determine easily
if a template is supposed to be included in a svg namespace or not. Therefore,
Owl depends on a heuristic: if a tag is either `svg`, `g` or `path`, then it will
be considered as svg. In practice, this means that each component or each sub
templates (included with `t-call`) should have one of these tag as root tag.
## Restrictions
Note that Owl templates forbid the use of tag and or attributes starting with
the `block-` string. This restriction prevents name collision with the internal
code of Owl.
```xml
<div><block-1>this will not be accepted by Owl</block-1></div>
```
+70
View File
@@ -0,0 +1,70 @@
# 🦉 Translations 🦉
If properly setup, Owl can translate all rendered templates. To do
so, it needs a translate function, which takes a string and returns a string.
For example:
```js
const translations = {
hello: "bonjour",
yes: "oui",
no: "non",
};
const translateFn = (str) => translations[str] || str;
const app = new App(Root, { templates, tranaslateFn });
// ...
```
See the [app configuration page](app.md#configuration) for more info on how to
configure an Owl application.
Once setup, all rendered templates will be translated using `translateFn`:
- each text node will be replaced with its translation,
- each of the following attribute values will be translated as well: `title`,
`placeholder`, `label` and `alt`,
- translating text nodes can be disabled with the special attribute `t-translation`,
if its value is `off`.
So, with the above `translateFn`, the following templates:
```xml
<div>hello</div>
<div t-translation="off">hello</div>
<div>Are you sure?</div>
<input placeholder="hello" other="yes"/>
```
will be rendered as:
```xml
<div>bonjour</div>
<div>hello</div>
<div>Are you sure?</div>
<input placeholder="bonjour" other="yes"/>
```
Note that the translation is done during the compilation of the template, not
when it is rendered.
In some case, it is useful to be able to extend the list of translatable attributes.
For example, one may want to also translate `data-title` attributes. To do that,
we can define additional attributes with the `translatableAttributes` option:
```js
const app = new App(Root, { templates, tranaslateFn, translatableAttributes: ["data-title"] });
// ...
```
It is also possible to remove an attribute from the default list by prefixing it with `-`:
```js
const app = new App(Root, {
templates,
tranaslateFn,
translatableAttributes: ["data-title", "-title"],
});
// data-title attribute will be translated, but not title attribute...
```
+80
View File
@@ -0,0 +1,80 @@
# 🦉 Utils 🦉
Owl export a few useful utility functions, to help with common issues. Those
functions are all available in the `owl.utils` namespace.
## Content
- [`whenReady`](#whenready): executing code when DOM is ready
- [`loadFile`](#loadfile): loading a file (useful for templates)
- [`EventBus`](#eventbus): a simple EventBus
- [`validate`](#validate): a validation function
## `whenReady`
The function `whenReady` returns a `Promise` resolved when the DOM is ready (if
not ready yet, resolved directly otherwise). If called with a callback as
argument, it executes it as soon as the DOM ready (or directly).
```js
const { whenReady } = owl;
await whenReady();
// do something
```
or alternatively:
```js
whenReady(function () {
// do something
});
```
## `loadFile`
`loadFile` is a helper function to fetch a file. It simply
performs a `GET` request and returns the resulting string in a promise. The
initial usecase for this function is to load a template file. For example:
```js
const { loadFile } = owl;
async function makeEnv() {
const templates = await loadFile("templates.xml");
// do something
}
```
## `EventBus`
It is a simple `EventBus`, with the same API as usual DOM elements, and an
additional `trigger` method to dispatch events:
```js
const bus = new EventBus();
bus.addEventListener("event", () => console.log("something happened"));
bus.trigger("event"); // 'something happened' is logged
```
## `validate`
The `validate` function is a function that validates if a given object satisfies a
specified schema. It is actually used by Owl itself to perform
[props validation](props.md#props-validation). For example:
```js
validate(
{ a: "hey" },
{
id: Number,
url: [Boolean, { type: Array, element: Number }],
}
);
// throws an error with the following information:
// - unknown key 'a',
// - 'id' is missing (should be a number),
// - 'url' is missing (should be a boolean or list of numbers),
```
-8
View File
@@ -1,8 +0,0 @@
# OWL: State Management
Managing the state in an application is not an easy task. Many different
architectures/designs/systems/... have been created. We propose here to use
the idea of a central store.
- Store
- connect
+56
View File
@@ -0,0 +1,56 @@
# Owl Devtools Browser extension
The owl devtools browser extension is an extension available on chrome or firefox which adds an owl tab
to the browser devtools in order to inspect all owl apps that are present on any web page, their components
and allows to interract with their data to a certain extend. There is also a profiler available to visualize
the components' lifecycle and be able to trace their origin.
See the [`devtools doc`](devtools_guide.md) for more information.
## Install the extension manually (for devs)
In the owl root folder:
```bash
npm install
```
For chrome:
```bash
npm run build:devtools-chrome
```
For firefox:
```bash
npm run build:devtools-firefox
```
You can also run:
```bash
npm run dev:devtools-chrome
```
or
```bash
npm run dev:devtools-firefox
```
to avoid recompiling owl and gain time if it has already been done.
To run the extension:
In google chrome: go to your chrome extensions admin panel, activate developer mode and click on `Load unpacked`.
Select the output folder (dist/devtools) and that's it, your extension is active!
There is a convenient refresh button on the extension card (still on the same admin page) to update your code.
Do note that if you got some problems, you may need to completly remove and reload the extension to completly refresh the extension.
In firefox: go to the address about:debugging#/runtime/this-firefox and click on `Load temporary Add-on...`.
Select any file of the output folder (dist/devtools) and that's it, your extension is active!
Here, you can use the reload button to refresh the extension.
Note that you may have to open another window or reload your tab to see the extension working.
Also note that the extension will only be active on pages that have a sufficient version of owl.
+155
View File
@@ -0,0 +1,155 @@
# Owl Devtools Guide
## Information popup
After having installed the extension, a new icon will be added to your extension bar.
If you don't see it, you can pin the extension using the extensions popup.
<img src="screenshots/extensions.png"/>
Clicking on the owl icon will open the information popup. This popup is useful
to know in advance whether owl is loaded in the tab or not. This is also indicated
by the icon itself: if it is flipped upside-down, it means that owl is not loaded in the
active tab. Do note that old versions of owl are not supported by the extension and will
therefore be indicated either as obsolete or absent by the extension popup.
<img src="screenshots/popup.png"/>
## First steps
When you are on a page where owl is detected, you can open your devtools either with
right-click -> Inspect or using F12. In the devtools menu, you can search for the Owl
tab which is added by the extension. It will be present by default at the end of the list but
you can drag and drop it at the position you want for easier navigation in the future.
<img src="screenshots/find_owl_tab.png"/>
When you open the tab, you arrive on the Components view by default which is one of the
two available tabs at the top. Here is an example of the devtools on the Odoo CRM app:
<img src="screenshots/crm.png"/>
## Components tab
The components tab is separated into two sub windows: the components tree in the left and
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 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 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.
<img src="screenshots/picker.png"/>
In the tree itself, the navigation is quite simple and is similar to the one in the Elements tab
of the browser's devtools. It is possible to navigate with the keyboard using the arrow keys and
multiple shortcuts are available in a custom menu when right-clicking on a component. This menu
allows to expand/fold all the children nodes of a component, fold its direct children only, inspect
the source code of the component, send it as a global variable in the console, go to the Elements tab
and focus on its content, force a rerender of the component, send its observed states to the console
as a global variable, inspect its compiled template in the Sources tab or send its raw template
to the console.
<img src="screenshots/menu.png"/>
The component details window in the right will show the component that is currently selected as well
as its env, props, observed states and all the other variables that are present on its instance.
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 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"/>
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.
<img src="screenshots/function_menu.png"/>
There are several icons available to perform several of the actions described before in the components
tree context menu and all these actions are also available by opening the menu by right-clicking on the
component's name. Using the left click on the component's name will focus it in the components tree.
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, ...). 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"/>
## Profiler
The profiler tab is the other tab of the owl devtools. It consists in an actions bar at the top and
a tree/list of events related to the owl components' renders. Here is an example of the events launched
when entering the Odoo Crm app.
<img src="screenshots/profiler.png"/>
In the initial state, no event is displayed. You need to activate the recording of events before they
are intercepted by the devtools using the record button.
<img src="screenshots/record.png"/>
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. Also, a transition line will
appear each time a new animation frame has been loaded between events.
<img src="screenshots/events_log.png"/>
The third button is only visible in tree view and allows to fold all the render events that were recorded.
Some actions are also available when using the right-click on any event of the tree view for navigation
purpose in a similar fashion as in the components tree.
<img src="screenshots/tree_actions.png"/>
There is also the Trace Renderings and Trace Subscriptions features. These features are independant of the
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.
<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. 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, 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.

After

Width:  |  Height:  |  Size: 545 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 387 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 266 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 142 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 320 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 206 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 329 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 166 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 536 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 488 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 177 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 182 KiB

-3
View File
@@ -1,3 +0,0 @@
# Tutorial
todo...
File diff suppressed because one or more lines are too long
+72
View File
@@ -0,0 +1,72 @@
/* http://jmblog.github.com/color-themes-for-google-code-highlightjs */
/* Tomorrow Comment */
.hljs-comment,
.hljs-quote {
color: #8e908c;
}
/* Tomorrow Red */
.hljs-variable,
.hljs-template-variable,
.hljs-tag,
.hljs-name,
.hljs-selector-id,
.hljs-selector-class,
.hljs-regexp,
.hljs-deletion {
color: #c82829;
}
/* Tomorrow Orange */
.hljs-number,
.hljs-built_in,
.hljs-builtin-name,
.hljs-literal,
.hljs-type,
.hljs-params,
.hljs-meta,
.hljs-link {
color: #f5871f;
}
/* Tomorrow Yellow */
.hljs-attribute {
color: #eab700;
}
/* Tomorrow Green */
.hljs-string,
.hljs-symbol,
.hljs-bullet,
.hljs-addition {
color: #718c00;
}
/* Tomorrow Blue */
.hljs-title,
.hljs-section {
color: #4271ae;
}
/* Tomorrow Purple */
.hljs-keyword,
.hljs-selector-tag {
color: #8959a8;
}
.hljs {
display: block;
overflow-x: auto;
background: white;
color: #4d4d4c;
padding: 0.5em;
}
.hljs-emphasis {
font-style: italic;
}
.hljs-strong {
font-weight: bold;
}
+116
View File
@@ -0,0 +1,116 @@
html, body {
background-color: #fefefe;
font-family: Roboto, -apple-system, BlinkMacSystemFont, "Segoe UI", Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
height: 100%;
margin: 0;
text-rendering: optimizeLegibility;
}
body {
display: grid;
grid-gap: 3rem;
grid-template-areas: "header" "nav" "main" "footer";
grid-template-columns: 1fr;
height: 100%;
grid-template-rows: 1fr 3rem 1fr 3rem;
}
@media screen and (max-width: 800px) {
body {
grid-template-rows: 1fr 3rem 1fr 5rem;
}
}
a {
color: #00A09D;
text-decoration: none;
}
a:hover, a:active, a:visited {
text-decoration: underline;
}
header {
grid-area: header;
display: flex;
align-items: center;
flex-direction: column;
justify-content: flex-end;
text-align: center;
padding-top: 3rem !important;
}
hgroup > p {
margin-bottom: auto;
}
nav {
grid-area: nav;
}
main {
grid-area: main;
/*justify-self: center;*/
grid-column: 1 / -1;
/*max-width: 80rem !important;*/
/*margin: 3rem 0;*/
}
footer {
grid-area: footer;
padding-bottom: 3rem !important;
}
header, nav, footer {
text-align: center;
}
article {
padding: 3rem 0;
}
article h3 {
font-size: 2rem;
font-weight: 700;
}
article.brand {
align-items: center;
display: flex;
flex-direction: column;
justify-content: center;
text-align: center;
}
article.design {
background-color: #875A7B;
color: #f0eeee;
}
header .homepage-logo {
margin-bottom: 2rem;
}
@media (min-width: 40rem) {
.row {
flex-direction: column;
margin-left: initial;
width: 100%;
}
.row .column {
margin-bottom: initial;
padding: initial;
}
}
@media (min-width: 60rem) {
.row {
flex-direction: row;
margin-left: -1.0rem;
width: calc(100% + 2.0rem);
}
.row .column {
margin-bottom: inherit;
padding: 0 1.0rem;
}
}
+602
View File
@@ -0,0 +1,602 @@
/*!
* Milligram v1.3.0
* https://milligram.github.io
*
* Copyright (c) 2017 CJ Patoilo
* Licensed under the MIT license
*/
*,
*:after,
*:before {
box-sizing: inherit;
}
html {
box-sizing: border-box;
font-size: 62.5%;
}
body {
color: #606c76;
font-family: 'Roboto', 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif;
font-size: 1.6em;
font-weight: 300;
letter-spacing: .01em;
line-height: 1.6;
}
blockquote {
border-left: 0.3rem solid #d1d1d1;
margin-left: 0;
margin-right: 0;
padding: 1rem 1.5rem;
}
blockquote *:last-child {
margin-bottom: 0;
}
.button,
button,
input[type='button'],
input[type='reset'],
input[type='submit'] {
background-color: #9b4dca;
border: 0.1rem solid #9b4dca;
border-radius: .4rem;
color: #fff;
cursor: pointer;
display: inline-block;
font-size: 1.1rem;
font-weight: 700;
height: 3.8rem;
letter-spacing: .1rem;
line-height: 3.8rem;
padding: 0 3.0rem;
text-align: center;
text-decoration: none;
text-transform: uppercase;
white-space: nowrap;
}
.button:focus, .button:hover,
button:focus,
button:hover,
input[type='button']:focus,
input[type='button']:hover,
input[type='reset']:focus,
input[type='reset']:hover,
input[type='submit']:focus,
input[type='submit']:hover {
background-color: #606c76;
border-color: #606c76;
color: #fff;
outline: 0;
}
.button[disabled],
button[disabled],
input[type='button'][disabled],
input[type='reset'][disabled],
input[type='submit'][disabled] {
cursor: default;
opacity: .5;
}
.button[disabled]:focus, .button[disabled]:hover,
button[disabled]:focus,
button[disabled]:hover,
input[type='button'][disabled]:focus,
input[type='button'][disabled]:hover,
input[type='reset'][disabled]:focus,
input[type='reset'][disabled]:hover,
input[type='submit'][disabled]:focus,
input[type='submit'][disabled]:hover {
background-color: #9b4dca;
border-color: #9b4dca;
}
.button.button-outline,
button.button-outline,
input[type='button'].button-outline,
input[type='reset'].button-outline,
input[type='submit'].button-outline {
background-color: transparent;
color: #9b4dca;
}
.button.button-outline:focus, .button.button-outline:hover,
button.button-outline:focus,
button.button-outline:hover,
input[type='button'].button-outline:focus,
input[type='button'].button-outline:hover,
input[type='reset'].button-outline:focus,
input[type='reset'].button-outline:hover,
input[type='submit'].button-outline:focus,
input[type='submit'].button-outline:hover {
background-color: transparent;
border-color: #606c76;
color: #606c76;
}
.button.button-outline[disabled]:focus, .button.button-outline[disabled]:hover,
button.button-outline[disabled]:focus,
button.button-outline[disabled]:hover,
input[type='button'].button-outline[disabled]:focus,
input[type='button'].button-outline[disabled]:hover,
input[type='reset'].button-outline[disabled]:focus,
input[type='reset'].button-outline[disabled]:hover,
input[type='submit'].button-outline[disabled]:focus,
input[type='submit'].button-outline[disabled]:hover {
border-color: inherit;
color: #9b4dca;
}
.button.button-clear,
button.button-clear,
input[type='button'].button-clear,
input[type='reset'].button-clear,
input[type='submit'].button-clear {
background-color: transparent;
border-color: transparent;
color: #9b4dca;
}
.button.button-clear:focus, .button.button-clear:hover,
button.button-clear:focus,
button.button-clear:hover,
input[type='button'].button-clear:focus,
input[type='button'].button-clear:hover,
input[type='reset'].button-clear:focus,
input[type='reset'].button-clear:hover,
input[type='submit'].button-clear:focus,
input[type='submit'].button-clear:hover {
background-color: transparent;
border-color: transparent;
color: #606c76;
}
.button.button-clear[disabled]:focus, .button.button-clear[disabled]:hover,
button.button-clear[disabled]:focus,
button.button-clear[disabled]:hover,
input[type='button'].button-clear[disabled]:focus,
input[type='button'].button-clear[disabled]:hover,
input[type='reset'].button-clear[disabled]:focus,
input[type='reset'].button-clear[disabled]:hover,
input[type='submit'].button-clear[disabled]:focus,
input[type='submit'].button-clear[disabled]:hover {
color: #9b4dca;
}
code {
background: #f4f5f6;
border-radius: .4rem;
font-size: 86%;
margin: 0 .2rem;
padding: .2rem .5rem;
white-space: nowrap;
}
pre {
background: #f4f5f6;
border-left: 0.3rem solid #9b4dca;
overflow-y: hidden;
}
pre > code {
border-radius: 0;
display: block;
padding: 1rem 1.5rem;
white-space: pre;
}
hr {
border: 0;
border-top: 0.1rem solid #f4f5f6;
margin: 3.0rem 0;
}
input[type='email'],
input[type='number'],
input[type='password'],
input[type='search'],
input[type='tel'],
input[type='text'],
input[type='url'],
textarea,
select {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background-color: transparent;
border: 0.1rem solid #d1d1d1;
border-radius: .4rem;
box-shadow: none;
box-sizing: inherit;
height: 3.8rem;
padding: .6rem 1.0rem;
width: 100%;
}
input[type='email']:focus,
input[type='number']:focus,
input[type='password']:focus,
input[type='search']:focus,
input[type='tel']:focus,
input[type='text']:focus,
input[type='url']:focus,
textarea:focus,
select:focus {
border-color: #9b4dca;
outline: 0;
}
select {
background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" height="14" viewBox="0 0 29 14" width="29"><path fill="#d1d1d1" d="M9.37727 3.625l5.08154 6.93523L19.54036 3.625"/></svg>') center right no-repeat;
padding-right: 3.0rem;
}
select:focus {
background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" height="14" viewBox="0 0 29 14" width="29"><path fill="#9b4dca" d="M9.37727 3.625l5.08154 6.93523L19.54036 3.625"/></svg>');
}
textarea {
min-height: 6.5rem;
}
label,
legend {
display: block;
font-size: 1.6rem;
font-weight: 700;
margin-bottom: .5rem;
}
fieldset {
border-width: 0;
padding: 0;
}
input[type='checkbox'],
input[type='radio'] {
display: inline;
}
.label-inline {
display: inline-block;
font-weight: normal;
margin-left: .5rem;
}
.container {
margin: 0 auto;
max-width: 112.0rem;
padding: 0 2.0rem;
position: relative;
width: 100%;
}
.row {
display: flex;
flex-direction: column;
padding: 0;
width: 100%;
}
.row.row-no-padding {
padding: 0;
}
.row.row-no-padding > .column {
padding: 0;
}
.row.row-wrap {
flex-wrap: wrap;
}
.row.row-top {
align-items: flex-start;
}
.row.row-bottom {
align-items: flex-end;
}
.row.row-center {
align-items: center;
}
.row.row-stretch {
align-items: stretch;
}
.row.row-baseline {
align-items: baseline;
}
.row .column {
display: block;
flex: 1 1 auto;
margin-left: 0;
max-width: 100%;
width: 100%;
}
.row .column.column-offset-10 {
margin-left: 10%;
}
.row .column.column-offset-20 {
margin-left: 20%;
}
.row .column.column-offset-25 {
margin-left: 25%;
}
.row .column.column-offset-33, .row .column.column-offset-34 {
margin-left: 33.3333%;
}
.row .column.column-offset-50 {
margin-left: 50%;
}
.row .column.column-offset-66, .row .column.column-offset-67 {
margin-left: 66.6666%;
}
.row .column.column-offset-75 {
margin-left: 75%;
}
.row .column.column-offset-80 {
margin-left: 80%;
}
.row .column.column-offset-90 {
margin-left: 90%;
}
.row .column.column-10 {
flex: 0 0 10%;
max-width: 10%;
}
.row .column.column-20 {
flex: 0 0 20%;
max-width: 20%;
}
.row .column.column-25 {
flex: 0 0 25%;
max-width: 25%;
}
.row .column.column-33, .row .column.column-34 {
flex: 0 0 33.3333%;
max-width: 33.3333%;
}
.row .column.column-40 {
flex: 0 0 40%;
max-width: 40%;
}
.row .column.column-50 {
flex: 0 0 50%;
max-width: 50%;
}
.row .column.column-60 {
flex: 0 0 60%;
max-width: 60%;
}
.row .column.column-66, .row .column.column-67 {
flex: 0 0 66.6666%;
max-width: 66.6666%;
}
.row .column.column-75 {
flex: 0 0 75%;
max-width: 75%;
}
.row .column.column-80 {
flex: 0 0 80%;
max-width: 80%;
}
.row .column.column-90 {
flex: 0 0 90%;
max-width: 90%;
}
.row .column .column-top {
align-self: flex-start;
}
.row .column .column-bottom {
align-self: flex-end;
}
.row .column .column-center {
-ms-grid-row-align: center;
align-self: center;
}
@media (min-width: 40rem) {
.row {
flex-direction: row;
margin-left: -1.0rem;
width: calc(100% + 2.0rem);
}
.row .column {
margin-bottom: inherit;
padding: 0 1.0rem;
}
}
a {
color: #9b4dca;
text-decoration: none;
}
a:focus, a:hover {
color: #606c76;
}
dl,
ol,
ul {
list-style: none;
margin-top: 0;
padding-left: 0;
}
dl dl,
dl ol,
dl ul,
ol dl,
ol ol,
ol ul,
ul dl,
ul ol,
ul ul {
font-size: 90%;
margin: 1.5rem 0 1.5rem 3.0rem;
}
ol {
list-style: decimal inside;
}
ul {
list-style: circle inside;
}
.button,
button,
dd,
dt,
li {
margin-bottom: 1.0rem;
}
fieldset,
input,
select,
textarea {
margin-bottom: 1.5rem;
}
blockquote,
dl,
figure,
form,
ol,
p,
pre,
table,
ul {
margin-bottom: 2.5rem;
}
table {
border-spacing: 0;
width: 100%;
}
td,
th {
border-bottom: 0.1rem solid #e1e1e1;
padding: 1.2rem 1.5rem;
text-align: left;
}
td:first-child,
th:first-child {
padding-left: 0;
}
td:last-child,
th:last-child {
padding-right: 0;
}
b,
strong {
font-weight: bold;
}
p {
margin-top: 0;
}
h1,
h2,
h3,
h4,
h5,
h6 {
font-weight: 300;
letter-spacing: -.1rem;
margin-bottom: 2.0rem;
margin-top: 0;
}
h1 {
font-size: 4.6rem;
line-height: 1.2;
}
h2 {
font-size: 3.6rem;
line-height: 1.25;
}
h3 {
font-size: 2.8rem;
line-height: 1.3;
}
h4 {
font-size: 2.2rem;
letter-spacing: -.08rem;
line-height: 1.35;
}
h5 {
font-size: 1.8rem;
letter-spacing: -.05rem;
line-height: 1.5;
}
h6 {
font-size: 1.6rem;
letter-spacing: 0;
line-height: 1.4;
}
img {
max-width: 100%;
}
.clearfix:after {
clear: both;
content: ' ';
display: table;
}
.float-left {
float: left;
}
.float-right {
float: right;
}
/*# sourceMappingURL=milligram.css.map */
+349
View File
@@ -0,0 +1,349 @@
/*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */
/* Document
========================================================================== */
/**
* 1. Correct the line height in all browsers.
* 2. Prevent adjustments of font size after orientation changes in iOS.
*/
html {
line-height: 1.15; /* 1 */
-webkit-text-size-adjust: 100%; /* 2 */
}
/* Sections
========================================================================== */
/**
* Remove the margin in all browsers.
*/
body {
margin: 0;
}
/**
* Render the `main` element consistently in IE.
*/
main {
display: block;
}
/**
* Correct the font size and margin on `h1` elements within `section` and
* `article` contexts in Chrome, Firefox, and Safari.
*/
h1 {
font-size: 2em;
margin: 0.67em 0;
}
/* Grouping content
========================================================================== */
/**
* 1. Add the correct box sizing in Firefox.
* 2. Show the overflow in Edge and IE.
*/
hr {
box-sizing: content-box; /* 1 */
height: 0; /* 1 */
overflow: visible; /* 2 */
}
/**
* 1. Correct the inheritance and scaling of font size in all browsers.
* 2. Correct the odd `em` font sizing in all browsers.
*/
pre {
font-family: monospace, monospace; /* 1 */
font-size: 1em; /* 2 */
}
/* Text-level semantics
========================================================================== */
/**
* Remove the gray background on active links in IE 10.
*/
a {
background-color: transparent;
}
/**
* 1. Remove the bottom border in Chrome 57-
* 2. Add the correct text decoration in Chrome, Edge, IE, Opera, and Safari.
*/
abbr[title] {
border-bottom: none; /* 1 */
text-decoration: underline; /* 2 */
text-decoration: underline dotted; /* 2 */
}
/**
* Add the correct font weight in Chrome, Edge, and Safari.
*/
b,
strong {
font-weight: bolder;
}
/**
* 1. Correct the inheritance and scaling of font size in all browsers.
* 2. Correct the odd `em` font sizing in all browsers.
*/
code,
kbd,
samp {
font-family: monospace, monospace; /* 1 */
font-size: 1em; /* 2 */
}
/**
* Add the correct font size in all browsers.
*/
small {
font-size: 80%;
}
/**
* Prevent `sub` and `sup` elements from affecting the line height in
* all browsers.
*/
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sub {
bottom: -0.25em;
}
sup {
top: -0.5em;
}
/* Embedded content
========================================================================== */
/**
* Remove the border on images inside links in IE 10.
*/
img {
border-style: none;
}
/* Forms
========================================================================== */
/**
* 1. Change the font styles in all browsers.
* 2. Remove the margin in Firefox and Safari.
*/
button,
input,
optgroup,
select,
textarea {
font-family: inherit; /* 1 */
font-size: 100%; /* 1 */
line-height: 1.15; /* 1 */
margin: 0; /* 2 */
}
/**
* Show the overflow in IE.
* 1. Show the overflow in Edge.
*/
button,
input { /* 1 */
overflow: visible;
}
/**
* Remove the inheritance of text transform in Edge, Firefox, and IE.
* 1. Remove the inheritance of text transform in Firefox.
*/
button,
select { /* 1 */
text-transform: none;
}
/**
* Correct the inability to style clickable types in iOS and Safari.
*/
button,
[type="button"],
[type="reset"],
[type="submit"] {
-webkit-appearance: button;
}
/**
* Remove the inner border and padding in Firefox.
*/
button::-moz-focus-inner,
[type="button"]::-moz-focus-inner,
[type="reset"]::-moz-focus-inner,
[type="submit"]::-moz-focus-inner {
border-style: none;
padding: 0;
}
/**
* Restore the focus styles unset by the previous rule.
*/
button:-moz-focusring,
[type="button"]:-moz-focusring,
[type="reset"]:-moz-focusring,
[type="submit"]:-moz-focusring {
outline: 1px dotted ButtonText;
}
/**
* Correct the padding in Firefox.
*/
fieldset {
padding: 0.35em 0.75em 0.625em;
}
/**
* 1. Correct the text wrapping in Edge and IE.
* 2. Correct the color inheritance from `fieldset` elements in IE.
* 3. Remove the padding so developers are not caught out when they zero out
* `fieldset` elements in all browsers.
*/
legend {
box-sizing: border-box; /* 1 */
color: inherit; /* 2 */
display: table; /* 1 */
max-width: 100%; /* 1 */
padding: 0; /* 3 */
white-space: normal; /* 1 */
}
/**
* Add the correct vertical alignment in Chrome, Firefox, and Opera.
*/
progress {
vertical-align: baseline;
}
/**
* Remove the default vertical scrollbar in IE 10+.
*/
textarea {
overflow: auto;
}
/**
* 1. Add the correct box sizing in IE 10.
* 2. Remove the padding in IE 10.
*/
[type="checkbox"],
[type="radio"] {
box-sizing: border-box; /* 1 */
padding: 0; /* 2 */
}
/**
* Correct the cursor style of increment and decrement buttons in Chrome.
*/
[type="number"]::-webkit-inner-spin-button,
[type="number"]::-webkit-outer-spin-button {
height: auto;
}
/**
* 1. Correct the odd appearance in Chrome and Safari.
* 2. Correct the outline style in Safari.
*/
[type="search"] {
-webkit-appearance: textfield; /* 1 */
outline-offset: -2px; /* 2 */
}
/**
* Remove the inner padding in Chrome and Safari on macOS.
*/
[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
/**
* 1. Correct the inability to style clickable types in iOS and Safari.
* 2. Change font properties to `inherit` in Safari.
*/
::-webkit-file-upload-button {
-webkit-appearance: button; /* 1 */
font: inherit; /* 2 */
}
/* Interactive
========================================================================== */
/*
* Add the correct display in Edge, IE 10+, and Firefox.
*/
details {
display: block;
}
/*
* Add the correct display in all browsers.
*/
summary {
display: list-item;
}
/* Misc
========================================================================== */
/**
* Add the correct display in IE 10+.
*/
template {
display: none;
}
/**
* Add the correct display in IE 10.
*/
[hidden] {
display: none;
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

+15
View File
@@ -0,0 +1,15 @@
import { mount, Component, useState, loadFile } from "@odoo/owl";
class Counter extends Component {
static template = "Counter";
setup() {
this.state = useState({ value: 0 });
}
increment() {
this.state.value++;
}
}
const templates = await loadFile("./counter.xml");
mount(Counter, document.getElementById("app-container"), { templates });
+7
View File
@@ -0,0 +1,7 @@
<templates>
<t t-name="Counter">
<button t-on-click="increment">
Click Me! [<t t-esc="state.value"/>]
</button>
</t>
</templates>
+9
View File
@@ -0,0 +1,9 @@
import { loadFile } from "@odoo/owl";
for (const [className, type] of [["xml", "xml"], ["javascript", "js"]]) {
loadFile(`./counter.${type}`).then(code => {
const el = document.querySelector(`code.${className}`);
el.textContent = code;
hljs.highlightBlock(el);
})
}
+74
View File
@@ -0,0 +1,74 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OWL Framework</title>
<link rel="icon" href="data:,">
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Roboto:300,300italic,700,700italic">
<link rel="stylesheet" href="assets/normalize.css">
<link rel="stylesheet" href="assets/milligram.css">
<link rel="stylesheet" href="assets/highlight.tomorrow.css">
<link rel="stylesheet" href="assets/main.css">
<script type="importmap">{ "imports": { "@odoo/owl": "./owl.js" } }</script>
</head>
<body>
<header class="container">
<img class="homepage-logo" src="assets/owl_1f989.png" alt="OWL Logo">
<hgroup>
<h1>OWL Framework</h1>
<p>Mysterious OWL: A web framework for structured, dynamic and maintainable applications</p>
</hgroup>
</header>
<nav class="container">
<p>
<a href="https://github.com/odoo/owl" title="https://github.com/odoo/owl">Github</a>
&bull;
<a href="https://github.com/odoo/owl/blob/master/doc/readme.md">Documentation</a>
&bull;
<a href="playground/">Playground</a>
</p>
</nav>
<main>
<article class="design">
<div class="container">
<h2>Why OWL?</h2>
<div class="row">
<section class="column">
<h3>XML based</h3>
<p>Templates are based on the XML format, which allows interesting applications. For example, they could be stored in a database and modified dynamically with <tt>xpaths</tt>.</p>
</section>
<section class="column">
<h3>Templates compiled in the browser</h3>
<p>This may not be a good fit for all applications, but if you need to generate dynamically user interfaces in the browser, this is very powerful. For example, a generic form view component could generate a specific form user interface for each various models, from a XML view.</p>
</section>
<section class="column">
<h3>No toolchain required</h3>
<p>This is extremely useful for some applications, if, for various reasons (security/deployment/dynamic modules/specific assets tools), it is not ok to use standard web tools based on <tt>npm</tt>.</p>
</section>
</div>
</div>
</article>
<article class="example">
<div class="container">
<h2>Example</h2>
<div class="row">
<section class="column">
<pre><code class="javascript"></code></pre>
</section>
<section class="column">
<pre><code class="xml"></code></pre>
<div id="app-container"></div>
</section>
</div>
</div>
</article>
</main>
<footer>
<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="module" src="display_code.js"></script>
<script type="module" src="counter.js"></script>
</body>
</html>
+5971
View File
File diff suppressed because it is too large Load Diff
+18
View File
@@ -0,0 +1,18 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>OWL Playground</title>
<link rel="icon" href="data:,">
<script src="libs/ace.js" type="text/javascript" charset="utf-8"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/solid.css" integrity="sha384-QokYePQSOwpBDuhlHOsX0ymF6R/vLk/UQVz3WHa6wygxI5oGTmDTv8wahFOSspdm" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/fontawesome.css" integrity="sha384-vd1e11sR28tEK9YANUtpIOdjGW14pS87bUBuOIoBILVWLFnS+MCX9T6MMf0VdPGq" crossorigin="anonymous">
<!-- Application JS/CSS -->
<link rel="stylesheet" href="playground.css">
<script type="module" src="playground.js"></script>
</head>
<body>
</body>
</html>
+3
View File
@@ -0,0 +1,3 @@
(function(a,b){if("function"==typeof define&&define.amd)define([],b);else if("undefined"!=typeof exports)b();else{b(),a.FileSaver={exports:{}}.exports}})(this,function(){"use strict";function b(a,b){return"undefined"==typeof b?b={autoBom:!1}:"object"!=typeof b&&(console.warn("Depricated: Expected third argument to be a object"),b={autoBom:!b}),b.autoBom&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(a.type)?new Blob(["\uFEFF",a],{type:a.type}):a}function c(b,c,d){var e=new XMLHttpRequest;e.open("GET",b),e.responseType="blob",e.onload=function(){a(e.response,c,d)},e.onerror=function(){console.error("could not download file")},e.send()}function d(a){var b=new XMLHttpRequest;return b.open("HEAD",a,!1),b.send(),200<=b.status&&299>=b.status}function e(a){try{a.dispatchEvent(new MouseEvent("click"))}catch(c){var b=document.createEvent("MouseEvents");b.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),a.dispatchEvent(b)}}var f="object"==typeof window&&window.window===window?window:"object"==typeof self&&self.self===self?self:"object"==typeof global&&global.global===global?global:void 0,a=f.saveAs||("object"!=typeof window||window!==f?function(){}:"download"in HTMLAnchorElement.prototype?function(b,g,h){var i=f.URL||f.webkitURL,j=document.createElement("a");g=g||b.name||"download",j.download=g,j.rel="noopener","string"==typeof b?(j.href=b,j.origin===location.origin?e(j):d(j.href)?c(b,g,h):e(j,j.target="_blank")):(j.href=i.createObjectURL(b),setTimeout(function(){i.revokeObjectURL(j.href)},4E4),setTimeout(function(){e(j)},0))}:"msSaveOrOpenBlob"in navigator?function(f,g,h){if(g=g||f.name||"download","string"!=typeof f)navigator.msSaveOrOpenBlob(b(f,h),g);else if(d(f))c(f,g,h);else{var i=document.createElement("a");i.href=f,i.target="_blank",setTimeout(function(){e(i)})}}:function(a,b,d,e){if(e=e||open("","_blank"),e&&(e.document.title=e.document.body.innerText="downloading..."),"string"==typeof a)return c(a,b,d);var g="application/octet-stream"===a.type,h=/constructor/i.test(f.HTMLElement)||f.safari,i=/CriOS\/[\d]+/.test(navigator.userAgent);if((i||g&&h)&&"object"==typeof FileReader){var j=new FileReader;j.onloadend=function(){var a=j.result;a=i?a:a.replace(/^data:[^;]*;/,"data:attachment/file;"),e?e.location.href=a:location=a,e=null},j.readAsDataURL(a)}else{var k=f.URL||f.webkitURL,l=k.createObjectURL(a);e?e.location=l:location.href=l,e=null,setTimeout(function(){k.revokeObjectURL(l)},4E4)}});f.saveAs=a.saveAs=a,"undefined"!=typeof module&&(module.exports=a)});
//# sourceMappingURL=FileSaver.min.js.map
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+980
View File
@@ -0,0 +1,980 @@
ace.define(
"ace/mode/css_highlight_rules",
[
"require",
"exports",
"module",
"ace/lib/oop",
"ace/lib/lang",
"ace/mode/text_highlight_rules"
],
function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var lang = require("../lib/lang");
var TextHighlightRules = require("./text_highlight_rules")
.TextHighlightRules;
var supportType = (exports.supportType =
"align-content|align-items|align-self|all|animation|animation-delay|animation-direction|animation-duration|animation-fill-mode|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|backface-visibility|background|background-attachment|background-blend-mode|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|border|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|bottom|box-shadow|box-sizing|caption-side|clear|clip|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|cursor|direction|display|empty-cells|filter|flex|flex-basis|flex-direction|flex-flow|flex-grow|flex-shrink|flex-wrap|float|font|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|hanging-punctuation|height|justify-content|left|letter-spacing|line-height|list-style|list-style-image|list-style-position|list-style-type|margin|margin-bottom|margin-left|margin-right|margin-top|max-height|max-width|max-zoom|min-height|min-width|min-zoom|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|order|outline|outline-color|outline-offset|outline-style|outline-width|overflow|overflow-x|overflow-y|padding|padding-bottom|padding-left|padding-right|padding-top|page-break-after|page-break-before|page-break-inside|perspective|perspective-origin|position|quotes|resize|right|tab-size|table-layout|text-align|text-align-last|text-decoration|text-decoration-color|text-decoration-line|text-decoration-style|text-indent|text-justify|text-overflow|text-shadow|text-transform|top|transform|transform-origin|transform-style|transition|transition-delay|transition-duration|transition-property|transition-timing-function|unicode-bidi|user-select|user-zoom|vertical-align|visibility|white-space|width|word-break|word-spacing|word-wrap|z-index");
var supportFunction = (exports.supportFunction =
"rgb|rgba|url|attr|counter|counters");
var supportConstant = (exports.supportConstant =
"absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero|zoom");
var supportConstantColor = (exports.supportConstantColor =
"aliceblue|antiquewhite|aqua|aquamarine|azure|beige|bisque|black|blanchedalmond|blue|blueviolet|brown|burlywood|cadetblue|chartreuse|chocolate|coral|cornflowerblue|cornsilk|crimson|cyan|darkblue|darkcyan|darkgoldenrod|darkgray|darkgreen|darkgrey|darkkhaki|darkmagenta|darkolivegreen|darkorange|darkorchid|darkred|darksalmon|darkseagreen|darkslateblue|darkslategray|darkslategrey|darkturquoise|darkviolet|deeppink|deepskyblue|dimgray|dimgrey|dodgerblue|firebrick|floralwhite|forestgreen|fuchsia|gainsboro|ghostwhite|gold|goldenrod|gray|green|greenyellow|grey|honeydew|hotpink|indianred|indigo|ivory|khaki|lavender|lavenderblush|lawngreen|lemonchiffon|lightblue|lightcoral|lightcyan|lightgoldenrodyellow|lightgray|lightgreen|lightgrey|lightpink|lightsalmon|lightseagreen|lightskyblue|lightslategray|lightslategrey|lightsteelblue|lightyellow|lime|limegreen|linen|magenta|maroon|mediumaquamarine|mediumblue|mediumorchid|mediumpurple|mediumseagreen|mediumslateblue|mediumspringgreen|mediumturquoise|mediumvioletred|midnightblue|mintcream|mistyrose|moccasin|navajowhite|navy|oldlace|olive|olivedrab|orange|orangered|orchid|palegoldenrod|palegreen|paleturquoise|palevioletred|papayawhip|peachpuff|peru|pink|plum|powderblue|purple|rebeccapurple|red|rosybrown|royalblue|saddlebrown|salmon|sandybrown|seagreen|seashell|sienna|silver|skyblue|slateblue|slategray|slategrey|snow|springgreen|steelblue|tan|teal|thistle|tomato|turquoise|violet|wheat|white|whitesmoke|yellow|yellowgreen");
var supportConstantFonts = (exports.supportConstantFonts =
"arial|century|comic|courier|cursive|fantasy|garamond|georgia|helvetica|impact|lucida|symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|serif|monospace");
var numRe = (exports.numRe =
"\\-?(?:(?:[0-9]+(?:\\.[0-9]+)?)|(?:\\.[0-9]+))");
var pseudoElements = (exports.pseudoElements =
"(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b");
var pseudoClasses = (exports.pseudoClasses =
"(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b");
var CssHighlightRules = function() {
var keywordMapper = this.createKeywordMapper(
{
"support.function": supportFunction,
"support.constant": supportConstant,
"support.type": supportType,
"support.constant.color": supportConstantColor,
"support.constant.fonts": supportConstantFonts
},
"text",
true
);
this.$rules = {
start: [
{
include: ["strings", "url", "comments"]
},
{
token: "paren.lparen",
regex: "\\{",
next: "ruleset"
},
{
token: "paren.rparen",
regex: "\\}"
},
{
token: "string",
regex: "@(?!viewport)",
next: "media"
},
{
token: "keyword",
regex: "#[a-z0-9-_]+"
},
{
token: "keyword",
regex: "%"
},
{
token: "variable",
regex: "\\.[a-z0-9-_]+"
},
{
token: "string",
regex: ":[a-z0-9-_]+"
},
{
token: "constant.numeric",
regex: numRe
},
{
token: "constant",
regex: "[a-z0-9-_]+"
},
{
caseInsensitive: true
}
],
media: [
{
include: ["strings", "url", "comments"]
},
{
token: "paren.lparen",
regex: "\\{",
next: "start"
},
{
token: "paren.rparen",
regex: "\\}",
next: "start"
},
{
token: "string",
regex: ";",
next: "start"
},
{
token: "keyword",
regex:
"(?:media|supports|document|charset|import|namespace|media|supports|document" +
"|page|font|keyframes|viewport|counter-style|font-feature-values" +
"|swash|ornaments|annotation|stylistic|styleset|character-variant)"
}
],
comments: [
{
token: "comment", // multi line comment
regex: "\\/\\*",
push: [
{
token: "comment",
regex: "\\*\\/",
next: "pop"
},
{
defaultToken: "comment"
}
]
}
],
ruleset: [
{
regex: "-(webkit|ms|moz|o)-",
token: "text"
},
{
token: "punctuation.operator",
regex: "[:;]"
},
{
token: "paren.rparen",
regex: "\\}",
next: "start"
},
{
include: ["strings", "url", "comments"]
},
{
token: ["constant.numeric", "keyword"],
regex:
"(" +
numRe +
")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vmax|vmin|vm|vw|%)"
},
{
token: "constant.numeric",
regex: numRe
},
{
token: "constant.numeric", // hex6 color
regex: "#[a-f0-9]{6}"
},
{
token: "constant.numeric", // hex3 color
regex: "#[a-f0-9]{3}"
},
{
token: [
"punctuation",
"entity.other.attribute-name.pseudo-element.css"
],
regex: pseudoElements
},
{
token: [
"punctuation",
"entity.other.attribute-name.pseudo-class.css"
],
regex: pseudoClasses
},
{
include: "url"
},
{
token: keywordMapper,
regex: "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*"
},
{
caseInsensitive: true
}
],
url: [
{
token: "support.function",
regex: "(?:url(:?-prefix)?|domain|regexp)\\(",
push: [
{
token: "support.function",
regex: "\\)",
next: "pop"
},
{
defaultToken: "string"
}
]
}
],
strings: [
{
token: "string.start",
regex: "'",
push: [
{
token: "string.end",
regex: "'|$",
next: "pop"
},
{
include: "escapes"
},
{
token: "constant.language.escape",
regex: /\\$/,
consumeLineEnd: true
},
{
defaultToken: "string"
}
]
},
{
token: "string.start",
regex: '"',
push: [
{
token: "string.end",
regex: '"|$',
next: "pop"
},
{
include: "escapes"
},
{
token: "constant.language.escape",
regex: /\\$/,
consumeLineEnd: true
},
{
defaultToken: "string"
}
]
}
],
escapes: [
{
token: "constant.language.escape",
regex: /\\([a-fA-F\d]{1,6}|[^a-fA-F\d])/
}
]
};
this.normalizeRules();
};
oop.inherits(CssHighlightRules, TextHighlightRules);
exports.CssHighlightRules = CssHighlightRules;
}
);
ace.define(
"ace/mode/matching_brace_outdent",
["require", "exports", "module", "ace/range"],
function(require, exports, module) {
"use strict";
var Range = require("../range").Range;
var MatchingBraceOutdent = function() {};
(function() {
this.checkOutdent = function(line, input) {
if (!/^\s+$/.test(line)) return false;
return /^\s*\}/.test(input);
};
this.autoOutdent = function(doc, row) {
var line = doc.getLine(row);
var match = line.match(/^(\s*\})/);
if (!match) return 0;
var column = match[1].length;
var openBracePos = doc.findMatchingBracket({
row: row,
column: column
});
if (!openBracePos || openBracePos.row == row) return 0;
var indent = this.$getIndent(doc.getLine(openBracePos.row));
doc.replace(new Range(row, 0, row, column - 1), indent);
};
this.$getIndent = function(line) {
return line.match(/^\s*/)[0];
};
}.call(MatchingBraceOutdent.prototype));
exports.MatchingBraceOutdent = MatchingBraceOutdent;
}
);
ace.define(
"ace/mode/css_completions",
["require", "exports", "module"],
function(require, exports, module) {
"use strict";
var propertyMap = {
background: { "#$0": 1 },
"background-color": { "#$0": 1, transparent: 1, fixed: 1 },
"background-image": { "url('/$0')": 1 },
"background-repeat": {
repeat: 1,
"repeat-x": 1,
"repeat-y": 1,
"no-repeat": 1,
inherit: 1
},
"background-position": {
bottom: 2,
center: 2,
left: 2,
right: 2,
top: 2,
inherit: 2
},
"background-attachment": { scroll: 1, fixed: 1 },
"background-size": { cover: 1, contain: 1 },
"background-clip": {
"border-box": 1,
"padding-box": 1,
"content-box": 1
},
"background-origin": {
"border-box": 1,
"padding-box": 1,
"content-box": 1
},
border: { "solid $0": 1, "dashed $0": 1, "dotted $0": 1, "#$0": 1 },
"border-color": { "#$0": 1 },
"border-style": {
solid: 2,
dashed: 2,
dotted: 2,
double: 2,
groove: 2,
hidden: 2,
inherit: 2,
inset: 2,
none: 2,
outset: 2,
ridged: 2
},
"border-collapse": { collapse: 1, separate: 1 },
bottom: { px: 1, em: 1, "%": 1 },
clear: { left: 1, right: 1, both: 1, none: 1 },
color: { "#$0": 1, "rgb(#$00,0,0)": 1 },
cursor: {
default: 1,
pointer: 1,
move: 1,
text: 1,
wait: 1,
help: 1,
progress: 1,
"n-resize": 1,
"ne-resize": 1,
"e-resize": 1,
"se-resize": 1,
"s-resize": 1,
"sw-resize": 1,
"w-resize": 1,
"nw-resize": 1
},
display: {
none: 1,
block: 1,
inline: 1,
"inline-block": 1,
"table-cell": 1
},
"empty-cells": { show: 1, hide: 1 },
float: { left: 1, right: 1, none: 1 },
"font-family": {
Arial: 2,
"Comic Sans MS": 2,
Consolas: 2,
"Courier New": 2,
Courier: 2,
Georgia: 2,
Monospace: 2,
"Sans-Serif": 2,
"Segoe UI": 2,
Tahoma: 2,
"Times New Roman": 2,
"Trebuchet MS": 2,
Verdana: 1
},
"font-size": { px: 1, em: 1, "%": 1 },
"font-weight": { bold: 1, normal: 1 },
"font-style": { italic: 1, normal: 1 },
"font-variant": { normal: 1, "small-caps": 1 },
height: { px: 1, em: 1, "%": 1 },
left: { px: 1, em: 1, "%": 1 },
"letter-spacing": { normal: 1 },
"line-height": { normal: 1 },
"list-style-type": {
none: 1,
disc: 1,
circle: 1,
square: 1,
decimal: 1,
"decimal-leading-zero": 1,
"lower-roman": 1,
"upper-roman": 1,
"lower-greek": 1,
"lower-latin": 1,
"upper-latin": 1,
georgian: 1,
"lower-alpha": 1,
"upper-alpha": 1
},
margin: { px: 1, em: 1, "%": 1 },
"margin-right": { px: 1, em: 1, "%": 1 },
"margin-left": { px: 1, em: 1, "%": 1 },
"margin-top": { px: 1, em: 1, "%": 1 },
"margin-bottom": { px: 1, em: 1, "%": 1 },
"max-height": { px: 1, em: 1, "%": 1 },
"max-width": { px: 1, em: 1, "%": 1 },
"min-height": { px: 1, em: 1, "%": 1 },
"min-width": { px: 1, em: 1, "%": 1 },
overflow: { hidden: 1, visible: 1, auto: 1, scroll: 1 },
"overflow-x": { hidden: 1, visible: 1, auto: 1, scroll: 1 },
"overflow-y": { hidden: 1, visible: 1, auto: 1, scroll: 1 },
padding: { px: 1, em: 1, "%": 1 },
"padding-top": { px: 1, em: 1, "%": 1 },
"padding-right": { px: 1, em: 1, "%": 1 },
"padding-bottom": { px: 1, em: 1, "%": 1 },
"padding-left": { px: 1, em: 1, "%": 1 },
"page-break-after": { auto: 1, always: 1, avoid: 1, left: 1, right: 1 },
"page-break-before": { auto: 1, always: 1, avoid: 1, left: 1, right: 1 },
position: { absolute: 1, relative: 1, fixed: 1, static: 1 },
right: { px: 1, em: 1, "%": 1 },
"table-layout": { fixed: 1, auto: 1 },
"text-decoration": { none: 1, underline: 1, "line-through": 1, blink: 1 },
"text-align": { left: 1, right: 1, center: 1, justify: 1 },
"text-transform": { capitalize: 1, uppercase: 1, lowercase: 1, none: 1 },
top: { px: 1, em: 1, "%": 1 },
"vertical-align": { top: 1, bottom: 1 },
visibility: { hidden: 1, visible: 1 },
"white-space": {
nowrap: 1,
normal: 1,
pre: 1,
"pre-line": 1,
"pre-wrap": 1
},
width: { px: 1, em: 1, "%": 1 },
"word-spacing": { normal: 1 },
filter: { "alpha(opacity=$0100)": 1 },
"text-shadow": { "$02px 2px 2px #777": 1 },
"text-overflow": { "ellipsis-word": 1, clip: 1, ellipsis: 1 },
"-moz-border-radius": 1,
"-moz-border-radius-topright": 1,
"-moz-border-radius-bottomright": 1,
"-moz-border-radius-topleft": 1,
"-moz-border-radius-bottomleft": 1,
"-webkit-border-radius": 1,
"-webkit-border-top-right-radius": 1,
"-webkit-border-top-left-radius": 1,
"-webkit-border-bottom-right-radius": 1,
"-webkit-border-bottom-left-radius": 1,
"-moz-box-shadow": 1,
"-webkit-box-shadow": 1,
transform: { "rotate($00deg)": 1, "skew($00deg)": 1 },
"-moz-transform": { "rotate($00deg)": 1, "skew($00deg)": 1 },
"-webkit-transform": { "rotate($00deg)": 1, "skew($00deg)": 1 }
};
var CssCompletions = function() {};
(function() {
this.completionsDefined = false;
this.defineCompletions = function() {
if (document) {
var style = document.createElement("c").style;
for (var i in style) {
if (typeof style[i] !== "string") continue;
var name = i.replace(/[A-Z]/g, function(x) {
return "-" + x.toLowerCase();
});
if (!propertyMap.hasOwnProperty(name)) propertyMap[name] = 1;
}
}
this.completionsDefined = true;
};
this.getCompletions = function(state, session, pos, prefix) {
if (!this.completionsDefined) {
this.defineCompletions();
}
if (state === "ruleset" || session.$mode.$id == "ace/mode/scss") {
var line = session.getLine(pos.row).substr(0, pos.column);
if (/:[^;]+$/.test(line)) {
/([\w\-]+):[^:]*$/.test(line);
return this.getPropertyValueCompletions(
state,
session,
pos,
prefix
);
} else {
return this.getPropertyCompletions(state, session, pos, prefix);
}
}
return [];
};
this.getPropertyCompletions = function(state, session, pos, prefix) {
var properties = Object.keys(propertyMap);
return properties.map(function(property) {
return {
caption: property,
snippet: property + ": $0;",
meta: "property",
score: 1000000
};
});
};
this.getPropertyValueCompletions = function(state, session, pos, prefix) {
var line = session.getLine(pos.row).substr(0, pos.column);
var property = (/([\w\-]+):[^:]*$/.exec(line) || {})[1];
if (!property) return [];
var values = [];
if (
property in propertyMap &&
typeof propertyMap[property] === "object"
) {
values = Object.keys(propertyMap[property]);
}
return values.map(function(value) {
return {
caption: value,
snippet: value,
meta: "property value",
score: 1000000
};
});
};
}.call(CssCompletions.prototype));
exports.CssCompletions = CssCompletions;
}
);
ace.define(
"ace/mode/behaviour/css",
[
"require",
"exports",
"module",
"ace/lib/oop",
"ace/mode/behaviour",
"ace/mode/behaviour/cstyle",
"ace/token_iterator"
],
function(require, exports, module) {
"use strict";
var oop = require("../../lib/oop");
var Behaviour = require("../behaviour").Behaviour;
var CstyleBehaviour = require("./cstyle").CstyleBehaviour;
var TokenIterator = require("../../token_iterator").TokenIterator;
var CssBehaviour = function() {
this.inherit(CstyleBehaviour);
this.add("colon", "insertion", function(
state,
action,
editor,
session,
text
) {
if (text === ":" && editor.selection.isEmpty()) {
var cursor = editor.getCursorPosition();
var iterator = new TokenIterator(session, cursor.row, cursor.column);
var token = iterator.getCurrentToken();
if (token && token.value.match(/\s+/)) {
token = iterator.stepBackward();
}
if (token && token.type === "support.type") {
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar === ":") {
return {
text: "",
selection: [1, 1]
};
}
if (/^(\s+[^;]|\s*$)/.test(line.substring(cursor.column))) {
return {
text: ":;",
selection: [1, 1]
};
}
}
}
});
this.add("colon", "deletion", function(
state,
action,
editor,
session,
range
) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected === ":") {
var cursor = editor.getCursorPosition();
var iterator = new TokenIterator(session, cursor.row, cursor.column);
var token = iterator.getCurrentToken();
if (token && token.value.match(/\s+/)) {
token = iterator.stepBackward();
}
if (token && token.type === "support.type") {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(
range.end.column,
range.end.column + 1
);
if (rightChar === ";") {
range.end.column++;
return range;
}
}
}
});
this.add("semicolon", "insertion", function(
state,
action,
editor,
session,
text
) {
if (text === ";" && editor.selection.isEmpty()) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar === ";") {
return {
text: "",
selection: [1, 1]
};
}
}
});
this.add("!important", "insertion", function(
state,
action,
editor,
session,
text
) {
if (text === "!" && editor.selection.isEmpty()) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (/^\s*(;|}|$)/.test(line.substring(cursor.column))) {
return {
text: "!important",
selection: [10, 10]
};
}
}
});
};
oop.inherits(CssBehaviour, CstyleBehaviour);
exports.CssBehaviour = CssBehaviour;
}
);
ace.define(
"ace/mode/folding/cstyle",
[
"require",
"exports",
"module",
"ace/lib/oop",
"ace/range",
"ace/mode/folding/fold_mode"
],
function(require, exports, module) {
"use strict";
var oop = require("../../lib/oop");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;
var FoldMode = (exports.FoldMode = function(commentRegex) {
if (commentRegex) {
this.foldingStartMarker = new RegExp(
this.foldingStartMarker.source.replace(
/\|[^|]*?$/,
"|" + commentRegex.start
)
);
this.foldingStopMarker = new RegExp(
this.foldingStopMarker.source.replace(
/\|[^|]*?$/,
"|" + commentRegex.end
)
);
}
});
oop.inherits(FoldMode, BaseFoldMode);
(function() {
this.foldingStartMarker = /([\{\[\(])[^\}\]\)]*$|^\s*(\/\*)/;
this.foldingStopMarker = /^[^\[\{\(]*([\}\]\)])|^[\s\*]*(\*\/)/;
this.singleLineBlockCommentRe = /^\s*(\/\*).*\*\/\s*$/;
this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/;
this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/;
this._getFoldWidgetBase = this.getFoldWidget;
this.getFoldWidget = function(session, foldStyle, row) {
var line = session.getLine(row);
if (this.singleLineBlockCommentRe.test(line)) {
if (
!this.startRegionRe.test(line) &&
!this.tripleStarBlockCommentRe.test(line)
)
return "";
}
var fw = this._getFoldWidgetBase(session, foldStyle, row);
if (!fw && this.startRegionRe.test(line)) return "start"; // lineCommentRegionStart
return fw;
};
this.getFoldWidgetRange = function(
session,
foldStyle,
row,
forceMultiline
) {
var line = session.getLine(row);
if (this.startRegionRe.test(line))
return this.getCommentRegionBlock(session, line, row);
var match = line.match(this.foldingStartMarker);
if (match) {
var i = match.index;
if (match[1])
return this.openingBracketBlock(session, match[1], row, i);
var range = session.getCommentFoldRange(row, i + match[0].length, 1);
if (range && !range.isMultiLine()) {
if (forceMultiline) {
range = this.getSectionRange(session, row);
} else if (foldStyle != "all") range = null;
}
return range;
}
if (foldStyle === "markbegin") return;
var match = line.match(this.foldingStopMarker);
if (match) {
var i = match.index + match[0].length;
if (match[1])
return this.closingBracketBlock(session, match[1], row, i);
return session.getCommentFoldRange(row, i, -1);
}
};
this.getSectionRange = function(session, row) {
var line = session.getLine(row);
var startIndent = line.search(/\S/);
var startRow = row;
var startColumn = line.length;
row = row + 1;
var endRow = row;
var maxRow = session.getLength();
while (++row < maxRow) {
line = session.getLine(row);
var indent = line.search(/\S/);
if (indent === -1) continue;
if (startIndent > indent) break;
var subRange = this.getFoldWidgetRange(session, "all", row);
if (subRange) {
if (subRange.start.row <= startRow) {
break;
} else if (subRange.isMultiLine()) {
row = subRange.end.row;
} else if (startIndent == indent) {
break;
}
}
endRow = row;
}
return new Range(
startRow,
startColumn,
endRow,
session.getLine(endRow).length
);
};
this.getCommentRegionBlock = function(session, line, row) {
var startColumn = line.search(/\s*$/);
var maxRow = session.getLength();
var startRow = row;
var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/;
var depth = 1;
while (++row < maxRow) {
line = session.getLine(row);
var m = re.exec(line);
if (!m) continue;
if (m[1]) depth--;
else depth++;
if (!depth) break;
}
var endRow = row;
if (endRow > startRow) {
return new Range(startRow, startColumn, endRow, line.length);
}
};
}.call(FoldMode.prototype));
}
);
ace.define(
"ace/mode/css",
[
"require",
"exports",
"module",
"ace/lib/oop",
"ace/mode/text",
"ace/mode/css_highlight_rules",
"ace/mode/matching_brace_outdent",
"ace/worker/worker_client",
"ace/mode/css_completions",
"ace/mode/behaviour/css",
"ace/mode/folding/cstyle"
],
function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules;
var MatchingBraceOutdent = require("./matching_brace_outdent")
.MatchingBraceOutdent;
var WorkerClient = require("../worker/worker_client").WorkerClient;
var CssCompletions = require("./css_completions").CssCompletions;
var CssBehaviour = require("./behaviour/css").CssBehaviour;
var CStyleFoldMode = require("./folding/cstyle").FoldMode;
var Mode = function() {
this.HighlightRules = CssHighlightRules;
this.$outdent = new MatchingBraceOutdent();
this.$behaviour = new CssBehaviour();
this.$completer = new CssCompletions();
this.foldingRules = new CStyleFoldMode();
};
oop.inherits(Mode, TextMode);
(function() {
this.foldingRules = "cStyle";
this.blockComment = { start: "/*", end: "*/" };
this.getNextLineIndent = function(state, line, tab) {
var indent = this.$getIndent(line);
var tokens = this.getTokenizer().getLineTokens(line, state).tokens;
if (tokens.length && tokens[tokens.length - 1].type == "comment") {
return indent;
}
var match = line.match(/^.*\{\s*$/);
if (match) {
indent += tab;
}
return indent;
};
this.checkOutdent = function(state, line, input) {
return this.$outdent.checkOutdent(line, input);
};
this.autoOutdent = function(state, doc, row) {
this.$outdent.autoOutdent(doc, row);
};
this.getCompletions = function(state, session, pos, prefix) {
return this.$completer.getCompletions(state, session, pos, prefix);
};
this.createWorker = function(session) {
var worker = new WorkerClient(["ace"], "ace/mode/css_worker", "Worker");
worker.attachToDocument(session.getDocument());
worker.on("annotate", function(e) {
session.setAnnotations(e.data);
});
worker.on("terminate", function() {
session.clearAnnotations();
});
return worker;
};
this.$id = "ace/mode/css";
}.call(Mode.prototype));
exports.Mode = Mode;
}
);
(function() {
ace.require(["ace/mode/css"], function(m) {
if (typeof module == "object" && typeof exports == "object" && module) {
module.exports = m;
}
});
})();
File diff suppressed because it is too large Load Diff
+820
View File
@@ -0,0 +1,820 @@
ace.define(
"ace/mode/xml_highlight_rules",
[
"require",
"exports",
"module",
"ace/lib/oop",
"ace/mode/text_highlight_rules"
],
function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules")
.TextHighlightRules;
var XmlHighlightRules = function(normalize) {
var tagRegex = "[_:a-zA-Z\xc0-\uffff][-_:.a-zA-Z0-9\xc0-\uffff]*";
this.$rules = {
start: [
{
token: "string.cdata.xml",
regex: "<\\!\\[CDATA\\[",
next: "cdata"
},
{
token: ["punctuation.instruction.xml", "keyword.instruction.xml"],
regex: "(<\\?)(" + tagRegex + ")",
next: "processing_instruction"
},
{ token: "comment.start.xml", regex: "<\\!--", next: "comment" },
{
token: ["xml-pe.doctype.xml", "xml-pe.doctype.xml"],
regex: "(<\\!)(DOCTYPE)(?=[\\s])",
next: "doctype",
caseInsensitive: true
},
{ include: "tag" },
{ token: "text.end-tag-open.xml", regex: "</" },
{ token: "text.tag-open.xml", regex: "<" },
{ include: "reference" },
{ defaultToken: "text.xml" }
],
processing_instruction: [
{
token: "entity.other.attribute-name.decl-attribute-name.xml",
regex: tagRegex
},
{
token: "keyword.operator.decl-attribute-equals.xml",
regex: "="
},
{
include: "whitespace"
},
{
include: "string"
},
{
token: "punctuation.xml-decl.xml",
regex: "\\?>",
next: "start"
}
],
doctype: [
{ include: "whitespace" },
{ include: "string" },
{ token: "xml-pe.doctype.xml", regex: ">", next: "start" },
{ token: "xml-pe.xml", regex: "[-_a-zA-Z0-9:]+" },
{ token: "punctuation.int-subset", regex: "\\[", push: "int_subset" }
],
int_subset: [
{
token: "text.xml",
regex: "\\s+"
},
{
token: "punctuation.int-subset.xml",
regex: "]",
next: "pop"
},
{
token: ["punctuation.markup-decl.xml", "keyword.markup-decl.xml"],
regex: "(<\\!)(" + tagRegex + ")",
push: [
{
token: "text",
regex: "\\s+"
},
{
token: "punctuation.markup-decl.xml",
regex: ">",
next: "pop"
},
{ include: "string" }
]
}
],
cdata: [
{ token: "string.cdata.xml", regex: "\\]\\]>", next: "start" },
{ token: "text.xml", regex: "\\s+" },
{ token: "text.xml", regex: "(?:[^\\]]|\\](?!\\]>))+" }
],
comment: [
{ token: "comment.end.xml", regex: "-->", next: "start" },
{ defaultToken: "comment.xml" }
],
reference: [
{
token: "constant.language.escape.reference.xml",
regex: "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)"
}
],
attr_reference: [
{
token: "constant.language.escape.reference.attribute-value.xml",
regex: "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)"
}
],
tag: [
{
token: [
"meta.tag.punctuation.tag-open.xml",
"meta.tag.punctuation.end-tag-open.xml",
"meta.tag.tag-name.xml"
],
regex: "(?:(<)|(</))((?:" + tagRegex + ":)?" + tagRegex + ")",
next: [
{ include: "attributes" },
{
token: "meta.tag.punctuation.tag-close.xml",
regex: "/?>",
next: "start"
}
]
}
],
tag_whitespace: [{ token: "text.tag-whitespace.xml", regex: "\\s+" }],
whitespace: [{ token: "text.whitespace.xml", regex: "\\s+" }],
string: [
{
token: "string.xml",
regex: "'",
push: [
{ token: "string.xml", regex: "'", next: "pop" },
{ defaultToken: "string.xml" }
]
},
{
token: "string.xml",
regex: '"',
push: [
{ token: "string.xml", regex: '"', next: "pop" },
{ defaultToken: "string.xml" }
]
}
],
attributes: [
{
token: "entity.other.attribute-name.xml",
regex: tagRegex
},
{
token: "keyword.operator.attribute-equals.xml",
regex: "="
},
{
include: "tag_whitespace"
},
{
include: "attribute_value"
}
],
attribute_value: [
{
token: "string.attribute-value.xml",
regex: "'",
push: [
{ token: "string.attribute-value.xml", regex: "'", next: "pop" },
{ include: "attr_reference" },
{ defaultToken: "string.attribute-value.xml" }
]
},
{
token: "string.attribute-value.xml",
regex: '"',
push: [
{ token: "string.attribute-value.xml", regex: '"', next: "pop" },
{ include: "attr_reference" },
{ defaultToken: "string.attribute-value.xml" }
]
}
]
};
if (this.constructor === XmlHighlightRules) this.normalizeRules();
};
(function() {
this.embedTagRules = function(HighlightRules, prefix, tag) {
this.$rules.tag.unshift({
token: [
"meta.tag.punctuation.tag-open.xml",
"meta.tag." + tag + ".tag-name.xml"
],
regex: "(<)(" + tag + "(?=\\s|>|$))",
next: [
{ include: "attributes" },
{
token: "meta.tag.punctuation.tag-close.xml",
regex: "/?>",
next: prefix + "start"
}
]
});
this.$rules[tag + "-end"] = [
{ include: "attributes" },
{
token: "meta.tag.punctuation.tag-close.xml",
regex: "/?>",
next: "start",
onMatch: function(value, currentState, stack) {
stack.splice(0);
return this.token;
}
}
];
this.embedRules(HighlightRules, prefix, [
{
token: [
"meta.tag.punctuation.end-tag-open.xml",
"meta.tag." + tag + ".tag-name.xml"
],
regex: "(</)(" + tag + "(?=\\s|>|$))",
next: tag + "-end"
},
{
token: "string.cdata.xml",
regex: "<\\!\\[CDATA\\["
},
{
token: "string.cdata.xml",
regex: "\\]\\]>"
}
]);
};
}.call(TextHighlightRules.prototype));
oop.inherits(XmlHighlightRules, TextHighlightRules);
exports.XmlHighlightRules = XmlHighlightRules;
}
);
ace.define(
"ace/mode/behaviour/xml",
[
"require",
"exports",
"module",
"ace/lib/oop",
"ace/mode/behaviour",
"ace/token_iterator",
"ace/lib/lang"
],
function(require, exports, module) {
"use strict";
var oop = require("../../lib/oop");
var Behaviour = require("../behaviour").Behaviour;
var TokenIterator = require("../../token_iterator").TokenIterator;
var lang = require("../../lib/lang");
function is(token, type) {
return token && token.type.lastIndexOf(type + ".xml") > -1;
}
var XmlBehaviour = function() {
this.add("string_dquotes", "insertion", function(
state,
action,
editor,
session,
text
) {
if (text == '"' || text == "'") {
var quote = text;
var selected = session.doc.getTextRange(editor.getSelectionRange());
if (
selected !== "" &&
selected !== "'" &&
selected != '"' &&
editor.getWrapBehavioursEnabled()
) {
return {
text: quote + selected + quote,
selection: false
};
}
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
var iterator = new TokenIterator(session, cursor.row, cursor.column);
var token = iterator.getCurrentToken();
if (
rightChar == quote &&
(is(token, "attribute-value") || is(token, "string"))
) {
return {
text: "",
selection: [1, 1]
};
}
if (!token) token = iterator.stepBackward();
if (!token) return;
while (is(token, "tag-whitespace") || is(token, "whitespace")) {
token = iterator.stepBackward();
}
var rightSpace = !rightChar || rightChar.match(/\s/);
if (
(is(token, "attribute-equals") &&
(rightSpace || rightChar == ">")) ||
(is(token, "decl-attribute-equals") &&
(rightSpace || rightChar == "?"))
) {
return {
text: quote + quote,
selection: [1, 1]
};
}
}
});
this.add("string_dquotes", "deletion", function(
state,
action,
editor,
session,
range
) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && (selected == '"' || selected == "'")) {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(
range.start.column + 1,
range.start.column + 2
);
if (rightChar == selected) {
range.end.column++;
return range;
}
}
});
this.add("autoclosing", "insertion", function(
state,
action,
editor,
session,
text
) {
if (text == ">") {
var position = editor.getSelectionRange().start;
var iterator = new TokenIterator(
session,
position.row,
position.column
);
var token = iterator.getCurrentToken() || iterator.stepBackward();
if (
!token ||
!(
is(token, "tag-name") ||
is(token, "tag-whitespace") ||
is(token, "attribute-name") ||
is(token, "attribute-equals") ||
is(token, "attribute-value")
)
)
return;
if (is(token, "reference.attribute-value")) return;
if (is(token, "attribute-value")) {
var tokenEndColumn =
iterator.getCurrentTokenColumn() + token.value.length;
if (position.column < tokenEndColumn) return;
if (position.column == tokenEndColumn) {
var nextToken = iterator.stepForward();
if (nextToken && is(nextToken, "attribute-value")) return;
iterator.stepBackward();
}
}
if (
/^\s*>/.test(session.getLine(position.row).slice(position.column))
)
return;
while (!is(token, "tag-name")) {
token = iterator.stepBackward();
if (token.value == "<") {
token = iterator.stepForward();
break;
}
}
var tokenRow = iterator.getCurrentTokenRow();
var tokenColumn = iterator.getCurrentTokenColumn();
if (is(iterator.stepBackward(), "end-tag-open")) return;
var element = token.value;
if (tokenRow == position.row)
element = element.substring(0, position.column - tokenColumn);
if (this.voidElements.hasOwnProperty(element.toLowerCase())) return;
return {
text: ">" + "</" + element + ">",
selection: [1, 1]
};
}
});
this.add("autoindent", "insertion", function(
state,
action,
editor,
session,
text
) {
if (text == "\n") {
var cursor = editor.getCursorPosition();
var line = session.getLine(cursor.row);
var iterator = new TokenIterator(session, cursor.row, cursor.column);
var token = iterator.getCurrentToken();
if (token && token.type.indexOf("tag-close") !== -1) {
if (token.value == "/>") return;
while (token && token.type.indexOf("tag-name") === -1) {
token = iterator.stepBackward();
}
if (!token) {
return;
}
var tag = token.value;
var row = iterator.getCurrentTokenRow();
token = iterator.stepBackward();
if (!token || token.type.indexOf("end-tag") !== -1) {
return;
}
if (this.voidElements && !this.voidElements[tag]) {
var nextToken = session.getTokenAt(cursor.row, cursor.column + 1);
var line = session.getLine(row);
var nextIndent = this.$getIndent(line);
var indent = nextIndent + session.getTabString();
if (nextToken && nextToken.value === "</") {
return {
text: "\n" + indent + "\n" + nextIndent,
selection: [1, indent.length, 1, indent.length]
};
} else {
return {
text: "\n" + indent
};
}
}
}
}
});
};
oop.inherits(XmlBehaviour, Behaviour);
exports.XmlBehaviour = XmlBehaviour;
}
);
ace.define(
"ace/mode/folding/xml",
[
"require",
"exports",
"module",
"ace/lib/oop",
"ace/lib/lang",
"ace/range",
"ace/mode/folding/fold_mode",
"ace/token_iterator"
],
function(require, exports, module) {
"use strict";
var oop = require("../../lib/oop");
var lang = require("../../lib/lang");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;
var TokenIterator = require("../../token_iterator").TokenIterator;
var FoldMode = (exports.FoldMode = function(voidElements, optionalEndTags) {
BaseFoldMode.call(this);
this.voidElements = voidElements || {};
this.optionalEndTags = oop.mixin({}, this.voidElements);
if (optionalEndTags) oop.mixin(this.optionalEndTags, optionalEndTags);
});
oop.inherits(FoldMode, BaseFoldMode);
var Tag = function() {
this.tagName = "";
this.closing = false;
this.selfClosing = false;
this.start = { row: 0, column: 0 };
this.end = { row: 0, column: 0 };
};
function is(token, type) {
return token.type.lastIndexOf(type + ".xml") > -1;
}
(function() {
this.getFoldWidget = function(session, foldStyle, row) {
var tag = this._getFirstTagInLine(session, row);
if (!tag) return this.getCommentFoldWidget(session, row);
if (tag.closing || (!tag.tagName && tag.selfClosing))
return foldStyle == "markbeginend" ? "end" : "";
if (
!tag.tagName ||
tag.selfClosing ||
this.voidElements.hasOwnProperty(tag.tagName.toLowerCase())
)
return "";
if (this._findEndTagInLine(session, row, tag.tagName, tag.end.column))
return "";
return "start";
};
this.getCommentFoldWidget = function(session, row) {
if (
/comment/.test(session.getState(row)) &&
/<!-/.test(session.getLine(row))
)
return "start";
return "";
};
this._getFirstTagInLine = function(session, row) {
var tokens = session.getTokens(row);
var tag = new Tag();
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (is(token, "tag-open")) {
tag.end.column = tag.start.column + token.value.length;
tag.closing = is(token, "end-tag-open");
token = tokens[++i];
if (!token) return null;
tag.tagName = token.value;
tag.end.column += token.value.length;
for (i++; i < tokens.length; i++) {
token = tokens[i];
tag.end.column += token.value.length;
if (is(token, "tag-close")) {
tag.selfClosing = token.value == "/>";
break;
}
}
return tag;
} else if (is(token, "tag-close")) {
tag.selfClosing = token.value == "/>";
return tag;
}
tag.start.column += token.value.length;
}
return null;
};
this._findEndTagInLine = function(session, row, tagName, startColumn) {
var tokens = session.getTokens(row);
var column = 0;
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
column += token.value.length;
if (column < startColumn) continue;
if (is(token, "end-tag-open")) {
token = tokens[i + 1];
if (token && token.value == tagName) return true;
}
}
return false;
};
this._readTagForward = function(iterator) {
var token = iterator.getCurrentToken();
if (!token) return null;
var tag = new Tag();
do {
if (is(token, "tag-open")) {
tag.closing = is(token, "end-tag-open");
tag.start.row = iterator.getCurrentTokenRow();
tag.start.column = iterator.getCurrentTokenColumn();
} else if (is(token, "tag-name")) {
tag.tagName = token.value;
} else if (is(token, "tag-close")) {
tag.selfClosing = token.value == "/>";
tag.end.row = iterator.getCurrentTokenRow();
tag.end.column =
iterator.getCurrentTokenColumn() + token.value.length;
iterator.stepForward();
return tag;
}
} while ((token = iterator.stepForward()));
return null;
};
this._readTagBackward = function(iterator) {
var token = iterator.getCurrentToken();
if (!token) return null;
var tag = new Tag();
do {
if (is(token, "tag-open")) {
tag.closing = is(token, "end-tag-open");
tag.start.row = iterator.getCurrentTokenRow();
tag.start.column = iterator.getCurrentTokenColumn();
iterator.stepBackward();
return tag;
} else if (is(token, "tag-name")) {
tag.tagName = token.value;
} else if (is(token, "tag-close")) {
tag.selfClosing = token.value == "/>";
tag.end.row = iterator.getCurrentTokenRow();
tag.end.column =
iterator.getCurrentTokenColumn() + token.value.length;
}
} while ((token = iterator.stepBackward()));
return null;
};
this._pop = function(stack, tag) {
while (stack.length) {
var top = stack[stack.length - 1];
if (!tag || top.tagName == tag.tagName) {
return stack.pop();
} else if (this.optionalEndTags.hasOwnProperty(top.tagName)) {
stack.pop();
continue;
} else {
return null;
}
}
};
this.getFoldWidgetRange = function(session, foldStyle, row) {
var firstTag = this._getFirstTagInLine(session, row);
if (!firstTag) {
return (
this.getCommentFoldWidget(session, row) &&
session.getCommentFoldRange(row, session.getLine(row).length)
);
}
var isBackward = firstTag.closing || firstTag.selfClosing;
var stack = [];
var tag;
if (!isBackward) {
var iterator = new TokenIterator(session, row, firstTag.start.column);
var start = {
row: row,
column: firstTag.start.column + firstTag.tagName.length + 2
};
if (firstTag.start.row == firstTag.end.row)
start.column = firstTag.end.column;
while ((tag = this._readTagForward(iterator))) {
if (tag.selfClosing) {
if (!stack.length) {
tag.start.column += tag.tagName.length + 2;
tag.end.column -= 2;
return Range.fromPoints(tag.start, tag.end);
} else continue;
}
if (tag.closing) {
this._pop(stack, tag);
if (stack.length == 0) return Range.fromPoints(start, tag.start);
} else {
stack.push(tag);
}
}
} else {
var iterator = new TokenIterator(session, row, firstTag.end.column);
var end = {
row: row,
column: firstTag.start.column
};
while ((tag = this._readTagBackward(iterator))) {
if (tag.selfClosing) {
if (!stack.length) {
tag.start.column += tag.tagName.length + 2;
tag.end.column -= 2;
return Range.fromPoints(tag.start, tag.end);
} else continue;
}
if (!tag.closing) {
this._pop(stack, tag);
if (stack.length == 0) {
tag.start.column += tag.tagName.length + 2;
if (
tag.start.row == tag.end.row &&
tag.start.column < tag.end.column
)
tag.start.column = tag.end.column;
return Range.fromPoints(tag.start, end);
}
} else {
stack.push(tag);
}
}
}
};
}.call(FoldMode.prototype));
}
);
ace.define(
"ace/mode/xml",
[
"require",
"exports",
"module",
"ace/lib/oop",
"ace/lib/lang",
"ace/mode/text",
"ace/mode/xml_highlight_rules",
"ace/mode/behaviour/xml",
"ace/mode/folding/xml",
"ace/worker/worker_client"
],
function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var lang = require("../lib/lang");
var TextMode = require("./text").Mode;
var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules;
var XmlBehaviour = require("./behaviour/xml").XmlBehaviour;
var XmlFoldMode = require("./folding/xml").FoldMode;
var WorkerClient = require("../worker/worker_client").WorkerClient;
var Mode = function() {
this.HighlightRules = XmlHighlightRules;
this.$behaviour = new XmlBehaviour();
this.foldingRules = new XmlFoldMode();
};
oop.inherits(Mode, TextMode);
(function() {
this.voidElements = lang.arrayToMap([]);
this.blockComment = { start: "<!--", end: "-->" };
this.createWorker = function(session) {
var worker = new WorkerClient(["ace"], "ace/mode/xml_worker", "Worker");
worker.attachToDocument(session.getDocument());
worker.on("error", function(e) {
session.setAnnotations(e.data);
});
worker.on("terminate", function() {
session.clearAnnotations();
});
return worker;
};
this.$id = "ace/mode/xml";
}.call(Mode.prototype));
exports.Mode = Mode;
}
);
(function() {
ace.require(["ace/mode/xml"], function(m) {
if (typeof module == "object" && typeof exports == "object" && module) {
module.exports = m;
}
});
})();
+116
View File
@@ -0,0 +1,116 @@
ace.define(
"ace/theme/monokai",
["require", "exports", "module", "ace/lib/dom"],
function(require, exports, module) {
exports.isDark = true;
exports.cssClass = "ace-monokai";
exports.cssText =
".ace-monokai .ace_gutter {\
background: #2F3129;\
color: #8F908A\
}\
.ace-monokai .ace_print-margin {\
width: 1px;\
background: #555651\
}\
.ace-monokai {\
background-color: #272822;\
color: #F8F8F2\
}\
.ace-monokai .ace_cursor {\
color: #F8F8F0\
}\
.ace-monokai .ace_marker-layer .ace_selection {\
background: #49483E\
}\
.ace-monokai.ace_multiselect .ace_selection.ace_start {\
box-shadow: 0 0 3px 0px #272822;\
}\
.ace-monokai .ace_marker-layer .ace_step {\
background: rgb(102, 82, 0)\
}\
.ace-monokai .ace_marker-layer .ace_bracket {\
margin: -1px 0 0 -1px;\
border: 1px solid #49483E\
}\
.ace-monokai .ace_marker-layer .ace_active-line {\
background: #202020\
}\
.ace-monokai .ace_gutter-active-line {\
background-color: #272727\
}\
.ace-monokai .ace_marker-layer .ace_selected-word {\
border: 1px solid #49483E\
}\
.ace-monokai .ace_invisible {\
color: #52524d\
}\
.ace-monokai .ace_entity.ace_name.ace_tag,\
.ace-monokai .ace_keyword,\
.ace-monokai .ace_meta.ace_tag,\
.ace-monokai .ace_storage {\
color: #F92672\
}\
.ace-monokai .ace_punctuation,\
.ace-monokai .ace_punctuation.ace_tag {\
color: #fff\
}\
.ace-monokai .ace_constant.ace_character,\
.ace-monokai .ace_constant.ace_language,\
.ace-monokai .ace_constant.ace_numeric,\
.ace-monokai .ace_constant.ace_other {\
color: #AE81FF\
}\
.ace-monokai .ace_invalid {\
color: #F8F8F0;\
background-color: #F92672\
}\
.ace-monokai .ace_invalid.ace_deprecated {\
color: #F8F8F0;\
background-color: #AE81FF\
}\
.ace-monokai .ace_support.ace_constant,\
.ace-monokai .ace_support.ace_function {\
color: #66D9EF\
}\
.ace-monokai .ace_fold {\
background-color: #A6E22E;\
border-color: #F8F8F2\
}\
.ace-monokai .ace_storage.ace_type,\
.ace-monokai .ace_support.ace_class,\
.ace-monokai .ace_support.ace_type {\
font-style: italic;\
color: #66D9EF\
}\
.ace-monokai .ace_entity.ace_name.ace_function,\
.ace-monokai .ace_entity.ace_other,\
.ace-monokai .ace_entity.ace_other.ace_attribute-name,\
.ace-monokai .ace_variable {\
color: #A6E22E\
}\
.ace-monokai .ace_variable.ace_parameter {\
font-style: italic;\
color: #FD971F\
}\
.ace-monokai .ace_string {\
color: #E6DB74\
}\
.ace-monokai .ace_comment {\
color: #75715E\
}\
.ace-monokai .ace_indent-guide {\
background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWPQ0FD0ZXBzd/wPAAjVAoxeSgNeAAAAAElFTkSuQmCC) right repeat-y\
}";
var dom = require("../lib/dom");
dom.importCssString(exports.cssText, exports.cssClass);
}
);
(function() {
ace.require(["ace/theme/monokai"], function(m) {
if (typeof module == "object" && typeof exports == "object" && module) {
module.exports = m;
}
});
})();
File diff suppressed because it is too large Load Diff
+194
View File
@@ -0,0 +1,194 @@
/* GENERIC STUFF ****************************************/
html,
body {
height: 100%;
font-family: Roboto, -apple-system, BlinkMacSystemFont, "Segoe UI", Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
}
body {
margin: 0;
}
.btn {
cursor: pointer;
padding: 5px;
margin: 5px;
}
/* APPLICATION ROOT ****************************************/
.playground {
display: grid;
height: 100%;
width: 100%;
grid-template-columns: auto 8px 1fr;
}
/* LEFT BAR ****************************************/
.left-bar {
display: flex;
flex-direction: column;
background-color: #2f3129;
}
.left-bar.split {
grid-template-rows: 50px 60% 23px 30%;
}
.menubar {
background-color: #1c2128;
color: white;
font-size: 18px;
display: flex;
flex: 0 0 50px;
flex-direction: row-reverse;
align-items: center;
user-select: none;
}
.menubar select {
margin: 10px;
font-size: 16px;
height: 25px;
}
.run-code {
margin-right: 12px;
height: 25px;
border: 2px solid transparent;
opacity: 0.9;
}
.run-code:hover {
opacity: 1;
}
.flash {
background-position: center;
transition: background 0.5s;
}
.flash:active {
background-color: #41454a;
background-size: 100%;
transition: background 0s;
}
.layout-selector {
cursor: pointer;
padding: 5px;
margin: 5px;
}
.share-code {
position: relative;
}
.copied-notification {
font-size: x-small;
position: absolute;
bottom: -5px;
white-space: nowrap;
left: 50%;
transform: translateX(-50%);
}
/* TABBED EDITOR ****************************************/
.tabbed-editor {
flex: 2 2 auto;
position: relative;
}
.separator.horizontal + .tabbed-editor {
flex: 1 1 auto;
}
.tabBar {
color: white;
height: 22px;
margin-top: -22px;
padding-left: 5px;
user-select: none;
width: 170px;
}
.tabBar.resizeable {
cursor: row-resize;
width: 100%;
}
.tab {
display: inline-block;
cursor: pointer;
padding: 0 8px;
font-size: 16px;
line-height: 20px;
width: 34px;
text-align: center;
border-bottom: 2px solid transparent;
text-transform: uppercase;
}
.tab.active {
border-bottom: 2px solid gray;
}
.code-editor {
margin-top: 8px;
height: calc(100% - 10px);
}
/* SEPARATOR ****************************************/
.separator {
background-color: #1c2128;
cursor: col-resize;
}
.separator.horizontal {
height: 20px;
}
/* RIGHT PANE ****************************************/
.right-pane {
background-color: bisque;
overflow: hidden;
}
.right-pane iframe {
background-color: white;
width: 100%;
height: 100%;
border: 0;
}
.right-pane iframe.disabled {
pointer-events: none;
}
.content {
height: 100%;
}
.right-pane .welcome {
text-align: center;
font-size: 30px;
color: gray;
margin-top: 50px;
}
.right-pane .url {
font-size: 20px;
margin-top: 20px;
}
.url a {
color: gray;
}
.right-pane .note {
font-size: 18px;
text-align: left;
margin-top: 20px;
padding: 5%;
}
+404
View File
@@ -0,0 +1,404 @@
import { debounce, loadJS } from "./utils.js";
import {
App,
Component,
useState,
useRef,
onMounted,
onWillUnmount,
onPatched,
onWillUpdateProps,
loadFile as _loadFile,
whenReady,
__info__,
useEffect,
onWillStart,
} from "../owl.js";
//------------------------------------------------------------------------------
// Constants, helpers, utils
//------------------------------------------------------------------------------
const MODES = {
js: "ace/mode/javascript",
css: "ace/mode/css",
xml: "ace/mode/xml"
};
const DEFAULT_XML = `<templates>
</templates>`;
// Memoize loadFile so that samples aren't reloaded whenever a sample is selected
const fileCache = {};
const loadFile = (path) => {
if (!(path in fileCache)) {
fileCache[path] = _loadFile(path);
}
return fileCache[path];
}
/**
* Make an iframe, with all the js, css and xml properly injected.
*/
function makeCodeIframe(js, css, xml) {
// escape backticks in the xml so they don't close the template string
const escapedXml = xml.replace(/`/g, '\\\`');
const iframe = document.createElement("iframe");
iframe.onload = () => {
const doc = iframe.contentDocument;
const importMap = doc.createElement("script");
importMap.type = "importmap";
importMap.textContent = `{ "imports": { "@odoo/owl": "../owl.js" } }`;
doc.head.appendChild(importMap);
const script = doc.createElement("script");
script.type = "module";
script.textContent = `const TEMPLATES = \`${escapedXml}\`\n${js}`;
doc.body.appendChild(script);
const style = document.createElement("style");
style.innerText = css;
doc.head.appendChild(style);
};
return iframe;
}
//------------------------------------------------------------------------------
// SAMPLES
//------------------------------------------------------------------------------
const SAMPLES = [
{
description: "Components",
folder: "components",
code: ["js", "xml", "css"],
},
{
description: "Form Input Bindings",
folder: "form",
code: ["js", "xml"],
},
{
description: "Inline templates",
folder: "single_file_component",
code: ["js"],
},
{
description: "Lifecycle demo",
folder: "lifecycle_demo",
code: ["js", "xml", "css"],
},
{
description: "Customized hook",
folder: "custom_hooks",
code: ["js", "xml", "css"],
},
{
description: "Todo List App (with reactivity)",
folder: "todo_app",
code: ["js", "xml", "css"],
},
{
description: "Responsive app",
folder: "responsive_app",
code: ["js", "xml", "css"],
},
{
description: "Slots And Generic Components",
folder: "slots",
code: ["js", "xml", "css"],
},
{
description: "Window Management System",
folder: "window_manager",
code: ["js", "xml", "css"],
},
{
description: "Benchmark example",
folder: "benchmark",
code: ["js", "xml", "css"],
},
]
function loadSamples() {
const result = SAMPLES.map(({ description, folder, code }) => ({
description,
code: async () => Object.fromEntries(
await Promise.all(
code.map(async (type) => [type, await loadFile(`./samples/${folder}/${folder}.${type}`)])
)
),
}));
const localSample = localStorage.getItem("owl-playground-local-sample");
if (localSample) {
const { js, css, xml } = JSON.parse(localSample);
result.unshift({
description: "Local Storage Code",
code: () => Promise.resolve({ js, xml, css }),
});
}
return result;
}
//------------------------------------------------------------------------------
// Tabbed editor
//------------------------------------------------------------------------------
class TabbedEditor extends Component {
setup() {
const props = this.props;
this.state = useState({
currentTab: props.js !== false ? "js" : props.xml ? "xml" : "css"
});
this.setTab = debounce(this.setTab.bind(this), 250, true);
this.sessions = {};
this._setupSessions(props);
this.editorNode = useRef("editor");
this._updateCode = this._updateCode.bind(this);
onMounted(() => {
this.editor = this.editor || ace.edit(this.editorNode.el);
this.editor.setValue(this.props[this.state.currentTab], -1);
this.editor.setFontSize("12px");
this.editor.setTheme("ace/theme/monokai");
this.editor.setSession(this.sessions[this.state.currentTab]);
const tabSize = this.state.currentTab === "xml" ? 2 : 4;
this.editor.session.setOption("tabSize", tabSize);
this.editor.on("blur", this._updateCode);
this.interval = setInterval(this._updateCode, 3000);
});
onPatched(() => {
const session = this.sessions[this.state.currentTab];
let content = this.props[this.state.currentTab];
if (content === false) {
const tab = this.props.js !== false ? "js" : this.props.xml ? "xml" : "css";
content = this.props[tab];
this.state.currentTab = tab;
}
if (this.editor.getValue() !== content) {
session.setValue(content, -1);
this.editor.setSession(session);
this.editor.resize();
}
});
onWillUpdateProps((nextProps) => this._setupSessions(nextProps));
onWillUnmount(() => {
clearInterval(this.interval);
this.editor.off("blur", this._updateCode);
});
}
setTab(tab) {
if (this.state.currentTab !== tab) {
this.state.currentTab = tab;
const session = this.sessions[this.state.currentTab];
session.doc.setValue(this.props[tab], -1);
this.editor.setSession(session);
}
}
onMouseDown(ev) {
if (ev.target.tagName === "DIV") {
let y = ev.clientY;
const resizer = ev => {
const delta = ev.clientY - y;
y = ev.clientY;
this.props.updatePanelHeight({ delta });
};
document.body.addEventListener("mousemove", resizer);
document.body.addEventListener("mouseup", () => {
document.body.removeEventListener("mousemove", resizer);
});
}
}
_setupSessions(props) {
for (let tab of ["js", "xml", "css"]) {
if (props[tab] !== false && !this.sessions[tab]) {
this.sessions[tab] = new ace.EditSession(props[tab], MODES[tab]);
this.sessions[tab].setOption("useWorker", false);
const tabSize = tab === "xml" ? 2 : 4;
this.sessions[tab].setOption("tabSize", tabSize);
this.sessions[tab].setUndoManager(new ace.UndoManager());
}
}
}
_updateCode() {
const editorValue = this.editor.getValue();
const propsValue = this.props[this.state.currentTab];
if (editorValue !== propsValue) {
this.props.updateCode({
type: this.state.currentTab,
value: editorValue
});
}
}
}
TabbedEditor.template = "TabbedEditor";
//------------------------------------------------------------------------------
// MAIN APP
//------------------------------------------------------------------------------
class Playground extends Component {
static template = "Playground";
static components = { TabbedEditor };
setup() {
this.version = __info__.version;
this.isDirty = false;
this.state = useState({
js: "",
css: "",
xml: DEFAULT_XML,
displayWelcome: true,
splitLayout: true,
leftPaneWidth: Math.ceil(window.innerWidth / 2),
topPanelHeight: null
});
this.samples = loadSamples();
if (window.location.hash) {
try {
const { js, css, xml } = JSON.parse(atob(decodeURIComponent(window.location.hash.slice(1))));
if ([js, css, xml].every(item => typeof item === "string")) {
Object.assign(this.state, { js, css, xml });
}
} catch {}
}
onWillStart(async () => {
if (!this.state.js) {
this.setSample(await this.samples[0].code());
}
})
useEffect(() => {
const interval = setInterval(() => {
if (this.isDirty) {
const { js, css, xml } = this.state;
const str = JSON.stringify({ js, css, xml });
localStorage.setItem("owl-playground-local-sample", str);
}
}, 1000);
return () => clearInterval(interval);
}, () => []);
this.toggleLayout = debounce(this.toggleLayout, 250, true);
this.runCode = debounce(this.runCode, 250, true);
this.exportStandaloneApp = debounce(this.exportStandaloneApp, 250, true);
this.content = useRef("content");
this.updateCode = this.updateCode.bind(this);
}
runCode() {
this.content.el.innerHTML = "";
this.state.displayWelcome = false;
const { js, css, xml } = this.state;
const subiframe = makeCodeIframe(js, css, xml);
this.content.el.appendChild(subiframe);
}
shareCode() {
const state = btoa(JSON.stringify({ js: this.state.js, css: this.state.css, xml: this.state.xml }));
const link = new URL(window.location.href);
link.hash = state;
if (navigator.clipboard) {
navigator.clipboard.writeText(link.href);
clearTimeout(this.state.copied)
this.state.copied = setTimeout(() => this.state.copied = null, 2000);
}
window.location.href = link.href;
}
setSample(sample) {
this.state.js = sample.js;
this.state.css = sample.css || "";
this.state.xml = sample.xml || DEFAULT_XML;
localStorage.removeItem("owl-playground-local-sample");
this.isDirty = false;
}
get leftPaneStyle() {
return `width:${this.state.leftPaneWidth}px`;
}
get topEditorStyle() {
return `flex: 0 0 ${this.state.topPanelHeight}px`;
}
async onSampleChange(ev) {
this.setSample(await this.samples.find(s => s.description === ev.target.value).code());
}
onMouseDown() {
const resizer = ev => {
this.state.leftPaneWidth = ev.clientX;
};
document.body.addEventListener("mousemove", resizer);
for (let iframe of document.getElementsByTagName("iframe")) {
iframe.classList.add("disabled");
}
document.body.addEventListener("mouseup", () => {
document.body.removeEventListener("mousemove", resizer);
for (let iframe of document.getElementsByTagName("iframe")) {
iframe.classList.remove("disabled");
}
});
}
updateCode({type, value}) {
if (this.state[type] !== value) {
this.state[type] = value;
this.isDirty = true;
}
}
toggleLayout() {
this.state.splitLayout = !this.state.splitLayout;
}
updatePanelHeight({ delta }) {
let height = this.state.topPanelHeight || document.querySelector(".tabbed-editor").clientHeight;
this.state.topPanelHeight = height + delta;
}
async exportStandaloneApp() {
const { js, css, xml } = this.state;
await loadJS("libs/jszip.min.js");
const zip = new JSZip();
zip.file("app.py", await loadFile("./standalone_app/app.py"));
zip.file("index.html", await loadFile("./standalone_app/index.html"));
zip.file("owl.js", await loadFile("../owl.js"));
zip.file("app.js", `const TEMPLATES = await (await fetch('app.xml')).text();\n${js}`);
zip.file("app.css", css);
zip.file("app.xml", xml);
await loadJS("libs/FileSaver.min.js");
saveAs(await zip.generateAsync({ type: "blob" }), "app.zip");
}
}
//------------------------------------------------------------------------------
// Application initialization
//------------------------------------------------------------------------------
async function start() {
document.title = `${document.title} (v${__info__.version})`;
const commit = `https://github.com/odoo/owl/commit/${__info__.hash}`;
console.info(`This application is using Owl built with the following commit:`, commit);
const [templates] = await Promise.all([
loadFile("templates.xml"),
whenReady()
]);
const rootApp = new App(Playground, { name: "Owl Playground" });
rootApp.addTemplates(templates);
await rootApp.mount(document.body);
}
start();
@@ -0,0 +1,11 @@
tr.danger {
font-weight: bold;
}
.remove:hover {
font-weight: bold;
}
.remove {
cursor: pointer;
}
@@ -0,0 +1,124 @@
import { Component, mount, useState, onPatched} from "@odoo/owl";
// -----------------------------------------------------------------------------
// Data generation
// -----------------------------------------------------------------------------
let idCounter = 1;
const adjectives = [
"pretty", "large", "big", "small", "tall", "short", "long", "handsome", "plain",
"quaint", "clean", "elegant", "easy", "angry", "crazy", "helpful", "mushy", "odd",
"unsightly", "adorable", "important", "inexpensive", "cheap", "expensive", "fancy"];
const colours = ["red", "yellow", "blue", "green", "pink", "brown", "purple", "brown", "white", "black", "orange"];
const nouns = ["table", "chair", "house", "bbq", "desk", "car", "pony", "cookie", "sandwich", "burger", "pizza", "mouse", "keyboard"];
function _random (max) { return Math.round(Math.random() * 1000) % max; };
function buildData(count) {
const data = new Array(count);
for (let i = 0; i < count; i++) {
const label = `${adjectives[_random(adjectives.length)]} ${colours[_random(colours.length)]} ${nouns[_random(nouns.length)]}`;
data[i] = {
id: idCounter++,
label,
};
}
return data;
}
// -----------------------------------------------------------------------------
// Components
// -----------------------------------------------------------------------------
class Button extends Component {
static template = "Button";
}
class Row extends Component {
static template = "Row";
}
class Root extends Component {
static template = "Root";
static components = { Button, Row };
setup() {
this.state = useState({
rows: [],
selectedRowId: null
});
this.benchmarking = false;
onPatched(() => {
if (this.benchmarking) {
this.stop();
}
});
}
start(descr) {
this.benchmarking = `[${descr}]`;
console.time(this.benchmarking);
}
stop() {
console.timeEnd(this.benchmarking);
this.benchmarking = false;
}
run() {
this.start('add1000');
this.state.rows = buildData(1000);
this.state.selectedRowId = null;
}
runLots() {
this.start('add10_000');
this.state.rows = buildData(10_000);
this.state.selectedRowId = null;
}
add() {
this.start('append1000');
this.state.rows = this.state.rows.concat(buildData(1000));
}
update() {
this.start('update1/10th');
let index = 0;
const rows = this.state.rows;
while (index < rows.length) {
rows[index].label = rows[index].label + " !!!";
index += 10;
}
}
clear() {
this.start('clear');
this.state.rows = [];
this.state.selectedRowId = null;
}
swapRows() {
this.start('swap');
const rows = this.state.rows;
if (rows.length > 998) {
let tmp = rows[1];
rows[1] = rows[998];
rows[998] = tmp;
}
}
selectRow(id) {
this.start('select');
this.state.selectedRowId = id;
}
removeRow(id) {
this.start('remove1');
const rows = this.state.rows;
rows.splice(rows.findIndex(row => row.id === id), 1);
}
}
// dev=false for benchmarking. we don't want to benchmark dev code!
mount(Root, document.body, { templates: TEMPLATES, dev: false });
@@ -0,0 +1,52 @@
<templates>
<t t-name="Button">
<div class='col-sm-6 smallpad'>
<button t-att-id="props.id" class='btn btn-primary btn-block' type='button' t-on-click="props.onClick">
<t t-esc="props.text"/>
</button>
</div>
</t>
<t t-name="Row">
<tr t-att-class="props.isSelected ? 'danger' : ''">
<td class="col-md-1" t-esc="props.row.id" />
<td class="col-md-4">
<a t-on-click="() => props.onSelect(props.row.id)" t-esc="props.row.label" />
</td>
<td class="col-md-1">
<a t-on-click="() => props.onRemove(props.row.id)" class="remove">[x]
<span class='glyphicon glyphicon-remove' aria-hidden="true" />
</a>
</td>
<td class='col-md-6'/>
</tr>
</t>
<t t-name="Root">
<div class='container'>
<div class='jumbotron'>
<div class='row'>
<div class='col-md-6'>
<h1>Owl Keyed</h1>
</div>
<div class='col-md-6'>
<div class='row'>
<Button id="'run'" onClick.bind="run" text="'Create 1,000 rows'" />
<Button id="'runlots'" onClick.bind="runLots" text="'Create 10,000 rows'" />
<Button id="'add'" onClick.bind="add" text="'Append 1,000 rows'" />
<Button id="'update'" onClick.bind="update" text="'Update every 10th row'" />
<Button id="'clear'" onClick.bind="clear" text="'Clear'" />
<Button id="'swaprows'" onClick.bind="swapRows" text="'Swap Rows'" />
</div>
</div>
</div>
</div>
<table class='table table-hover table-striped test-data'>
<tbody>
<t t-foreach="state.rows" t-as="row" t-key="row.id">
<Row row="row" isSelected="row.id === state.selectedRowId" onSelect.bind="selectRow" onRemove.bind="removeRow"/>
</t>
</tbody>
</table>
<span class='preloadicon glyphicon glyphicon-remove' aria-hidden="true" />
</div>
</t>
</templates>
@@ -0,0 +1,10 @@
.greeter {
font-size: 20px;
width: 300px;
height: 100px;
margin: 5px;
text-align: center;
line-height: 100px;
background-color: #eeeeee;
user-select: none;
}
@@ -0,0 +1,26 @@
// In this example, we show how components can be defined and created.
import { Component, useState, mount } from "@odoo/owl";
class Greeter extends Component {
static template = "Greeter";
setup() {
this.state = useState({ word: 'Hello' });
}
toggle() {
this.state.word = this.state.word === 'Hi' ? 'Hello' : 'Hi';
}
}
// Main root component
class Root extends Component {
static components = { Greeter };
static template = "Root"
setup() {
this.state = useState({ name: 'World'});
}
}
mount(Root, document.body, { templates: TEMPLATES, dev: true });
@@ -0,0 +1,9 @@
<templates>
<div t-name="Greeter" class="greeter" t-on-click="toggle">
<t t-esc="state.word"/>, <t t-esc="props.name"/>
</div>
<t t-name="Root">
<Greeter name="state.name"/>
</t>
</templates>
@@ -0,0 +1,6 @@
button {
width: 120px;
height: 35px;
font-size: 16px;
}
@@ -0,0 +1,40 @@
// In this example, we show how hooks can be used or defined.
import { Component, mount, useState, onWillDestroy } from "@odoo/owl";
// We define here a custom behaviour: this hook tracks the state of the mouse
// position
function useMouse() {
const position = useState({x:0, y: 0});
function update(e) {
position.x = e.clientX;
position.y = e.clientY;
}
window.addEventListener('mousemove', update);
onWillDestroy(() => {
window.removeEventListener('mousemove', update);
});
return position;
}
// Main root component
class Root extends Component {
static template = "Root";
setup() {
// simple state hook (reactive object)
this.counter = useState({ value: 0 });
// this hooks is bound to the 'mouse' property.
this.mouse = useMouse();
}
increment() {
this.counter.value++;
}
}
// Application setup
mount(Root, document.body, { templates: TEMPLATES, dev: true });
@@ -0,0 +1,7 @@
<templates>
<div t-name="Root">
<button t-on-click="increment">Click! <t t-esc="counter.value"/></button>
<div>Mouse: <t t-esc="mouse.x"/>, <t t-esc="mouse.y"/></div>
</div>
</templates>
+22
View File
@@ -0,0 +1,22 @@
// This example illustrate how the t-model directive can be used to synchronize
// data between html inputs (and select/textareas) and the state of a component.
// Note that there are two controls with t-model="color": they are totally
// synchronized.
import { Component, useState, mount } from "@odoo/owl";
class Form extends Component {
static template = "Form";
setup() {
this.state = useState({
text: "",
othertext: "",
number: 11,
color: "",
bool: false
});
}
}
// Application setup
mount(Form, document.body, { templates: TEMPLATES, dev: true });
+37
View File
@@ -0,0 +1,37 @@
<templates>
<div t-name="Form">
<h1>Form</h1>
<div>
Text (immediate): <input t-model="state.text"/>
</div>
<div>
Other text (lazy): <input t-model.lazy="state.othertext"/>
</div>
<div>
Number: <input t-model.number="state.number"/>
</div>
<div>
Boolean: <input type="checkbox" t-model="state.bool"/>
</div>
<div>
Color, with a select:
<select t-model="state.color">
<option value="">Select a color</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
</select>
</div>
<div>
Color, with radio buttons:
<span><input type="radio" name="color" id="red" value="red" t-model="state.color"/><label for="red">Red</label></span>
<span><input type="radio" name="color" id="blue" value="blue" t-model="state.color"/><label for="blue">Blue</label></span>
</div>
<hr/>
<h1>State</h1>
<div>Text: <t t-esc="state.text"/></div>
<div>Other Text: <t t-esc="state.othertext"/></div>
<div>Number: <t t-esc="state.number"/></div>
<div>Boolean: <t t-if="state.bool">True</t><t t-else="">False</t></div>
<div>Color: <t t-esc="state.color"/></div>
</div>
</templates>
+7
View File
@@ -0,0 +1,7 @@
{
"compilerOptions": {
"paths": {
"owl": ["../../../src/index.ts"],
},
}
}
@@ -0,0 +1,11 @@
button {
font-size: 18px;
margin: 5px;
}
.demo {
margin: 10px;
padding: 10px;
background-color: #dddddd;
width: 250px;
}
@@ -0,0 +1,68 @@
// This example shows all the possible lifecycle hooks
//
// The root component controls a sub component (DemoComponent). It logs all its lifecycle
// methods in the console. Try modifying its state by clicking on it, or by
// clicking on the two main buttons, and look into the console to see what
// happens.
import {
Component,
useState,
mount,
useComponent,
onWillStart,
onMounted,
onWillUnmount,
onWillUpdateProps,
onPatched,
onWillPatch,
onWillRender,
onRendered,
onWillDestroy,
} from "@odoo/owl";
function useLogLifecycle() {
const component = useComponent();
const name = component.constructor.name;
onWillStart(() => console.log(`${name}:willStart`));
onMounted(() => console.log(`${name}:mounted`));
onWillUpdateProps(() => console.log(`${name}:willUpdateProps`));
onWillRender(() => console.log(`${name}:willRender`));
onRendered(() => console.log(`${name}:rendered`));
onWillPatch(() => console.log(`${name}:willPatch`));
onPatched(() => console.log(`${name}:patched`));
onWillUnmount(() => console.log(`${name}:willUnmount`));
onWillDestroy(() => console.log(`${name}:willDestroy`));
}
class DemoComponent extends Component {
static template = "DemoComponent";
setup() {
useLogLifecycle();
this.state = useState({ n: 0 });
}
increment() {
this.state.n++;
}
}
class Root extends Component {
static template = "Root";
static components = { DemoComponent };
setup() {
useLogLifecycle();
this.state = useState({ n: 0, flag: true });
}
increment() {
this.state.n++;
}
toggleSubComponent() {
this.state.flag = !this.state.flag;
}
}
mount(Root, document.body, { templates: TEMPLATES, dev: true });
@@ -0,0 +1,15 @@
<templates>
<div t-name="DemoComponent" t-on-click="increment" class="demo">
<div>Demo Sub Component</div>
<div>(click on me to update me)</div>
<div>Props: <t t-esc="props.n"/>, State: <t t-esc="state.n"/>. </div>
</div>
<div t-name="Root">
<button t-on-click="increment">Increment Parent State</button>
<button t-on-click="toggleSubComponent">Toggle SubComponent</button>
<div t-if="state.flag">
<DemoComponent n="state.n"/>
</div>
</div>
</templates>
@@ -0,0 +1,56 @@
body {
margin: 0;
}
.app {
height: 100%;
flex-direction: column;
}
.app.desktop {
display: flex;
}
.navbar {
flex: 0 0 30px;
height: 30px;
background-color: cadetblue;
color: white;
line-height: 30px;
}
.controlpanel {
flex: 0 0 100px;
height: 100px;
background-color: #dddddd;
padding: 8px;
}
.content-wrapper {
flex: 1 1 auto;
position: relative;
}
.content {
display: flex;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
.formview {
overflow-y: auto;
flex: 1 1 60%;
min-height: 200px;
padding: 8px;
}
.chatter {
overflow-y: auto;
flex: 1 1 40%;
background-color: #eeeeee;
color: #333333;
padding: 8px;
}
@@ -0,0 +1,118 @@
// In this example, we show how one can design an application that is responsive:
// its UI is different in mobile mode or in desktop mode.
//
// The main idea is to have a "isMobile" key in the environment, then listen
// to resize events and update the env if needed. Then, the whole interface
// will be updated, creating and destroying components as needed.
//
// To see this in action, try resizing the window. The application will switch
// to mobile mode whenever it has less than 768px.
import { Component, useState, mount, reactive, useEnv } from "@odoo/owl";
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
function debounce(func, wait, immediate) {
let timeout;
return function () {
const context = this;
const args = arguments;
function later() {
timeout = null;
if (!immediate) {
func.apply(context, args);
}
}
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
func.apply(context, args);
}
};
}
//------------------------------------------------------------------------------
// Responsive hook
//------------------------------------------------------------------------------
function createUI() {
const getIsMobile = () => window.innerWidth <= 768;
const ui = reactive({ isMobile: getIsMobile() });
const updateEnv = debounce(() => {
const isMobile = getIsMobile();
if (ui.isMobile !== isMobile) {
ui.isMobile = isMobile;
}
}, 15);
window.addEventListener("resize", updateEnv);
return ui;
}
function useUI() {
const env = useEnv();
return useState(env.ui);
}
//------------------------------------------------------------------------------
// Components
//------------------------------------------------------------------------------
class Navbar extends Component {
static template = "Navbar";
}
class MobileSearchView extends Component {
static template = "MobileSearchView";
}
class ControlPanel extends Component {
static template = "ControlPanel";
static components = { MobileSearchView };
setup() {
this.ui = useUI();
}
}
class AdvancedComponent extends Component {
static template = "AdvancedComponent";
}
class FormView extends Component {
static template = "FormView";
static components = { AdvancedComponent };
setup() {
this.ui = useUI();
}
}
class Chatter extends Component {
static template = "Chatter";
setup() {
this.messages = Array.from(Array(100).keys());
}
}
class Root extends Component {
static template = "Root";
static components = { Navbar, ControlPanel, FormView, Chatter };
setup() {
this.ui = useUI();
}
}
//------------------------------------------------------------------------------
// Application Startup
//------------------------------------------------------------------------------
const env = {
ui: createUI()
};
mount(Root, document.body, { templates: TEMPLATES, env, dev: true });
@@ -0,0 +1,42 @@
<templates>
<div t-name="Navbar" class="navbar">Navbar</div>
<div t-name="ControlPanel" class="controlpanel">
<h2>Control Panel</h2>
<MobileSearchView t-if="ui.isMobile" />
</div>
<div t-name="FormView" class="formview">
<h2>Form View</h2>
<AdvancedComponent t-if="!ui.isMobile" />
</div>
<div t-name="Chatter" class="chatter">
<h2>Chatter</h2>
<t t-foreach="messages" t-as="item" t-key="item"><div>Message <t t-esc="item"/></div></t>
</div>
<div t-name="MobileSearchView">Mobile searchview</div>
<div t-name="AdvancedComponent">
This component is only created in desktop mode.
<button>Button!</button>
</div>
<t t-name="maincontent">
<FormView />
<Chatter />
</t>
<div t-name="Root" class="app" t-att-class="{mobile: ui.isMobile, desktop: !ui.isMobile}">
<Navbar/>
<ControlPanel/>
<div class="content-wrapper" t-if="!ui.isMobile">
<div class="content">
<t t-call="maincontent"/>
</div>
</div>
<t t-else="">
<t t-call="maincontent"/>
</t>
</div>
</templates>
@@ -0,0 +1,28 @@
// This example illustrates how one can write Owl components with
// inline templates.
import { Component, useState, xml, mount } from "@odoo/owl";
// Counter component
class Counter extends Component {
static template = xml`
<button t-on-click="() => state.value++">
Click! [<t t-esc="state.value"/>]
</button>`;
state = useState({ value: 0 })
}
// Root
class Root extends Component {
static template = xml`
<div>
<Counter/>
<Counter/>
</div>`;
static components = { Counter };
}
// Application setup
mount(Root, document.body, { templates: TEMPLATES, dev: true});
+43
View File
@@ -0,0 +1,43 @@
.main {
display: flex;
}
.card {
display: flex;
flex-direction: column;
background-color: #eeeeee;
width: 200px;
height: 100px;
margin: 10px;
border: 1px solid gray;
}
.card.full {
height: 100px;
}
.card.small {
height: 25px;
}
.card-title {
flex: 0 0 25px;
font-weight: bold;
background-color: darkcyan;
color: white;
padding: 2px;
}
.card-title button {
float: right;
}
.card-content {
flex: 1 1 auto;
padding: 5px;
border-top: 1px solid white;
}
.card-footer {
border-top: 1px solid white;
}
+49
View File
@@ -0,0 +1,49 @@
// We show here how slots can be used to create generic components.
// In this example, the Card component is basically only a container. It is not
// aware of its content. It just knows where it should be (with t-slot).
// The parent component define the content with t-set-slot.
//
// Note that the t-on-click event, defined in the Root template, is executed in
// the context of the Root component, even though it is inside the Card component
import { Component, useState, mount } from "@odoo/owl";
class Card extends Component {
static template = "Card";
setup() {
this.state = useState({ showContent: true });
}
toggleDisplay() {
this.state.showContent = !this.state.showContent;
}
}
class Counter extends Component {
static template = "Counter";
setup() {
this.state = useState({val: 1});
}
inc() {
this.state.val++;
}
}
// Main root component
class Root extends Component {
static template = "Root"
static components = { Card, Counter };
setup() {
this.state = useState({a: 1, b: 3});
}
inc(key, delta) {
this.state[key] += delta;
}
}
// Application setup
mount(Root, document.body, { templates: TEMPLATES, dev: true});

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