Compare commits

...

145 Commits

Author SHA1 Message Date
Lucas Perais (lpe) fb7d25ba0e [FIX] error_handling: onError works if handling happens between culprit and root
Have a component implementing onError that calls a callback from one of its parent.
That parent should not be the original source of the rendering (a parent above is).

Make the callback handle the error and trigger an render()

Before this commit, the parent did not see it was handling a subtree in error,
and did not have a chance to revert that error state in its rendering stack.

After this commit, this flow works.
2025-10-02 12:46:55 +02:00
Romeo Fragomeli 5187f01c44 [REL] v2.8.1
# v2.8.1

 - [FIX] parser, code_generator: wrapped children recognition
 - [DOC] `slots` prop validation
2025-09-23 09:17:54 +02:00
Mathieu Duckerts-Antoine 521111644c [FIX] parser, code_generator: wrapped children recognition
Several directives (t-key, t-log, t-translation, …) are represented by
wrapper ASTs that contain another AST or null.
Because these wrappers don't share the same type as their children,
various AST type checks were broken.

This commit addresses those issues by:

- Commuting Translation / TranslationContext and Multi ASTs so that
  Multi children are spread as expected (see parseChildren).

- Parsing the t-key directive before t-esc / t-out (in line with https://github.com/odoo/owl/pull/1685).

- Ensuring wrappers around TSet ASTs are recognized as having no
  representation, so compileMulti properly discards children equivalent
  to TSet.
2025-09-22 16:59:47 +02:00
Damien Bouvy c2728c9daf [DOC] slots prop validation
Make it explicit that props validation should accept `slots` if a component uses slots (even the `default` slot).
2025-09-03 13:46:45 +02:00
Romeo Fragomeli 871dad6a13 [REL] v2.8.0
# v2.8.0

 - [FIX] parser: t-esc/t-out vs t-translation*
 - [IMP] compiler: make human-readable ARIA attributes translatable
2025-06-30 14:46:16 +02:00
Mathieu Duckerts-Antoine b620502a0f [FIX] parser: t-esc/t-out vs t-translation*
The directives t-esc/t-out both discard the ASTs that are not of DomNode
type. Since the directives t-translation and t-translation-context both
creates AST wrappers of type TTranslation and TTranslationContext
respectively, mix t-esc/t-out and t-translation/t-translation-context
does not work. For example parse

<span t-esc="'Hello'" t-translation="off"/>

gives the AST

{
    type: ASTType.TEsc,
    expr: "'Hello'",
    defaultValue: "",
}

This makes the span not been rendered in the end.

We fix that problem.
2025-06-24 16:03:56 +02:00
Louis Wicket (wil) 89cb00cc83 [IMP] compiler: make human-readable ARIA attributes translatable
ARIA attributes containing human-readable text should be translated.
This commit adds human-readable ARIA attributes to the list of the
attributes translated by OWL.
2025-04-03 21:40:27 +02:00
Romeo Fragomeli 56041bc133 [REL] v2.7.0
# v2.7.0

 - [IMP] runtime/utils: export htmlEscape and add tests
 - [FIX] utils: Correct validation of mount target in shadow DOM/iframe
 - [IMP] runtime: add markup tag function
2025-03-26 13:58:50 +01:00
Sébastien Theys e788e361c7 [IMP] runtime/utils: export htmlEscape and add tests
markup tag function requires markup awareness to determine whether a
given parameter should be escaped or not.

This implies that pre-escaped content should be properly marked'ed up to
avoid double escaping. Having to manually wrap all calls to escape
with markup is cumbersome and prone to issues (on top of having to be
validated by the security team for no reason).

This commit introduces a markup-aware escape function to resolve those
issues.
2025-03-26 13:52:35 +01:00
Achraf (abz) 9d378b0e7b [FIX] utils: Correct validation of mount target in shadow DOM/iframe
Previously, `validateTarget` only checked if the target element or its
host (if it was a ShadowRoot) was directly contained in the document body.
This failed in cases where the target element was nested inside a shadow
DOM, which itself was attached to the document.

This commit introduces a new helper `isAttachedToDocument` that
traverses through parent nodes and shadow roots to ensure that the
target is ultimately attached to the given document.
Additionally, it now throws a clear error if `document.defaultView` is
missing, indicating that the target document is detached or invalid.

This ensures proper validation of mount targets, including complex
scenarios with shadow roots and iframes.
2025-03-25 21:11:39 +01:00
Louis Wicket (wil) fd3c194525 [IMP] runtime: add markup tag function
Allows markup to be called as a tag function. The interpolated strings
are then safely escaped for injection in HTML code.

Example usage:
```js
const maliciousInput = "<script>alert('💥💥')</script>";
const value = markup`<b>${maliciousInput}</b>`;
// no problem, maliciousInput is properly escaped
```
2025-03-25 15:39:26 +01:00
Romeo Fragomeli ac9ccb81ca [REL] v2.6.1
# v2.6.1

 - [FIX] code generator: prevent AST change
 - [IMP] runtime: simplify info message when running in dev mode
2025-03-05 09:38:08 +01:00
Michaël Mattiello 2b5cea944b [FIX] code generator: prevent AST change
This commit removes an AST change during the code generation of slots.
Before, the `compileTSlot` function deleted the `t-props` attribute
directly on `ast.attrs`. This creates wrong code when compiling a
second time as the `t-props` attribute does not exist anymore.
2025-03-05 09:27:43 +01:00
Géry Debongnie cf8039f643 [IMP] runtime: simplify info message when running in dev mode
The owl dev info message may be useful, but does not bring that much
value. Also, this is even slightly annoying while debugging odoo, since
it is common to have to go to dev mode, and the message takes some
visual space, which is a distraction.  In this commit, we simplify it to
just warn that owl is in dev mode.
2025-01-16 15:55:11 +01:00
Romeo Fragomeli aec2373e6d [REL] v2.6.0
# v2.6.0

 - [IMP] translation contexts
2025-01-15 11:40:33 +01:00
Mathieu Duckerts-Antoine a9be149e1e [IMP] translation contexts
A new directive t-tanslation-context and a new family of directives (of the form
t-translation-context-...) are introduced to allow to translate terms in contexts.

Set t-translation-context="fr" on a node makes every call of the translation
function to be done with "fr" as seconde parameter when translating an
attribute/content within that node or its children (if no closer
t-translation-context directive is found).
A directive t-translation-context-attr="fr" can be used on a node to target its
attribute "attr". For example, if a div has an attribute title="a title",
use t-translation-context-title="pt" will make "a title" to be translated
in the context "pt". Note that this takes precedence over any other directive
t-translation-context found on a parent (or the div itself).
The translation function is in charge of the interpretation of the context: OWL
does not associate any meaning with a translation context.
2025-01-15 11:01:53 +01:00
Romeo Fragomeli b365ea5c9c [REL] v2.5.3
# v2.5.3

 - [IMP] tools: expose template compiler as npm command
 - [IMP] compiler: add prop suffix name in the error message
2025-01-10 11:11:03 +01:00
odoo b31fa81083 [IMP] tools: expose template compiler as npm command
Previously, we made it possible to compile templates ahead of time as
this was required by the owl devtools. Unfortunately, no effort was made
at the time to make this ahead-of-time compiler outside of the owl repo.

This commit refactors the AoT template compiler by splitting it in two
parts: a typescript module that gets bundled in the dist folder that
gives a programmatic way to call the standalone compiler from another
javascript module by importing it, and a command line utility that is
exposed as an executable files available to npm run-script of dependent
modules (configured in the bin field of owl's package.json).

This allows a simple workflow for modules wanting to use owl:

`npm install @odoo/owl`

add a script to your package.json that calls compile_owl_templates on
your source files, eg:

```jsonc
{
  // ...
  "scripts": {
    "build": "compile_owl_templates src -o dist/templates.js"
  }
}
```

`npm run build`
2025-01-09 16:17:36 +01:00
Romain Derie 9b656fd9e4 [IMP] compiler: add prop suffix name in the error message
Without this, you only get the following error:
```
UncaughtPromiseError > OwlError
Uncaught promise > Invalid prop suffix
OwlError: Invalid prop suffix
```

Which is not helping much to find the problematic code.
2025-01-07 13:34:03 -05:00
Julien Carion (juca) 17f4823b13 [FIX] devtools: sort object keys numerically as well
This commit makes the alphabetical sort of object keys account for
numerical order as well so that it will feel right when handling objects
with numerical keys.
2025-01-06 12:15:39 +01:00
Julien Carion (juca) d3bc101177 [FIX] devtools: fix observe variables
This commit solves issues with the observe variables functionality: it
first restricts refreshing the observed variables to when owl is loaded
on the page and then fixes how simplified paths are handled to find
components so that both type of path will work fine no matter from where
the function is called. This would cause issues when observing variables
from the observed state section.
2024-12-12 11:27:30 +01:00
Julien Carion (juca) 4287beae19 [REL] devtools: chrome v1.3.0, firefox v1.1.0 2024-12-05 15:43:39 +01:00
Julien Carion (juca) a073c68685 [IMP] devtools: update doc
This commit updates the owl devttols documentation for its new versions
(1.3.0 chrome and 1.1.0 firefox).
2024-12-05 15:43:39 +01:00
Julien Carion (juca) 7078d64049 [IMP] devtools: observe variables
This commit allows the user to observe variables so that their content
will be refreshed every 200ms and will be displayed as long as they
are found in the tree.
2024-12-05 15:43:39 +01:00
Julien Carion (juca) ccd31f12d9 [IMP] devtools: add lifecycle hooks management
This commit adds lifecycle hooks to the interface of the selected
component and allows to inject breakpoints into these hooks.
2024-12-05 15:43:39 +01:00
Julien Carion (juca) aff4019cde [REF] devtools: linting and context menu rework
This commit cleans up linting issues and proposes a new implementation
for the devtools custom context menus.
2024-12-05 15:43:39 +01:00
Julien Carion (juca) 5ecb4809ff [FIX] devtools: arrays are objects
This commit fixes some dead code related to the display of arrays inside
other objects. Arrays are objects indeed so the condition was impossible
to satisfy.
2024-12-05 15:43:39 +01:00
Julien Carion (juca) c2daecc07b [FIX] devtools: don't evaluate getters at object stringification
This commit prevents the serializer to evaluate object getters when
it is trying to display an object in a reduced form. This would cause
issues when a getter was returning an error instead of a value.
2024-12-05 15:43:39 +01:00
Julien Carion (juca) fcda17c8e9 [IMP] devtools: sort object keys in alphabetical order
Some big objects are quite hard to read because keys are sorted by
order of definition inside the object. It is better to sort them in
alphabetical order as is done in the base devtools.
2024-12-05 15:43:39 +01:00
Géry Debongnie aeed79c7e5 [REL] v2.5.2
# v2.5.2

 - [FIX] runtime: make error recovery more robust
2024-12-02 16:51:14 +01:00
Géry Debongnie 1c5b6f2573 [FIX] runtime: make error recovery more robust
The error recovery process is necessary, but is particularly subtle. An
error may occur basically any time some user code is called, which may
leave the internal owl state in an invalid situation.

In this commit, we try to improve Owl behaviour when a crash occurs in a
onMounted hook. Before this commit, it was possible for other component
mounted hooks to be called even though the component was not mounted, or
for willUnmount hooks to be called even though the component was
mounted, but its onMounted hooks had not been called.

All these situations need to be handled when we catch an error. In this
commit, we try to clean more internal state in the error handling code,
to make Owl more consistent.
2024-11-28 16:27:56 +01:00
Romeo Fragomeli cd9b72158b [REL] v2.5.1
# v2.5.1

 - [FIX] compiler: multiple modifiers on t-custom
2024-11-26 09:42:49 +01:00
Jorge Pinna Puissant 7fc552e2f8 [FIX] compiler: multiple modifiers on t-custom
Since [1] it's possible to have a custom directive, this directive only
supported one modifier. This commit, add the support to have multiple
modifiers on a t-custom directive.

[1] : https://github.com/odoo/owl/commit/7e687234bf40bdcf5e6598401d8604d66b14ad32
2024-11-25 16:14:56 +01:00
Romeo Fragomeli e6768501cd [REL] v2.5.0
# v2.5.0

 - [IMP] app: add global values at compile time
 - [IMP] parser: add support for custom directives
 - [FIX] runtime: properly handle error caused in mounted hook
2024-11-25 10:30:53 +01:00
Jorge Pinna Puissant 6b2486473f [IMP] app: add global values at compile time
This commit, add a new configuration on the App: globalValues.
It's a global object of elements available at compilations.

For instance:
```js
    const app = new App(SomeComponent, {
      globalValues: {
        plop: (string: any) => {
          steps.push(string);
        },
      },
    });
```

The plop function will be available at the compilation, so it can be
used on the templates :
```xml
<div t-on-click="() => __globals__.plop('click')" class="my-div"/>
```
2024-11-25 09:57:54 +01:00
Jorge Pinna Puissant 7e687234bf [IMP] parser: add support for custom directives
This commit adds the support for custom directives. To use the
custom directive, an Object of functions needs to be configured on
the owl APP:
```js
 new App(..., {
    customDirectives: {
     test_directive: function (el, value) {
            el.setAttribute("t-on-click", value);
            return el;
       }
   }
  });
```
The functions will be called when a custom directive with the name of the
function is found. The original element will be replaced with the one
returned by the function.
This :
```xml
<div t-custom-test_directive="click" />
```
will be replace by :
```xml
<div t-on-click="value"/>
```

issue : https://github.com/odoo/owl/issues/1650
2024-11-25 09:57:54 +01:00
Géry Debongnie 968e96ad08 [FIX] runtime: properly handle error caused in mounted hook
If a component onMounted hook causes an error, and an error handler
tries to reinitiate a new correct render, the fiber may be recycled. But
the scheduler removes it from its own set of tasks, so it will be
ignored.

We simply check for this condition before removing it from the tasks
set.
2024-11-25 09:56:34 +01:00
Romeo Fragomeli 26c7856d5d [REL] v2.4.1
# v2.4.1

 - [FIX] app: make subroots more robust
 - [IMP] devtools: show objects class name and add special extension cases
 - [IMP] devtools: allow expansion of empty class
 - [IMP] Bump support for Node 20+
2024-10-31 10:42:38 +01:00
Géry Debongnie b8d09e523d [FIX] app: make subroots more robust
This commit fixes two issues with subroots:

1. creating a subroot create a new component node synchronously. This
   would causes issues if the creation was done in the setup of a
component, since in that case, owl would reset the current component to
null right after, which would cause all calls to hooks to fail. This is
fixed by restoring the previous component node right after creating a
root.

2. the destroy method for roots calls the scheduler processTasks.
   However, the processTasks method was not safe to reentrant calls,
which would in some cases crashes owl. For example, if a destroy is done
while a new component is mounted, the mount method would be called
twice.

This is fixed by ignoring the processTasks if we are currently
processing tasks. It works because the "for ... of" loop will still
process all new tasks in the current iteration.
2024-10-21 14:28:27 +02:00
Julien Carion (juca) 04c2808701 [IMP] devtools: show objects class name and add special extension cases
This commit ensures that class names are displayed for non generic
objects and extensions of generic classes will have custom display for
their content.
2024-10-11 10:39:50 +02:00
Julien Carion (juca) 15c2604df1 [IMP] devtools: allow expansion of empty class
This commit makes it possible to expand empty classes to see their
prototype instead of displaying them as simple empty objects.
2024-10-11 10:39:50 +02:00
Romeo Fragomeli 3e11fe6b12 [IMP] Bump support for Node 20+
This commit bump the support for Node 20+.
2024-10-09 20:31:31 +02:00
Romeo Fragomeli 20c6cacb4e [REL] v2.4.0
# v2.4.0

 - [IMP] owl: add basic support for sub roots
 - [IMP] make set of timeout-able hooks (and their timeouts) clearer by using a const map
 - [IMP] devtools: add support for file urls on chrome
2024-09-30 10:49:39 +02:00
Géry Debongnie eb2b32ab60 [IMP] owl: add basic support for sub roots
In this commit, we extend the owl App class to support multiple sub
roots. This is useful for situations where we want to mount sub
components in non-managed DOM. This is exactly what the Knowledge app is
doing, with mounting views in an html editor.

Currently, this requires some difficult and fragile hacks, and still,
the result is that it is very easy to mix components from the main App
and a SubApp.  But Knowledge does not actually care about creating a sub
app. It only needs the possibility to mount sub components in dynamic
places.

closes #1640
2024-09-27 15:35:37 -04:00
Xavier Morel 2a223288d4 [IMP] make set of timeout-able hooks (and their timeouts) clearer by using a const map
Also unnest the handling of `result` via guard clauses, and generate
messages as close as possible to use site, keeping the error
construction itself where it currently is as the goal is specifically
to point back to the *definition* site for the hook function.
2024-09-23 20:29:20 +02:00
Julien Carion (juca) 1272278225 [IMP] devtools: add support for file urls on chrome
This commit ensures that the hook will properly be loaded on file urls
when using chrome (this was already working in firefox). It is still
necessary to check the "Allow access to file URLs" option in the
extensions manager for this to work properly.
2024-09-18 16:24:53 +02:00
Aaron Bohy f502dd732e [REL] v2.3.1
# v2.3.1

 - [FIX] runtime: log if willStart takes more than 3s
2024-08-14 16:25:32 +02:00
Aaron Bohy 9c2d957525 [FIX] runtime: log if willStart takes more than 3s
Before this commit, when willStart/willUpdateProps took more than
3s, a console.warn was done. In odoo, when a warning is logged
during a test, the test fails and the build is considered as "in
error".

There's a component that loads several resources (sequentially) in
its onWillStart, which *sometimes* takes more than 3s, making
builds fail non deterministically. Since a recent change (which
adds another call in the problematic onWillStart), the warning gets
logged quite often.

A quick fix is necessary, so we change the warn into a log, which
won't make build fail.

We may consider alternatives in the future though:
 - add a parameter to onWillStart, to disable the timeout, or to
   specify the delay (which is 3s by default)
 - do not warn in test mode
2024-08-14 15:48:49 +02:00
Romeo Fragomeli f8bb86820e [REL] v2.3.0
# v2.3.0

 - [IMP] compiler: add support for the .translate suffix
2024-07-26 10:36:12 +02:00
Samuel Degueldre 0cde4b8737 [IMP] compiler: add support for the .translate suffix
Previously, if you wanted to pass a prop and have it be translated, you
had to either to the translation manually in JS, or use a workaround
with t-set and a body so that Owl would translate it for you, and then
pass the t-set variable as a prop. This is quite inconvenient and is a
common use case.

This commit introduces the `.translate` suffix to solve this issue. When
a prop uses this suffix, it is treated as a string instead of a JS
expression, avoiding the need for quotes as well as their escaping and
allowing extraction tools such as babel to generate a clean string as
the term's translation id. This is also more ergonomic. This suffix is
available for both component props and slot props.

This change will still require some work in Odoo to correctly extract
the terms for props using this suffix.
2024-07-15 10:14:08 +02:00
Romeo Fragomeli 66a801393f [REL] v2.2.11
# v2.2.11

 - [FIX] compiler: better support for arrow function and function call
 - [IMP] owl-vision: Autocomplete and added missing owl directives
 - [IMP] index: export batched utility function
 - [FIX] playground: correctly escape backslashes and interpolation sigils
 - [FIX] compiler: correctly escape special characters in template literals
 - [FIX] Typo docs
 - [FIX] runtime: don't emit async hook warnings when cancelled/destroyed
2024-06-17 15:31:21 +02:00
Romeo Fragomeli e7f405cc97 [FIX] compiler: better support for arrow function and function call
This commit fixes inline expressions when we have these conditions:
* inline expression that contains an arrow function
* inside the arrow function call a function with multiple arguments (3+)
* the second argument (not the first and not the last) must be a variable

In the `compileExprToArray` we have a code to handle missing tokens in an object
e.g.: {a} (equivalent to {a:a})

When OWL match all 3 conditions listed above we execute the code to handle
the missing tokens and so it alter the tokens and adds a new token:
`{ type: "COLON", value: ":" }`
This result in a Javascript compilation error:
OwlError: Failed to compile template "XXX": missing ) after argument list

To fix the error and avoid execute the code to handle the missing tokens, now,
we track also the parentheses in our local stack.
2024-06-17 12:51:59 +02:00
Bastien Fafchamps (bafa) 55c48b2b12 [IMP] owl-vision: Autocomplete and added missing owl directives
This commit adds basic autocomplete in  xml files. This includes autocompletion
for elements, components, props, attributes, and javascript expressions.

It also:
- Adds "Go To Definition" support for props and javascript expressions in xml
- Support for the following directives: t-att, t-model, t-tag, t-debug, t-log
- Fixes t-else syntax highlight to be non-dynamic as the attribute value
should be empty
2024-06-11 10:18:03 +02:00
Lucas Lefèvre (lul) 2eb151c92d [IMP] index: export batched utility function
'batched' will be used in odoo/o-spreadsheet.
There's also a copied version (slightly modified) in odoo/odoo.

It shows it could be useful outside owl.
2024-05-22 12:01:13 +02:00
Samuel Degueldre 7952f31e63 [FIX] playground: correctly escape backslashes and interpolation sigils
Previously, if you used a backslash in a template on the playground, it
would be interpreted as an escape sequence, and if you wrote "${" it
would likely crash, as it would be treated as an interpolation sigil in
the context of the script element injected inside the playground's
iframe.

A previous fix already escaped backticks, this commit completes the
escaping by escaping the two other things that have special meaning
within template literals.
2024-05-13 15:35:02 +02:00
Samuel Degueldre 11e4e67599 [FIX] compiler: correctly escape special characters in template literals
Previously, there were a few places where the compiler would create
strings from template content and emit them as template literals, but
didn't properly escape characters or character sequences with special
meanings, in particular: backslashes, backticks, and interpolation
sigils.

This commit fixes this in:
- block creation (interpolation sigils were not escaped)
- text node creation (no escaping was performed)
- comment not creation (no escaping was performed)
- default values for t-esc (no escaping was performed)
- body of a t-set (no escaping was performed)
2024-05-13 15:35:02 +02:00
Giorgio (gito) 7b7a6de373 [FIX] Typo docs
interplolation -> interpolation
2024-04-22 16:09:06 +02:00
Giorgio (gito) b63d1e28b2 [FIX] Typo docs
Fixed brackets on props validation example
2024-04-22 11:33:55 +02:00
Giorgio (gito) c0667a11c6 [FIX] Typo docs
Missing closing parenthesis in props validation code example
2024-04-22 10:54:37 +02:00
Samuel Degueldre fddb1ec924 [FIX] runtime: don't emit async hook warnings when cancelled/destroyed
Previously, the async hook warning that's emitted when async hooks take
too long to resolve would be emitted even if the component was
destroyed or cancelled. We used to check if the node's fiber was still
the current fiber as a proxy for cancellation, but this is insufficient
in the case where an app might be destroyed.

This commit also wraps the content of some of the warning tests into a
try/finally block so that a failure of these tests doesn't pollute
setTimeout and console.warn and cause other tests to timeout one after
another.
2024-04-15 10:01:54 +02:00
Samuel Degueldre e6c3b62ef0 [REL] v2.2.10
# v2.2.10

 - [IMP] runtime: allow using any class as a type in props validation
 - Update reactivity.md
 - [IMP] owl-vision: Better snippets
 - [FIX] docs: code in example cannot run
2024-04-02 12:25:50 +02:00
Samuel Degueldre 97b69f164f [IMP] runtime: allow using any class as a type in props validation
Previously, we had a fixed whitelist for types that were allowed during
props validation. The implementation however supports using arbitrary
classes, and in practice it's desirable to do so, and already done when
not using typescript (when using typescript, it will error if the class
is not whitelisted), eg in Odoo, we use "Element" for the arch in the
standard view props, but this causes all view controllers to fail type
checking because it's not whitelisted.

This commit simply replaces existing constructors by a generic
constructor type, and adds a test with a validation success and a test
with a validation failure.
2024-03-26 14:10:30 +01:00
Mohamed Alkobrosli 33dfeb1b41 Update reactivity.md
of a of a repeatition, it is fixed by removing "of a"
2024-03-21 23:33:00 +01:00
Arnaud Baes dd292472b9 [IMP] owl-vision: Better snippets
- Adds a basic XML owl template
- Make use of `$TM_FILENAME_BASE` and `$RELATIVE_FILEPATH` and attempt
  to predict the component and template names.

See: https://code.visualstudio.com/docs/editor/userdefinedsnippets#_variables
2024-03-14 12:40:37 +01:00
Trịnh Đức Độ 9b18b57fdf [FIX] docs: code in example cannot run 2024-03-14 08:10:42 +01:00
Samuel Degueldre 68f491cd32 [REL] v2.2.9
# v2.2.9

 - [IMP] reactivity: replace sets with small arrays for performance
2024-01-12 15:44:13 +01:00
Samuel Degueldre 7b3e39ba27 [IMP] reactivity: replace sets with small arrays for performance
While Sets have better lookup complexity than arrays, because of the
large constant factors, small arrays can perform better than small sets
when checking for inclusion.

In practice, replacing both of the raw types sets with arrays can
improve performance of reactive-heavy workloads by as much as 30%.

Considering the reactivity code is very hot when rendering data-heavy
components, and the low impact on readability of the fix, the
cost-benefit analysis is clearly in favour of making the fix.
2024-01-12 15:40:14 +01:00
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
207 changed files with 21117 additions and 4735 deletions
+1 -1
View File
@@ -14,7 +14,7 @@ jobs:
strategy:
matrix:
node-version: [12.x, 14.x, 16.x]
node-version: [20.x, 22.x]
steps:
- uses: actions/checkout@v2
+8 -1
View File
@@ -15,7 +15,7 @@ yarn-debug.log*
yarn-error.log*
#ide's
.vscode
**/.vscode/*
.idea
node_modules
@@ -26,3 +26,10 @@ release-notes.md
# useful in some cases
/temp
# owl-vision
*/owl-vision/out/
*/owl-vision/.vs/
**/*.vsix
!*/owl-vision/.vscode/launch.json
!*/owl-vision/.vscode/tasks.json
+1
View File
@@ -47,3 +47,4 @@ Utility/helpers:
- [`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
- [`batched`](reference/utils.md#batched): utility function to batch function calls
+33
View File
@@ -6,6 +6,7 @@
- [API](#api)
- [Configuration](#configuration)
- [`mount` helper](#mount-helper)
- [Roots](#roots)
- [Loading templates](#loading-templates)
## Overview
@@ -61,8 +62,13 @@ The `config` object is an object with some of the following keys:
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).
- **`customDirectives (object)`**: if given, the corresponding function on the object will be called
on the template custom directives: `t-custom-*` (see [Custom Directives](templates.md#custom-directives)).
- **`globalValues (object)`**: Global object of elements available at compilations.
## `mount` helper
@@ -90,6 +96,33 @@ 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.
## Roots
An application can have multiple roots. It is sometimes useful to instantiate
sub components in places that are not managed by Owl, such as an html editor
with dynamic content (the Knowledge application in Odoo).
To create a root, one can use the `createRoot` method, which takes two arguments:
- **`Component`**: a component class (Root component of the app)
- **`config (optional)`**: a config object that may contain a `props` object or a
`env` object.
The `createRoot` method returns an object with a `mount` method (same API as
the `App.mount` method), and a `destroy` method.
```js
const root = app.createRoot(MyComponent, { props: { someProps: true } });
await root.mount(targetElement);
// later
root.destroy();
```
Note that, like with owl `App`, it is the responsibility of the code that created
the root to properly destroy it (before it has been removed from the DOM!). Owl
has no way of doing it itself.
## Loading templates
Most applications will need to load templates whenever they start. Here is
+2 -1
View File
@@ -357,7 +357,7 @@ cleaning operation, since the component may be destroyed before it has even been
mounted. The `willDestroy` hook is useful in that situation, since it is always
called.
The `onWillUnmount` hook is used to register a function that will be executed at
The `onWillDestroy` hook is used to register a function that will be executed at
this moment:
```javascript
@@ -451,5 +451,6 @@ console.log(status(component));
// logs either:
// - 'new', if the component is new and has not been mounted yet
// - 'mounted', if the component is currently mounted
// - 'cancelled', if the component has not been mounted yet but will be destroyed soon
// - 'destroyed' if the component is currently destroyed
```
+2 -2
View File
@@ -51,8 +51,8 @@ that render its content, and a fallback if an error happened.
```js
class ErrorBoundary extends Component {
static template = xml`
<t t-if="error" t-slot="fallback">An error occurred</t>
<t t-else="" t-slot="content"`;
<t t-if="state.error" t-slot="fallback">An error occurred</t>
<t t-else="" t-slot="default"/>`;
setup() {
this.state = useState({ error: false });
+3 -2
View File
@@ -190,12 +190,13 @@ will then be updated accordingly.
### `useExternalListener`
The `useExternalListener` hook helps solve a very common problem: adding and removing
a listener on some target whenever a component is mounted/unmounted. For example,
a listener on some target whenever a component is mounted/unmounted. It takes a target
as its first argument, forwards the other arguments to `addEventListener`. For example,
a dropdown menu (or its parent) may need to listen to a `click` event on `window`
to be closed:
```js
useExternalListener(window, "click", this.closeMenu);
useExternalListener(window, "click", this.closeMenu, { capture: true });
```
### `useComponent`
+47 -2
View File
@@ -140,6 +140,28 @@ class SomeComponent extends Component {
The `.bind` suffix also implies `.alike`, so these props will not cause additional
renderings.
## Translatable props
When you need to pass a user-facing string to a subcomponent, you likely want it
to be translated. Unfortunately, because props are arbitrary expressions, it wouldn't
be practical for Owl to find out which parts of the expression are strings and translate
them, and it also makes it difficult for tooling to extract these strings to generate
terms to translate. While you can work around this issue by doing the translation in
JavaScript, or by using `t-set` with a body (the body of `t-set` is translated),
and passing the variable as a prop, this is a sufficiently common use case that Owl
provides a suffix for this purpose: `.translate`.
```xml
<t t-name="ParentComponent">
<Child someProp.translate="some message"/>
</t>
```
Note that the content of this attribute is _NOT_ treated as a JavaScript expression:
it is treated as a string, as if it was an attribute on an HTML element, and translated
before being passed to the component. If you need to interpolate some data into the
string, you will still have to do this in JavaScript.
## Dynamic Props
The `t-props` directive can be used to specify totally dynamic props:
@@ -238,7 +260,7 @@ class ComponentB extends owl.Component {
count: {type: Number},
messages: {
type: Array,
element: {type: Object, shape: {id: Boolean, text: String }
element: {type: Object, shape: {id: Boolean, text: String }}
},
date: Date,
combinedVal: [Number, Boolean],
@@ -276,7 +298,8 @@ class ComponentB extends owl.Component {
id: Number,
name: {type: String, optional: true},
url: String
]}, // object, with keys id (number), name (string, optional) and url (string)
}
}, // object, with keys id (number), name (string, optional) and url (string)
someObj3: {
type: Object,
values: { type: Array, element: String },
@@ -297,6 +320,28 @@ class ComponentB extends owl.Component {
Note: the props validation code is done by using the [validate utility function](utils.md#validate).
### `slots` prop
If a component that uses [slots](slots.md) also lists or validates its props, then
you will have to explicitely allow the `slots` prop (with an `Object` type), or
allow extra props using the `*` notation mentioned above. This is because slots
are provided to a component [as props](slots.md#slots-and-props).
For example:
```js
class MyComponent extends Component {
static props = [someProp, slots?];
}
class MyComponentWithValidation extends Component {
static props = {
someProp: {type: Number, optional: true},
slots : {type: Object, optional: true},
}
}
```
## Good Practices
A `props` object is a collection of values that come from the parent. As such,
+2 -2
View File
@@ -152,7 +152,7 @@ This may seem counter-intuitive, but it makes perfect sense in the context of co
```js
class DoubleCounter extends Component {
static template = xml`
<t t-esc="state.selected + ': ' + state[state.selected].value"/>
<t t-esc="'selected: ' + state.selected + ', value: ' + state[state.selected]"/>
<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>
@@ -193,7 +193,7 @@ to be able to opt out of creating them in the first place. This is the purpose o
### `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
part of a reactive object, it will be returned as is, and no keys in that object will be
observed.
```js
+5 -4
View File
@@ -133,7 +133,7 @@ Slots can define a default content, in case the parent did not define them:
## Dynamic Slots
The `t-slot` directive is actually able to use any expressions, using string
interplolation:
interpolation:
```xml
<t t-slot="{{current}}" />
@@ -201,16 +201,17 @@ use this `Notebook` component:
```xml
<Notebook>
<t t-set-slot="page1" title="'Page 1'">
<t t-set-slot="page1" title.translate="Page 1">
<div>this is in the page 1</div>
</t>
<t t-set-slot="page2" title="'Page 2'" hidden="somevalue">
<t t-set-slot="page2" title.translate="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
Slot params works like normal props, so one can use suffixes like `.translate`
when a prop is a user facing string and should be translated, or `.bind` to
bind a function if needed.
## Slot scopes
+61 -18
View File
@@ -18,6 +18,7 @@
- [Sub Templates](#sub-templates)
- [Dynamic Sub Templates](#dynamic-sub-templates)
- [Debugging](#debugging)
- [Custom Directives](#custom-directives)
- [Fragments](#fragments)
- [Inline templates](#inline-templates)
- [Rendering svg](#rendering-svg)
@@ -55,17 +56,19 @@ extensions.
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) |
| 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) |
| `t-translation-context` | [Context of translations within a node](translations.md) |
| `t-translation-context-*` | [Context of translation for a specific node attribute](translations.md) |
The component system in Owl requires additional directives, to express various
needs. Here is a list of all Owl specific directives:
@@ -80,6 +83,7 @@ needs. Here is a list of all Owl specific directives:
| `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) |
| `t-custom-*` | [Rendering nodes with custom directives](#custom-directives) |
## QWeb Template Reference
@@ -189,6 +193,15 @@ 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.
`markup` can also be used as a tag function, allowing the interpolated values to
be safely escaped:
```js
const maliciousInput = "<script>alert('💥💥')</script>";
// <b>&lt;script&gt;alert(&#x27;💥💥&#x27;)&lt;/script&gt;</b>
const value = markup`<b>${maliciousInput}</b>`;
```
### 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, ...
@@ -376,15 +389,16 @@ An important difference should be made with the usual `QWeb` behaviour: Owl
requires the presence of a `t-key` directive, to be able to properly reconcile
renderings.
`t-foreach` can iterate on an array (the current item will be the current value)
or an object (the current item will be the current key).
`t-foreach` can iterate on any iterable, and also has special support for objects
and maps, it will expose the key of the current iteration as the contents of the
`t-as`, and the corresponding value with the same name and the suffix `_value`.
In addition to the name passed via t-as, `t-foreach` provides a few other
variables for various data points (note: `$as` will be replaced with the name
passed to `t-as`):
In addition to the name passed via t-as, `t-foreach` provides a few other useful
variables (note: `$as` will be replaced with the name passed to `t-as`):
- `$as_value`: the current iteration value, identical to `$as` for lists and
integers, but for objects, it provides the value (where `$as` provides the key)
- `$as_value`: the current iteration value, identical to `$as` for arrays and
other iterables, but for objects and maps, it provides the value (where `$as`
provides the key)
- `$as_index`: the current iteration index (the first item of the iteration has index 0)
- `$as_first`: whether the current item is the first of the iteration
(equivalent to `$as_index == 0`)
@@ -587,6 +601,35 @@ will stop execution if the browser dev tools are open.
will print 42 to the console.
### Custom Directives
Owl 2 supports the declaration of custom directives. To use them, an Object of functions needs to be configured on the owl APP:
```js
new App(..., {
customDirectives: {
test_directive: function (el, value) {
el.setAttribute("t-on-click", value);
}
}
});
```
The functions will be called when a custom directive with the name of the
function is found. The original element will be replaced with the one
modified by the function.
This :
```xml
<div t-custom-test_directive="click" />
```
will be replaced by :
```xml
<div t-on-click="value"/>
```
## Fragments
Owl 2 supports templates with an arbitrary number of root elements, or even just
+37 -5
View File
@@ -1,17 +1,28 @@
# 🦉 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.
so, it needs a translate function, which takes
- a string (the term to translate)
- a string (the translation context of the term)
and returns a string.
For example:
```js
const translations = {
hello: "bonjour",
yes: "oui",
no: "non",
fr: {
hello: "bonjour",
yes: "oui",
no: "non",
},
pt: {
hello: "bom dia",
yes: "sim",
no: "não",
},
};
const translateFn = (str) => translations[str] || str;
const translateFn = (str, ctx) => translations[ctx]?.[str] || str;
const app = new App(Root, { templates, tranaslateFn });
// ...
@@ -27,6 +38,11 @@ Once setup, all rendered templates will be translated using `translateFn`:
`placeholder`, `label` and `alt`,
- translating text nodes can be disabled with the special attribute `t-translation`,
if its value is `off`.
- the translate function receives as second parameter a context that can be used
to contextualized the translation. That context can be set globally on a node
and its children by using `t-translation-context`. If a specific node
attribute `x` needs another context, that context can be specified with a
special directive `t-translation-context-x`.
So, with the above `translateFn`, the following templates:
@@ -46,6 +62,22 @@ will be rendered as:
<input placeholder="bonjour" other="yes"/>
```
and the following template:
```xml
<div t-translation-context="fr" title="hello">hello</div>
<div>Are you sure?</div>
<input t-translation-context-placeholder="pt" placeholder="hello" other="yes"/>
```
will be rendered as:
```xml
<div title="bonjour">bonjour</div>
<div>Are you sure?</div>
<input placeholder="bom dia" other="yes"/>
```
Note that the translation is done during the compilation of the template, not
when it is rendered.
+20
View File
@@ -9,6 +9,7 @@ functions are all available in the `owl.utils` namespace.
- [`loadFile`](#loadfile): loading a file (useful for templates)
- [`EventBus`](#eventbus): a simple EventBus
- [`validate`](#validate): a validation function
- [`batched`](#batched): batch function calls
## `whenReady`
@@ -78,3 +79,22 @@ validate(
// - 'id' is missing (should be a number),
// - 'url' is missing (should be a boolean or list of numbers),
```
## `batched`
The `batched` function creates a batched version of a callback so that multiple calls to it within the same microtick will only result in a single invocation of the original callback.
```js
function hello() {
console.log("hello");
}
const batchedHello = batched(hello);
batchedHello();
// Nothing is logged
batchedHello();
// Still not logged
await Promise.resolve(); // Await the next microtick
// "hello" is logged only once
```
+46 -25
View File
@@ -35,13 +35,13 @@ The components tab is separated into two sub windows: the components tree in the
the component details in the right. The components tree will display all the different
components that are present in the tab in the form of a tree. The root of this tree is
actually the app which is not a component but can still be inspected by the devtools like
one. There can also be multiple apps loaded in the page like in the following:
one. There can also be multiple apps loaded in the page like in website:
<img src="screenshots/multi_apps.png"/>
There is a convenient search bar at the top of the components tree which will help finding
the components tou want in the tree and also, an element picker can be used to directly select
the component you want to focus on in the page which is especially useful when trying to find
the component you want to focus on in the page which is especially useful when 1trying to find
what you want. Just click on the elements picker icon and click on the element you want to focus
on in the page and it will be selected in the devtools accordingly. Hovering any element in the
page in this mode will highlight it and the same happens anytime in the components tree.
@@ -64,31 +64,40 @@ as its env, props, observed states and all the other variables that are present
While the props and the env are already present on the actual instance of the component and are
pretty explicit by themselves, the observed state value is a bit more complicated to grasp.
The observed state is actually information about which variables are observed by the component
which will trigger a rerender of the component when it is modified. The keys represent which part of the
variable is actually observed and the target is the actual variable. For simplicity, the properties
that are not observed by the component are greyed out while the others are in bold. This means that
editing bold ones will trigger a rerender while the greyed out ones will not.
The observed state is actually information about which variables are being observed by the component:
when any property of a reactive object is being read by the component, the component will subscribe
to this property which means it will listen to any change that can occur on the property and render
when such a change occurs. This can be visualized easily within the devtools inside of the observed
state section: observed properties of the reactive object(s) are displayed in bold while the others
are greyed out. Do keep in mind that a greyed out property in the observed state of one component
may be observed by another and the other way around is also possible. Here is an example for some
user Field component:
<img src="screenshots/states.png"/>
In the given example, we have two keys/target pairs for two different variables. The first one indicates
that adding or removing an element to the array will trigger a rerender since the length will have changed.
Replacing the element at index 0, 1 or 2 will also have the same effect as implied by the keys. It doesn't
mean that editing the properties of element at index 0, 1 or 2 will rerender the component though. It may
be the case for some but this will be described in another keys/target pair. The second keys/target pair
is actually the element at index 0 of the first pair. It only has id in the keys meaning that only the
id property will actually trigger a rerender the component when modified. Be aware however that the other
properties may be in the observed state of another component like a child one in this case. A greyed out
property only implies it is not reactive for the selected component and not for the others.
The navigation inside the properties is also similar to the one in console variables: properties have
Navigation inside the properties is also similar to the one in console variables: properties have
their prototype displayed and getters will get their value when clicked on (...). It is also possible to
send any property to the console using the right-click context menu on it and functions can be inspected
in the sources tab as well.
<img src="screenshots/function_menu.png"/>
Using the right-click context menu on a property also allows to observe variables. Observed variables will
be sent to a dedicated section of the details window and their value will be refreshed every 200ms. These
variables are only shown when they are found and their access path will be kept in memory inside the
browser so that it will always persist until the user decides to stop observing the variable. As in the
browser's devtools, observed objects are displayed in reduced form and cannot be interacted with. It is
still possible to send them to the console or remove them from the list using right-click.
<img src="screenshots/observe_variables.png"/>
The last section of the details window is filled with the component's lifecycle hooks. Using right click on
them allows to place breakpoints inside the hook (either on its instance or class, hooks like mounted and
willStart cannot have instance-based breakpoints because they will never trigger). Conditions in conditional
breakpoints will be evaluated in the context of the component's definition.
<img src="screenshots/hooks.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.
@@ -96,8 +105,10 @@ component's name. Using the left click on the component's name will focus it in
It is also possible to edit any of the leaf node properties. To do so, you must double click on the
property's value and modify it using the freshly created input then press enter to apply the changes.
Do note that the modified values should be written in JSON format in order to be valid (examples:
89, "yes", undefined, null, \["hello", 15\], {"a": 1}, true, ...). Whether it has an impact on the
component or not and whether it produces an error is the responsability of the user.
89, "yes", undefined, null, \["hello", 15\], {"a": 1}, true, ...). Editing any value will produce a
manual render of the component (or the root component of the application in the case of env values).
Whether the edition has an impact on the component or not and whether it produces an error is the
responsability of the user.
<img src="screenshots/edit.png"/>
@@ -117,7 +128,8 @@ are intercepted by the devtools using the record button.
The second button is used to clear all the events that have been recorded. The select can be used to
switch between the tree view (which shows the causality between renders) and the events log view which
simply displays the events in the exact order they were triggered. In this view, you can expand the create,
update and destroy events which reveals the component that initiated the event.
update and destroy events which reveals the component that initiated the event. Also, a transition line will
appear each time a new animation frame has been loaded between events.
<img src="screenshots/events_log.png"/>
@@ -131,20 +143,29 @@ There is also the Trace Renderings and Trace Subscriptions features. These featu
recording of events and have no effect on the profiler tab. The Trace Renderings option is used to log in
the console all the render events and allows to show their traceback information. Similarly, the Trace
Subscriptions option logs all the properties that caused a render event and also allows to see the traceback
of the modification
of the modification.
<img src="screenshots/trace_rendering.png"/>
<img src="screenshots/trace_subscriptions.png"/>
The Owl Devtools also allow to inspect iframes coded in Owl: when an Owl iframe is detected in the page,
the iframe selector will appear next to the tabs. This allows to switch from an iframe to another easily.
Be aware that switching iframes will clear all record events from the profiler tab. Iframes detection is
currently not working in the firefox version, we are aware of this issue and will try to address it in the
future.
<img src="screenshots/iframes.png"/>
## Options
The owl devtools extension has a dark mode feature which defaults to your general devtools settings and can
be toggled using the sun/moon icon at the top-right corner of the tab. All the examples above were created
with the dark mode enabled. There is also a refresh button to completely reset the owl devtools.
be toggled using the sun/moon icon at the top-right corner of the tab. There is also a refresh button to
completely reset the owl devtools.
<img src="screenshots/darkmode.png"/>
## Troubleshooting
If the feedback from the page to the devtools seems to be cut, just close the devtools and refresh the page.
If the feedback from the page to the devtools seems to be cut, you can first try to use the refresh
button mentioned above but if it still doesn't seem to work, just close the devtools and refresh the page.
This will eventually happen any time a tab stays opened for too long without being refreshed.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 333 KiB

After

Width:  |  Height:  |  Size: 314 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 210 KiB

After

Width:  |  Height:  |  Size: 193 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 197 KiB

After

Width:  |  Height:  |  Size: 266 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 185 KiB

After

Width:  |  Height:  |  Size: 188 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 172 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 166 KiB

After

Width:  |  Height:  |  Size: 200 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 86 KiB

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 311 KiB

After

Width:  |  Height:  |  Size: 346 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 336 KiB

After

Width:  |  Height:  |  Size: 488 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

After

Width:  |  Height:  |  Size: 93 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 146 KiB

After

Width:  |  Height:  |  Size: 182 KiB

+1 -2
View File
@@ -10,7 +10,7 @@
<link rel="stylesheet" href="assets/milligram.css">
<link rel="stylesheet" href="assets/highlight.tomorrow.css">
<link rel="stylesheet" href="assets/main.css">
<script src="./owl.js"></script>
<script type="importmap">{ "imports": { "@odoo/owl": "./owl.js" } }</script>
</head>
<body>
<header class="container">
@@ -68,7 +68,6 @@
<p><a href=".">OWL</a> is licensed under LGPLv3.<br>Logo from <a href="https://github.com/googlefonts/noto-emoji">Google Noto Emoji Font</a>, licensed under Apache License 2.0</p>
</footer>
<script src="assets/highlight.pack.js"></script>
<script type="importmap">{ "imports": { "@odoo/owl": "./owl.js" } }</script>
<script type="module" src="display_code.js"></script>
<script type="module" src="counter.js"></script>
</body>
+718 -354
View File
File diff suppressed because it is too large Load Diff
+2 -3
View File
@@ -41,9 +41,6 @@ const loadFile = (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;
@@ -55,6 +52,8 @@ function makeCodeIframe(js, css, xml) {
const script = doc.createElement("script");
script.type = "module";
// escape characters with special meaning in template literals
const escapedXml = xml.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$\{/, "\\${");
script.textContent = `const TEMPLATES = \`${escapedXml}\`\n${js}`;
doc.body.appendChild(script);
+1 -5
View File
@@ -43,10 +43,6 @@ class TaskList {
}
}
toggleTask(task) {
task.isCompleted = !task.isCompleted;
}
toggleTask(id) {
const task = this.tasks.find(t => t.id === id);
task.isCompleted = !task.isCompleted;
@@ -61,7 +57,7 @@ class TaskList {
clearCompleted() {
const tasks = this.tasks.filter(t => t.isCompleted);
for (let task of tasks) {
this.deleteTask(task);
this.deleteTask(task.id);
}
}
+827 -212
View File
File diff suppressed because it is too large Load Diff
+10 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@odoo/owl",
"version": "2.1.3",
"version": "2.8.1",
"description": "Odoo Web Library (OWL)",
"main": "dist/owl.cjs.js",
"module": "dist/owl.es.js",
@@ -9,7 +9,7 @@
"dist"
],
"engines": {
"node": ">=12.18.3"
"node": ">=20.0.0"
},
"scripts": {
"build:bundle": "rollup -c --failAfterWarnings",
@@ -32,7 +32,10 @@
"check-formatting": "prettier {src/*.ts,src/**/*.ts,tests/*.ts,tests/**/*.ts,doc/*.md,doc/**/*.md,tools/devtools/**/*.js} --check",
"lint": "eslint src/**/*.ts tests/**/*.ts",
"release": "node tools/release.js",
"compile_templates": "node tools/compile_xml.js"
"compile_templates": "node tools/compile_owl_templates.mjs"
},
"bin": {
"compile_owl_templates": "tools/compile_owl_templates.mjs"
},
"repository": {
"type": "git",
@@ -46,6 +49,7 @@
"homepage": "https://github.com/odoo/owl#readme",
"devDependencies": {
"@types/jest": "^27.0.1",
"@types/jsdom": "^21.1.7",
"@types/node": "^14.11.8",
"@typescript-eslint/eslint-plugin": "5.48.1",
"@typescript-eslint/parser": "5.48.1",
@@ -97,5 +101,8 @@
"prettier": {
"printWidth": 100,
"endOfLine": "auto"
},
"dependencies": {
"jsdom": "^25.0.1"
}
}
+33 -25
View File
@@ -1,6 +1,6 @@
import pkg from "./package.json";
import git from "git-rev-sync";
import typescript from 'rollup-plugin-typescript2';
import typescript from "rollup-plugin-typescript2";
import { terser } from "rollup-plugin-terser";
import dts from "rollup-plugin-dts";
@@ -12,7 +12,7 @@ const ES_FILENAME = "dist/owl.es.js";
if (pkg.module !== ES_FILENAME || pkg.main !== CJS_FILENAME) {
throw new Error("package.json has been modified. Build script should be updated accordingly");
}
}
const outro = `
__info__.date = '${new Date().toISOString()}';
@@ -21,39 +21,37 @@ __info__.url = 'https://github.com/odoo/owl';
`;
switch (process.argv[4]) {
case "compiler":
input = "src/compiler/index.ts",
output = [
getConfigForFormat('cjs', 'dist/compiler.js', ''),
]
case "compiler":
(input = "src/compiler/index.ts"),
(output = [getConfigForFormat("cjs", "dist/compiler.js", "")]);
break;
case "runtime":
input = "src/runtime/index.ts";
output = [
getConfigForFormat('esm', addSuffix(ES_FILENAME, 'runtime'), outro),
getConfigForFormat('cjs', addSuffix(CJS_FILENAME, 'runtime'), outro),
getConfigForFormat('iife', addSuffix(IIFE_FILENAME, 'runtime'), outro),
getConfigForFormat('iife', addSuffix(IIFE_FILENAME, 'runtime'), outro, true),
]
getConfigForFormat("esm", addSuffix(ES_FILENAME, "runtime"), outro),
getConfigForFormat("cjs", addSuffix(CJS_FILENAME, "runtime"), outro),
getConfigForFormat("iife", addSuffix(IIFE_FILENAME, "runtime"), outro),
getConfigForFormat("iife", addSuffix(IIFE_FILENAME, "runtime"), outro, true),
];
break;
default:
input = "src/index.ts",
output = [
getConfigForFormat('esm', ES_FILENAME, outro),
getConfigForFormat('cjs', CJS_FILENAME, outro),
getConfigForFormat('iife', IIFE_FILENAME, outro),
getConfigForFormat('iife', IIFE_FILENAME, outro, true),
]
}
(input = "src/index.ts"),
(output = [
getConfigForFormat("esm", ES_FILENAME, outro),
getConfigForFormat("cjs", CJS_FILENAME, outro),
getConfigForFormat("iife", IIFE_FILENAME, outro),
getConfigForFormat("iife", IIFE_FILENAME, outro, true),
]);
}
/**
* Generate from a string depicting a path a new path for the minified version.
* @param {string} pkgFileName file name
*/
function addSuffix(pkgFileName, suffix) {
const parts = pkgFileName.split('.');
const parts = pkgFileName.split(".");
parts.splice(parts.length - 1, 0, suffix);
return parts.join('.');
return parts.join(".");
}
/**
@@ -71,7 +69,7 @@ function getConfigForFormat(format, generatedFileName, outro, minified = false)
outro: outro,
freeze: false,
plugins: minified ? [terser()] : [],
indent: ' ', // indent with 4 spaces
indent: " ", // indent with 4 spaces
};
}
@@ -81,9 +79,19 @@ export default [
output,
plugins: [
typescript({
useTsconfigDeclarationDir: true
useTsconfigDeclarationDir: true,
}),
]
],
},
{
input: "src/compiler/standalone/index.ts",
output: [{ file: "dist/compile_templates.mjs", format: "es" }],
external: ["fs", "fs/promises", "path", "jsdom"],
plugins: [
typescript({
useTsconfigDeclarationDir: true,
}),
],
},
{
input: "dist/types/index.d.ts",
+4
View File
@@ -0,0 +1,4 @@
// Custom error class that wraps error that happen in the owl lifecycle
export class OwlError extends Error {
cause?: any;
}
+4
View File
@@ -0,0 +1,4 @@
export type customDirectives = Record<
string,
(node: Element, value: string, modifier: string[]) => void
>;
+38
View File
@@ -0,0 +1,38 @@
import { OwlError } from "./owl_error";
/**
* Parses an XML string into an XML document, throwing errors on parser errors
* instead of returning an XML document containing the parseerror.
*
* @param xml the string to parse
* @returns an XML document corresponding to the content of the string
*/
export function parseXML(xml: string): XMLDocument {
const parser = new DOMParser();
const doc = parser.parseFromString(xml, "text/xml");
if (doc.getElementsByTagName("parsererror").length) {
let msg = "Invalid XML in template.";
const parsererrorText = doc.getElementsByTagName("parsererror")[0].textContent;
if (parsererrorText) {
msg += "\nThe parser has produced the following error message:\n" + parsererrorText;
const re = /\d+/g;
const firstMatch = re.exec(parsererrorText);
if (firstMatch) {
const lineNumber = Number(firstMatch[0]);
const line = xml.split("\n")[lineNumber - 1];
const secondMatch = re.exec(parsererrorText);
if (line && secondMatch) {
const columnIndex = Number(secondMatch[0]) - 1;
if (line[columnIndex]) {
msg +=
`\nThe error might be located at xml line ${lineNumber} column ${columnIndex}\n` +
`${line}\n${"-".repeat(columnIndex - 1)}^`;
}
}
}
}
throw new OwlError(msg);
}
return doc;
}
+140 -79
View File
@@ -24,18 +24,19 @@ import {
ASTTOut,
ASTTPortal,
ASTTranslation,
ASTTranslationContext,
ASTTSet,
ASTType,
Attrs,
EventHandlers,
} from "./parser";
import { OwlError } from "../runtime/error_handling";
import { OwlError } from "../common/owl_error";
type BlockType = "block" | "text" | "multi" | "list" | "html" | "comment";
const whitespaceRE = /\s+/g;
export interface Config {
translateFn?: (s: string) => string;
translateFn?: (s: string, translationCtx: string) => string;
translatableAttributes?: string[];
dev?: boolean;
}
@@ -43,6 +44,7 @@ export interface Config {
export interface CodeGenOptions extends Config {
hasSafeContext?: boolean;
name?: string;
hasGlobalValues: boolean;
}
// using a non-html document so that <inner/outer>HTML serializes as XML instead
@@ -82,6 +84,14 @@ function isProp(tag: string, key: string): boolean {
return false;
}
/**
* Returns a template literal that evaluates to str. You can add interpolation
* sigils into the string if required
*/
function toStringExpression(str: string) {
return `\`${str.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$\{/, "\\${")}\``;
}
// -----------------------------------------------------------------------------
// BlockDescription
// -----------------------------------------------------------------------------
@@ -160,9 +170,9 @@ interface Context {
block: BlockDescription | null;
index: number | string;
forceNewBlock: boolean;
preventRoot?: boolean;
isLast?: boolean;
translate: boolean;
translationCtx: string;
tKeyExpr: string | null;
nameSpace?: string;
tModelSelectedExpr?: string;
@@ -177,6 +187,7 @@ function createContext(parentCtx: Context, params?: Partial<Context>): Context {
index: 0,
forceNewBlock: true,
translate: parentCtx.translate,
translationCtx: parentCtx.translationCtx,
tKeyExpr: null,
nameSpace: parentCtx.nameSpace,
tModelSelectedExpr: parentCtx.tModelSelectedExpr,
@@ -243,7 +254,16 @@ class CodeTarget {
}
}
const TRANSLATABLE_ATTRS = ["label", "title", "placeholder", "alt"];
const TRANSLATABLE_ATTRS = [
"alt",
"aria-label",
"aria-placeholder",
"aria-roledescription",
"aria-valuetext",
"label",
"placeholder",
"title",
];
const translationRE = /^(\s*)([\s\S]+?)(\s*)$/;
export class CodeGenerator {
@@ -255,7 +275,7 @@ export class CodeGenerator {
target = new CodeTarget("template");
templateName?: string;
dev: boolean;
translateFn: (s: string) => string;
translateFn: (s: string, translationCtx: string) => string;
translatableAttributes: string[] = TRANSLATABLE_ATTRS;
ast: AST;
staticDefs: { id: string; expr: string }[] = [];
@@ -279,6 +299,9 @@ export class CodeGenerator {
this.dev = options.dev || false;
this.ast = ast;
this.templateName = options.name;
if (options.hasGlobalValues) {
this.helpers.add("__globals__");
}
}
generateCode(): string {
@@ -292,6 +315,7 @@ export class CodeGenerator {
forceNewBlock: false,
isLast: true,
translate: true,
translationCtx: "",
tKeyExpr: null,
});
// define blocks and utility functions
@@ -312,14 +336,13 @@ export class CodeGenerator {
mainCode.push(``);
for (let block of this.blocks) {
if (block.dom) {
let xmlString = block.asXmlString();
xmlString = xmlString.replace(/\\/g, "\\\\").replace(/`/g, "\\`");
let xmlString = toStringExpression(block.asXmlString());
if (block.dynamicTagName) {
xmlString = xmlString.replace(/^<\w+/, `<\${tag || '${block.dom.nodeName}'}`);
xmlString = xmlString.replace(/\w+>$/, `\${tag || '${block.dom.nodeName}'}>`);
mainCode.push(`let ${block.blockName} = tag => createBlock(\`${xmlString}\`);`);
xmlString = xmlString.replace(/^`<\w+/, `\`<\${tag || '${block.dom.nodeName}'}`);
xmlString = xmlString.replace(/\w+>`$/, `\${tag || '${block.dom.nodeName}'}>\``);
mainCode.push(`let ${block.blockName} = tag => createBlock(${xmlString});`);
} else {
mainCode.push(`let ${block.blockName} = createBlock(\`${xmlString}\`);`);
mainCode.push(`let ${block.blockName} = createBlock(${xmlString});`);
}
}
}
@@ -377,7 +400,7 @@ export class CodeGenerator {
): BlockDescription {
const hasRoot = this.target.hasRoot;
const block = new BlockDescription(this.target, type);
if (!hasRoot && !ctx.preventRoot) {
if (!hasRoot) {
this.target.hasRoot = true;
block.isRoot = true;
}
@@ -403,7 +426,7 @@ export class CodeGenerator {
blockExpr = `toggler(${ctx.tKeyExpr}, ${blockExpr})`;
}
if (block.isRoot && !ctx.preventRoot) {
if (block.isRoot) {
if (this.target.on) {
blockExpr = this.wrapWithEventCatcher(blockExpr, this.target.on);
}
@@ -447,6 +470,11 @@ export class CodeGenerator {
.join("");
}
translate(str: string, translationCtx: string): string {
const match = translationRE.exec(str) as any;
return match[1] + this.translateFn(match[2], translationCtx) + match[3];
}
/**
* @returns the newly created block name, if any
*/
@@ -486,6 +514,8 @@ export class CodeGenerator {
return this.compileTSlot(ast, ctx);
case ASTType.TTranslation:
return this.compileTTranslation(ast, ctx);
case ASTType.TTranslationContext:
return this.compileTTranslationContext(ast, ctx);
case ASTType.TPortal:
return this.compileTPortal(ast, ctx);
}
@@ -511,7 +541,7 @@ export class CodeGenerator {
const isNewBlock = !block || forceNewBlock;
if (isNewBlock) {
block = this.createBlock(block, "comment", ctx);
this.insertBlock(`comment(\`${ast.value}\`)`, block, {
this.insertBlock(`comment(${toStringExpression(ast.value)})`, block, {
...ctx,
forceNewBlock: forceNewBlock && !block,
});
@@ -527,8 +557,7 @@ export class CodeGenerator {
let value = ast.value;
if (value && ctx.translate !== false) {
const match = translationRE.exec(value) as any;
value = match[1] + this.translateFn(match[2]) + match[3];
value = this.translate(value, ctx.translationCtx);
}
if (!ctx.inPreTag) {
value = value.replace(whitespaceRE, " ");
@@ -536,7 +565,7 @@ export class CodeGenerator {
if (!block || forceNewBlock) {
block = this.createBlock(block, "text", ctx);
this.insertBlock(`text(\`${value}\`)`, block, {
this.insertBlock(`text(${toStringExpression(value)})`, block, {
...ctx,
forceNewBlock: forceNewBlock && !block,
});
@@ -582,11 +611,6 @@ export class CodeGenerator {
}
// attributes
const attrs: Attrs = {};
const nameSpace = ast.ns || ctx.nameSpace;
if (nameSpace && isNewBlock) {
// specific namespace uri
attrs["block-ns"] = nameSpace;
}
for (let key in ast.attrs) {
let expr, attrName;
@@ -622,7 +646,8 @@ export class CodeGenerator {
}
}
} else if (this.translatableAttributes.includes(key)) {
attrs[key] = this.translateFn(ast.attrs[key]);
const attrTranslationCtx = ast.attrsTranslationCtx?.[key] || ctx.translationCtx;
attrs[key] = this.translateFn(ast.attrs[key], attrTranslationCtx);
} else {
expr = `"${ast.attrs[key]}"`;
attrName = key;
@@ -715,7 +740,10 @@ export class CodeGenerator {
attrs["block-ref"] = String(idx);
}
const dom = xmlDoc.createElement(ast.tag);
const nameSpace = ast.ns || ctx.nameSpace;
const dom = nameSpace
? xmlDoc.createElementNS(nameSpace, ast.tag)
: xmlDoc.createElement(ast.tag);
for (const [attr, val] of Object.entries(attrs)) {
if (!(attr === "class" && val === "")) {
dom.setAttribute(attr, val);
@@ -757,7 +785,7 @@ export class CodeGenerator {
if (!current) break;
}
}
this.addLine(`let ${block!.children.map((c) => c.varName)};`, codeIdx);
this.addLine(`let ${block!.children.map((c) => c.varName).join(", ")};`, codeIdx);
}
}
return block!.varName;
@@ -773,7 +801,8 @@ export class CodeGenerator {
expr = compileExpr(ast.expr);
if (ast.defaultValue) {
this.helpers.add("withDefault");
expr = `withDefault(${expr}, \`${ast.defaultValue}\`)`;
// FIXME: defaultValue is not translated
expr = `withDefault(${expr}, ${toStringExpression(ast.defaultValue)})`;
}
}
if (!block || forceNewBlock) {
@@ -859,7 +888,7 @@ export class CodeGenerator {
if (!current) break;
}
}
this.addLine(`let ${block!.children.map((c) => c.varName)};`, codeIdx);
this.addLine(`let ${block!.children.map((c) => c.varName).join(", ")};`, codeIdx);
}
// note: this part is duplicated from end of compilemulti:
@@ -890,18 +919,18 @@ export class CodeGenerator {
}
this.addLine(`for (let ${loopVar} = 0; ${loopVar} < ${l}; ${loopVar}++) {`);
this.target.indentLevel++;
this.addLine(`ctx[\`${ast.elem}\`] = ${vals}[${loopVar}];`);
this.addLine(`ctx[\`${ast.elem}\`] = ${keys}[${loopVar}];`);
if (!ast.hasNoFirst) {
this.addLine(`ctx[\`${ast.elem}_first\`] = ${loopVar} === 0;`);
}
if (!ast.hasNoLast) {
this.addLine(`ctx[\`${ast.elem}_last\`] = ${loopVar} === ${vals}.length - 1;`);
this.addLine(`ctx[\`${ast.elem}_last\`] = ${loopVar} === ${keys}.length - 1;`);
}
if (!ast.hasNoIndex) {
this.addLine(`ctx[\`${ast.elem}_index\`] = ${loopVar};`);
}
if (!ast.hasNoValue) {
this.addLine(`ctx[\`${ast.elem}_value\`] = ${keys}[${loopVar}];`);
this.addLine(`ctx[\`${ast.elem}_value\`] = ${vals}[${loopVar}];`);
}
this.define(`key${this.target.loopLevel}`, ast.key ? compileExpr(ast.key) : loopVar);
if (this.dev) {
@@ -966,7 +995,7 @@ export class CodeGenerator {
const isNewBlock = !block || forceNewBlock;
let codeIdx = this.target.code.length;
if (isNewBlock) {
const n = ast.content.filter((c) => c.type !== ASTType.TSet).length;
const n = ast.content.filter((c) => !c.hasNoRepresentation).length;
let result: string | null = null;
if (n <= 1) {
for (let child of ast.content) {
@@ -980,34 +1009,31 @@ export class CodeGenerator {
let index = 0;
for (let i = 0, l = ast.content.length; i < l; i++) {
const child = ast.content[i];
const isTSet = child.type === ASTType.TSet;
const forceNewBlock = !child.hasNoRepresentation;
const subCtx = createContext(ctx, {
block,
index,
forceNewBlock: !isTSet,
preventRoot: ctx.preventRoot,
forceNewBlock,
isLast: ctx.isLast && i === l - 1,
});
this.compileAST(child, subCtx);
if (!isTSet) {
if (forceNewBlock) {
index++;
}
}
if (isNewBlock) {
if (block!.hasDynamicChildren) {
if (block!.children.length) {
const code = this.target.code;
const children = block!.children.slice();
let current = children.shift();
for (let i = codeIdx; i < code.length; i++) {
if (code[i].trimStart().startsWith(`const ${current!.varName} `)) {
code[i] = code[i].replace(`const ${current!.varName}`, current!.varName);
current = children.shift();
if (!current) break;
}
if (block!.hasDynamicChildren && block!.children.length) {
const code = this.target.code;
const children = block!.children.slice();
let current = children.shift();
for (let i = codeIdx; i < code.length; i++) {
if (code[i].trimStart().startsWith(`const ${current!.varName} `)) {
code[i] = code[i].replace(`const ${current!.varName}`, current!.varName);
current = children.shift();
if (!current) break;
}
this.addLine(`let ${block!.children.map((c) => c.varName)};`, codeIdx);
}
this.addLine(`let ${block!.children.map((c) => c.varName).join(", ")};`, codeIdx);
}
const args = block!.children.map((c) => c.varName).join(", ");
@@ -1023,32 +1049,31 @@ export class CodeGenerator {
ctxVar = generateId("ctx");
this.addLine(`let ${ctxVar} = ${compileExpr(ast.context)};`);
}
const isDynamic = INTERP_REGEXP.test(ast.name);
const subTemplate = isDynamic ? interpolate(ast.name) : "`" + ast.name + "`";
if (block && !forceNewBlock) {
this.insertAnchor(block);
}
block = this.createBlock(block, "multi", ctx);
if (ast.body) {
this.addLine(`${ctxVar} = Object.create(${ctxVar});`);
this.addLine(`${ctxVar}[isBoundary] = 1;`);
this.helpers.add("isBoundary");
const subCtx = createContext(ctx, { preventRoot: true, ctxVar });
const subCtx = createContext(ctx, { ctxVar });
const bl = this.compileMulti({ type: ASTType.Multi, content: ast.body }, subCtx);
if (bl) {
this.helpers.add("zero");
this.addLine(`${ctxVar}[zero] = ${bl};`);
}
}
const isDynamic = INTERP_REGEXP.test(ast.name);
const subTemplate = isDynamic ? interpolate(ast.name) : "`" + ast.name + "`";
if (block) {
if (!forceNewBlock) {
this.insertAnchor(block);
}
}
const key = `key + \`${this.generateComponentKey()}\``;
const key = this.generateComponentKey();
if (isDynamic) {
const templateVar = generateId("template");
if (!this.staticDefs.find((d) => d.id === "call")) {
this.staticDefs.push({ id: "call", expr: `app.callTemplate.bind(app)` });
}
this.define(templateVar, subTemplate);
block = this.createBlock(block, "multi", ctx);
this.insertBlock(`call(this, ${templateVar}, ${ctxVar}, node, ${key})`, block!, {
...ctx,
forceNewBlock: !block,
@@ -1056,7 +1081,6 @@ export class CodeGenerator {
} else {
const id = generateId(`callTemplate_`);
this.staticDefs.push({ id, expr: `app.getTemplate(${subTemplate})` });
block = this.createBlock(block, "multi", ctx);
this.insertBlock(`${id}.call(this, ${ctxVar}, node, ${key})`, block!, {
...ctx,
forceNewBlock: !block,
@@ -1095,10 +1119,13 @@ export class CodeGenerator {
} else {
let value: string;
if (ast.defaultValue) {
const defaultValue = toStringExpression(
ctx.translate ? this.translate(ast.defaultValue, ctx.translationCtx) : ast.defaultValue
);
if (ast.value) {
value = `withDefault(${expr}, \`${ast.defaultValue}\`)`;
value = `withDefault(${expr}, ${defaultValue})`;
} else {
value = `\`${ast.defaultValue}\``;
value = defaultValue;
}
} else {
value = expr;
@@ -1109,12 +1136,12 @@ export class CodeGenerator {
return null;
}
generateComponentKey() {
generateComponentKey(currentKey: string = "key") {
const parts = [generateId("__")];
for (let i = 0; i < this.target.loopLevel; i++) {
parts.push(`\${key${i + 1}}`);
}
return parts.join("__");
return `${currentKey} + \`${parts.join("__")}\``;
}
/**
@@ -1128,8 +1155,18 @@ export class CodeGenerator {
* "some-prop" "state" "'some-prop': ctx['state']"
* "onClick.bind" "onClick" "onClick: bind(ctx, ctx['onClick'])"
*/
formatProp(name: string, value: string): string {
value = this.captureExpression(value);
formatProp(
name: string,
value: string,
attrsTranslationCtx: { [name: string]: string } | null,
translationCtx: string
): string {
if (name.endsWith(".translate")) {
const attrTranslationCtx = attrsTranslationCtx?.[name] || translationCtx;
value = toStringExpression(this.translateFn(value, attrTranslationCtx));
} else {
value = this.captureExpression(value);
}
if (name.includes(".")) {
let [_name, suffix] = name.split(".");
name = _name;
@@ -1138,17 +1175,24 @@ export class CodeGenerator {
value = `(${value}).bind(this)`;
break;
case "alike":
case "translate":
break;
default:
throw new OwlError("Invalid prop suffix");
throw new OwlError(`Invalid prop suffix: ${suffix}`);
}
}
name = /^[a-z_]+$/i.test(name) ? name : `'${name}'`;
return `${name}: ${value || undefined}`;
}
formatPropObject(obj: { [prop: string]: any }): string[] {
return Object.entries(obj).map(([k, v]) => this.formatProp(k, v));
formatPropObject(
obj: { [prop: string]: any },
attrsTranslationCtx: { [name: string]: string } | null,
translationCtx: string
): string[] {
return Object.entries(obj).map(([k, v]) =>
this.formatProp(k, v, attrsTranslationCtx, translationCtx)
);
}
getPropString(props: string[], dynProps: string | null): string {
@@ -1165,7 +1209,9 @@ export class CodeGenerator {
let { block } = ctx;
// props
const hasSlotsProp = "slots" in (ast.props || {});
const props: string[] = ast.props ? this.formatPropObject(ast.props) : [];
const props: string[] = ast.props
? this.formatPropObject(ast.props, ast.propsTranslationCtx, ctx.translationCtx)
: [];
// slots
let slotDef: string = "";
@@ -1189,7 +1235,13 @@ export class CodeGenerator {
params.push(`__scope: "${scope}"`);
}
if (ast.slots[slotName].attrs) {
params.push(...this.formatPropObject(ast.slots[slotName].attrs!));
params.push(
...this.formatPropObject(
ast.slots[slotName].attrs!,
ast.slots[slotName].attrsTranslationCtx,
ctx.translationCtx
)
);
}
const slotInfo = `{${params.join(", ")}}`;
slotStr.push(`'${slotName}': ${slotInfo}`);
@@ -1217,7 +1269,6 @@ export class CodeGenerator {
}
// cmap key
const key = this.generateComponentKey();
let expr: string;
if (ast.isDynamic) {
expr = generateId("Comp");
@@ -1235,7 +1286,7 @@ export class CodeGenerator {
this.insertAnchor(block);
}
let keyArg = `key + \`${key}\``;
let keyArg = this.generateComponentKey();
if (ctx.tKeyExpr) {
keyArg = `${ctx.tKeyExpr} + ${keyArg}`;
}
@@ -1308,16 +1359,17 @@ export class CodeGenerator {
isMultiple = isMultiple || this.slotNames.has(ast.name);
this.slotNames.add(ast.name);
}
const dynProps = ast.attrs ? ast.attrs["t-props"] : null;
if (ast.attrs) {
delete ast.attrs["t-props"];
}
const attrs = { ...ast.attrs };
const dynProps = attrs["t-props"];
delete attrs["t-props"];
let key = this.target.loopLevel ? `key${this.target.loopLevel}` : "key";
if (isMultiple) {
key = `${key} + \`${this.generateComponentKey()}\``;
key = this.generateComponentKey(key);
}
const props = ast.attrs ? this.formatPropObject(ast.attrs) : [];
const props = ast.attrs
? this.formatPropObject(attrs, ast.attrsTranslationCtx, ctx.translationCtx)
: [];
const scope = this.getPropString(props, dynProps);
if (ast.defaultContent) {
const name = this.compileInNewTarget("defaultContent", ast.defaultContent, ctx);
@@ -1350,6 +1402,15 @@ export class CodeGenerator {
}
return null;
}
compileTTranslationContext(ast: ASTTranslationContext, ctx: Context): string | null {
if (ast.content) {
return this.compileAST(
ast.content,
Object.assign({}, ctx, { translationCtx: ast.translationCtx })
);
}
return null;
}
compileTPortal(ast: ASTTPortal, ctx: Context): string {
if (!this.staticDefs.find((d) => d.id === "Portal")) {
this.staticDefs.push({ id: "Portal", expr: `app.Portal` });
@@ -1357,7 +1418,6 @@ export class CodeGenerator {
let { block } = ctx;
const name = this.compileInNewTarget("slot", ast.content, ctx);
const key = this.generateComponentKey();
let ctxStr = "ctx";
if (this.target.loopLevel || !this.hasSafeContext) {
ctxStr = generateId("ctx");
@@ -1371,7 +1431,8 @@ export class CodeGenerator {
});
const target = compileExpr(ast.target);
const blockString = `${id}({target: ${target},slots: {'default': {__render: ${name}.bind(this), __ctx: ${ctxStr}}}}, key + \`${key}\`, node, ctx, Portal)`;
const key = this.generateComponentKey();
const blockString = `${id}({target: ${target},slots: {'default': {__render: ${name}.bind(this), __ctx: ${ctxStr}}}}, ${key}, node, ctx, Portal)`;
if (block) {
this.insertAnchor(block);
}
+19 -3
View File
@@ -1,7 +1,9 @@
import type { customDirectives } from "../common/types";
import type { TemplateSet } from "../runtime/template_set";
import type { BDom } from "../runtime/blockdom";
import { CodeGenerator, Config } from "./code_generator";
import { parse } from "./parser";
import { OwlError } from "../common/owl_error";
export type Template = (context: any, vnode: any, key?: string) => BDom;
@@ -9,13 +11,17 @@ export type TemplateFunction = (app: TemplateSet, bdom: any, helpers: any) => Te
interface CompileOptions extends Config {
name?: string;
customDirectives?: customDirectives;
hasGlobalValues: boolean;
}
export function compile(
template: string | Element,
options: CompileOptions = {}
options: CompileOptions = {
hasGlobalValues: false,
}
): TemplateFunction {
// parsing
const ast = parse(template);
const ast = parse(template, options.customDirectives);
// some work
const hasSafeContext =
@@ -27,5 +33,15 @@ export function compile(
const codeGenerator = new CodeGenerator(ast, { ...options, hasSafeContext });
const code = codeGenerator.generateCode();
// template function
return new Function("app, bdom, helpers", code) as TemplateFunction;
try {
return new Function("app, bdom, helpers", code) as TemplateFunction;
} catch (originalError: any) {
const { name } = options;
const nameStr = name ? `template "${name}"` : "anonymous template";
const err = new OwlError(
`Failed to compile ${nameStr}: ${originalError.message}\n\ngenerated code:\nfunction(app, bdom, helpers) {\n${code}\n}`
);
err.cause = originalError;
throw err;
}
}
+5 -3
View File
@@ -1,4 +1,4 @@
import { OwlError } from "../runtime/error_handling";
import { OwlError } from "../common/owl_error";
/**
* Owl QWeb Expression Parser
@@ -28,7 +28,7 @@ import { OwlError } from "../runtime/error_handling";
//------------------------------------------------------------------------------
const RESERVED_WORDS =
"true,false,NaN,null,undefined,debugger,console,window,in,instanceof,new,function,return,eval,void,Math,RegExp,Array,Object,Date".split(
"true,false,NaN,null,undefined,debugger,console,window,in,instanceof,new,function,return,eval,void,Math,RegExp,Array,Object,Date,__globals__".split(
","
);
@@ -268,7 +268,7 @@ export function compileExprToArray(expr: string): Token[] {
const localVars = new Set<string>();
const tokens = tokenize(expr);
let i = 0;
let stack = []; // to track last opening [ or {
let stack = []; // to track last opening (, [ or {
while (i < tokens.length) {
let token = tokens[i];
@@ -279,10 +279,12 @@ export function compileExprToArray(expr: string): Token[] {
switch (token.type) {
case "LEFT_BRACE":
case "LEFT_BRACKET":
case "LEFT_PAREN":
stack.push(token.type);
break;
case "RIGHT_BRACE":
case "RIGHT_BRACKET":
case "RIGHT_PAREN":
stack.pop();
}
+251 -115
View File
@@ -1,4 +1,6 @@
import { OwlError } from "../runtime/error_handling";
import { OwlError } from "../common/owl_error";
import type { customDirectives } from "../common/types";
import { parseXML } from "../common/utils";
// -----------------------------------------------------------------------------
// AST Type definition
@@ -25,15 +27,21 @@ export const enum ASTType {
TSlot,
TCallBlock,
TTranslation,
TTranslationContext,
TPortal,
}
export interface ASTText {
export interface BaseAST {
type: ASTType;
hasNoRepresentation?: true;
}
export interface ASTText extends BaseAST {
type: ASTType.Text;
value: string;
}
export interface ASTComment {
export interface ASTComment extends BaseAST {
type: ASTType.Comment;
value: string;
}
@@ -49,11 +57,12 @@ interface TModelInfo {
specialInitTargetAttr: string | null;
}
export interface ASTDomNode {
export interface ASTDomNode extends BaseAST {
type: ASTType.DomNode;
tag: string;
content: AST[];
attrs: Attrs | null;
attrsTranslationCtx: Attrs | null;
ref: string | null;
on: EventHandlers | null;
model: TModelInfo | null;
@@ -61,24 +70,24 @@ export interface ASTDomNode {
ns: string | null;
}
export interface ASTMulti {
export interface ASTMulti extends BaseAST {
type: ASTType.Multi;
content: AST[];
}
export interface ASTTEsc {
export interface ASTTEsc extends BaseAST {
type: ASTType.TEsc;
expr: string;
defaultValue: string;
}
export interface ASTTOut {
export interface ASTTOut extends BaseAST {
type: ASTType.TOut;
expr: string;
body: AST[] | null;
}
export interface ASTTif {
export interface ASTTif extends BaseAST {
type: ASTType.TIf;
condition: string;
content: AST;
@@ -86,15 +95,16 @@ export interface ASTTif {
tElse: AST | null;
}
export interface ASTTSet {
export interface ASTTSet extends BaseAST {
type: ASTType.TSet;
name: string;
value: string | null; // value defined in attribute
defaultValue: string | null; // value defined in body, if text
body: AST[] | null; // content of body if not text
hasNoRepresentation: true;
}
export interface ASTTForEach {
export interface ASTTForEach extends BaseAST {
type: ASTType.TForEach;
collection: string;
elem: string;
@@ -107,13 +117,13 @@ export interface ASTTForEach {
key: string | null;
}
export interface ASTTKey {
export interface ASTTKey extends BaseAST {
type: ASTType.TKey;
expr: string;
content: AST;
}
export interface ASTTCall {
export interface ASTTCall extends BaseAST {
type: ASTType.TCall;
name: string;
body: AST[] | null;
@@ -125,48 +135,57 @@ interface SlotDefinition {
scope: string | null;
on: EventHandlers | null;
attrs: Attrs | null;
attrsTranslationCtx: Attrs | null;
}
export interface ASTComponent {
export interface ASTComponent extends BaseAST {
type: ASTType.TComponent;
name: string;
isDynamic: boolean;
dynamicProps: string | null;
on: EventHandlers | null;
props: { [name: string]: string } | null;
propsTranslationCtx: { [name: string]: string } | null;
slots: { [name: string]: SlotDefinition } | null;
}
export interface ASTSlot {
export interface ASTSlot extends BaseAST {
type: ASTType.TSlot;
name: string;
attrs: Attrs | null;
attrsTranslationCtx: Attrs | null;
on: EventHandlers | null;
defaultContent: AST | null;
}
export interface ASTTCallBlock {
export interface ASTTCallBlock extends BaseAST {
type: ASTType.TCallBlock;
name: string;
}
export interface ASTDebug {
export interface ASTDebug extends BaseAST {
type: ASTType.TDebug;
content: AST | null;
}
export interface ASTLog {
export interface ASTLog extends BaseAST {
type: ASTType.TLog;
expr: string;
content: AST | null;
}
export interface ASTTranslation {
export interface ASTTranslation extends BaseAST {
type: ASTType.TTranslation;
content: AST | null;
}
export interface ASTTPortal {
export interface ASTTranslationContext extends BaseAST {
type: ASTType.TTranslationContext;
content: AST | null;
translationCtx: string;
}
export interface ASTTPortal extends BaseAST {
type: ASTType.TPortal;
target: string;
content: AST;
@@ -190,6 +209,7 @@ export type AST =
| ASTLog
| ASTDebug
| ASTTranslation
| ASTTranslationContext
| ASTTPortal;
// -----------------------------------------------------------------------------
@@ -197,30 +217,34 @@ export type AST =
// -----------------------------------------------------------------------------
const cache: WeakMap<Element, AST> = new WeakMap();
export function parse(xml: string | Element): AST {
export function parse(xml: string | Element, customDir?: customDirectives): AST {
const ctx = {
inPreTag: false,
customDirectives: customDir,
};
if (typeof xml === "string") {
const elem = parseXML(`<t>${xml}</t>`).firstChild as Element;
return _parse(elem);
return _parse(elem, ctx);
}
let ast = cache.get(xml);
if (!ast) {
// we clone here the xml to prevent modifying it in place
ast = _parse(xml.cloneNode(true) as Element);
ast = _parse(xml.cloneNode(true) as Element, ctx);
cache.set(xml, ast);
}
return ast;
}
function _parse(xml: Element): AST {
function _parse(xml: Element, ctx: ParsingContext): AST {
normalizeXML(xml);
const ctx = { inPreTag: false, inSVG: false };
return parseNode(xml, ctx) || { type: ASTType.Text, value: "" };
}
interface ParsingContext {
tModelInfo?: TModelInfo | null;
nameSpace?: string;
inPreTag: boolean;
inSVG: boolean;
customDirectives?: customDirectives;
}
function parseNode(node: Node, ctx: ParsingContext): AST | null {
@@ -228,17 +252,19 @@ function parseNode(node: Node, ctx: ParsingContext): AST | null {
return parseTextCommentNode(node, ctx);
}
return (
parseTCustom(node, ctx) ||
parseTDebugLog(node, ctx) ||
parseTForEach(node, ctx) ||
parseTIf(node, ctx) ||
parseTPortal(node, ctx) ||
parseTCall(node, ctx) ||
parseTCallBlock(node, ctx) ||
parseTEscNode(node, ctx) ||
parseTKey(node, ctx) ||
parseTTranslation(node, ctx) ||
parseTSlot(node, ctx) ||
parseTTranslationContext(node, ctx) ||
parseTKey(node, ctx) ||
parseTEscNode(node, ctx) ||
parseTOutNode(node, ctx) ||
parseTSlot(node, ctx) ||
parseComponent(node, ctx) ||
parseDOMNode(node, ctx) ||
parseTSetNode(node, ctx) ||
@@ -276,6 +302,37 @@ function parseTextCommentNode(node: Node, ctx: ParsingContext): AST | null {
return null;
}
function parseTCustom(node: Element, ctx: ParsingContext): AST | null {
if (!ctx.customDirectives) {
return null;
}
const nodeAttrsNames = node.getAttributeNames();
for (let attr of nodeAttrsNames) {
if (attr === "t-custom" || attr === "t-custom-") {
throw new OwlError("Missing custom directive name with t-custom directive");
}
if (attr.startsWith("t-custom-")) {
const directiveName = attr.split(".")[0].slice(9);
const customDirective = ctx.customDirectives[directiveName];
if (!customDirective) {
throw new OwlError(`Custom directive "${directiveName}" is not defined`);
}
const value = node.getAttribute(attr)!;
const modifiers = attr.split(".").slice(1);
node.removeAttribute(attr);
try {
customDirective(node, value, modifiers);
} catch (error) {
throw new OwlError(
`Custom directive "${directiveName}" throw the following error: ${error}`
);
}
return parseNode(node, ctx);
}
}
return null;
}
// -----------------------------------------------------------------------------
// debugging
// -----------------------------------------------------------------------------
@@ -283,20 +340,30 @@ function parseTextCommentNode(node: Node, ctx: ParsingContext): AST | null {
function parseTDebugLog(node: Element, ctx: ParsingContext): AST | null {
if (node.hasAttribute("t-debug")) {
node.removeAttribute("t-debug");
return {
const content = parseNode(node, ctx);
const ast: ASTDebug = {
type: ASTType.TDebug,
content: parseNode(node, ctx),
content,
};
if (content?.hasNoRepresentation) {
ast.hasNoRepresentation = true;
}
return ast;
}
if (node.hasAttribute("t-log")) {
const expr = node.getAttribute("t-log")!;
node.removeAttribute("t-log");
return {
const content = parseNode(node, ctx);
const ast: ASTLog = {
type: ASTType.TLog,
expr,
content: parseNode(node, ctx),
content,
};
if (content?.hasNoRepresentation) {
ast.hasNoRepresentation = true;
}
return ast;
}
return null;
}
@@ -323,23 +390,23 @@ function parseDOMNode(node: Element, ctx: ParsingContext): AST | null {
if (tagName === "pre") {
ctx.inPreTag = true;
}
const shouldAddSVGNS = ROOT_SVG_TAGS.has(tagName) && !ctx.inSVG;
ctx.inSVG = ctx.inSVG || shouldAddSVGNS;
const ns = shouldAddSVGNS ? "http://www.w3.org/2000/svg" : null;
let ns = !ctx.nameSpace && ROOT_SVG_TAGS.has(tagName) ? "http://www.w3.org/2000/svg" : null;
const ref = node.getAttribute("t-ref");
node.removeAttribute("t-ref");
const nodeAttrsNames = node.getAttributeNames();
let attrs: ASTDomNode["attrs"] = null;
let attrsTranslationCtx: ASTDomNode["attrsTranslationCtx"] = null;
let on: EventHandlers | null = null;
let model: TModelInfo | null = null;
for (let attr of nodeAttrsNames) {
const value = node.getAttribute(attr)!;
if (attr.startsWith("t-on")) {
if (attr === "t-on") {
throw new OwlError("Missing event name with t-on directive");
}
if (attr === "t-on" || attr === "t-on-") {
throw new OwlError("Missing event name with t-on directive");
}
if (attr.startsWith("t-on-")) {
on = on || {};
on[attr.slice(5)] = value;
} else if (attr.startsWith("t-model")) {
@@ -365,13 +432,11 @@ function parseDOMNode(node: Element, ctx: ParsingContext): AST | null {
const typeAttr = node.getAttribute("type");
const isInput = tagName === "input";
const isSelect = tagName === "select";
const isTextarea = tagName === "textarea";
const isCheckboxInput = isInput && typeAttr === "checkbox";
const isRadioInput = isInput && typeAttr === "radio";
const isOtherInput = isInput && !isCheckboxInput && !isRadioInput;
const hasLazyMod = attr.includes(".lazy");
const hasNumberMod = attr.includes(".number");
const hasTrimMod = attr.includes(".trim");
const hasLazyMod = hasTrimMod || attr.includes(".lazy");
const hasNumberMod = attr.includes(".number");
const eventType = isRadioInput ? "click" : isSelect || hasLazyMod ? "change" : "input";
model = {
@@ -381,8 +446,8 @@ function parseDOMNode(node: Element, ctx: ParsingContext): AST | null {
specialInitTargetAttr: isRadioInput ? "checked" : null,
eventType,
hasDynamicChildren: false,
shouldTrim: hasTrimMod && (isOtherInput || isTextarea),
shouldNumberize: hasNumberMod && (isOtherInput || isTextarea),
shouldTrim: hasTrimMod,
shouldNumberize: hasNumberMod,
};
if (isSelect) {
// don't pollute the original ctx
@@ -391,6 +456,12 @@ function parseDOMNode(node: Element, ctx: ParsingContext): AST | null {
}
} else if (attr.startsWith("block-")) {
throw new OwlError(`Invalid attribute: '${attr}'`);
} else if (attr === "xmlns") {
ns = value;
} else if (attr.startsWith("t-translation-context-")) {
const attrName = attr.slice(22);
attrsTranslationCtx = attrsTranslationCtx || {};
attrsTranslationCtx[attrName] = value;
} else if (attr !== "t-name") {
if (attr.startsWith("t-") && !attr.startsWith("t-att")) {
throw new OwlError(`Unknown QWeb directive: '${attr}'`);
@@ -403,6 +474,9 @@ function parseDOMNode(node: Element, ctx: ParsingContext): AST | null {
attrs[attr] = value;
}
}
if (ns) {
ctx.nameSpace = ns;
}
const children = parseChildren(node, ctx);
return {
@@ -410,6 +484,7 @@ function parseDOMNode(node: Element, ctx: ParsingContext): AST | null {
tag: tagName,
dynamicTag,
attrs,
attrsTranslationCtx,
on,
ref,
content: children,
@@ -446,9 +521,6 @@ function parseTEscNode(node: Element, ctx: ParsingContext): AST | null {
content: [tesc],
};
}
if (ast.type === ASTType.TComponent) {
throw new OwlError("t-esc is not supported on Component nodes");
}
return tesc;
}
@@ -542,11 +614,19 @@ function parseTKey(node: Element, ctx: ParsingContext): AST | null {
}
const key = node.getAttribute("t-key")!;
node.removeAttribute("t-key");
const body = parseNode(node, ctx);
if (!body) {
const content = parseNode(node, ctx);
if (!content) {
return null;
}
return { type: ASTType.TKey, expr: key, content: body };
const ast: ASTTKey = {
type: ASTType.TKey,
expr: key,
content,
};
if (content.hasNoRepresentation) {
ast.hasNoRepresentation = true;
}
return ast;
}
// -----------------------------------------------------------------------------
@@ -572,7 +652,15 @@ function parseTCall(node: Element, ctx: ParsingContext): AST | null {
if (ast && ast.type === ASTType.TComponent) {
return {
...ast,
slots: { default: { content: tcall, scope: null, on: null, attrs: null } },
slots: {
default: {
content: tcall,
scope: null,
on: null,
attrs: null,
attrsTranslationCtx: null,
},
},
};
}
}
@@ -660,7 +748,7 @@ function parseTSetNode(node: Element, ctx: ParsingContext): AST | null {
if (node.textContent !== node.innerHTML) {
body = parseChildren(node, ctx);
}
return { type: ASTType.TSet, name, value, defaultValue, body };
return { type: ASTType.TSet, name, value, defaultValue, body, hasNoRepresentation: true };
}
// -----------------------------------------------------------------------------
@@ -707,9 +795,14 @@ function parseComponent(node: Element, ctx: ParsingContext): AST | null {
let on: ASTComponent["on"] = null;
let props: ASTComponent["props"] = null;
let propsTranslationCtx: ASTComponent["propsTranslationCtx"] = null;
for (let name of node.getAttributeNames()) {
const value = node.getAttribute(name)!;
if (name.startsWith("t-")) {
if (name.startsWith("t-translation-context-")) {
const attrName = name.slice(22);
propsTranslationCtx = propsTranslationCtx || {};
propsTranslationCtx[attrName] = value;
} else if (name.startsWith("t-")) {
if (name.startsWith("t-on-")) {
on = on || {};
on[name.slice(5)] = value;
@@ -741,14 +834,14 @@ function parseComponent(node: Element, ctx: ParsingContext): AST | null {
// be ignored)
let el = slotNode.parentElement!;
let isInSubComponent = false;
while (el !== clone) {
while (el && el !== clone) {
if (el!.hasAttribute("t-component") || el!.tagName[0] === el!.tagName[0].toUpperCase()) {
isInSubComponent = true;
break;
}
el = el.parentElement!;
}
if (isInSubComponent) {
if (isInSubComponent || !el) {
continue;
}
@@ -757,12 +850,17 @@ function parseComponent(node: Element, ctx: ParsingContext): AST | null {
const slotAst = parseNode(slotNode, ctx);
let on: SlotDefinition["on"] = null;
let attrs: Attrs | null = null;
let attrsTranslationCtx: Attrs | null = null;
let scope: string | null = null;
for (let attributeName of slotNode.getAttributeNames()) {
const value = slotNode.getAttribute(attributeName)!;
if (attributeName === "t-slot-scope") {
scope = value;
continue;
} else if (attributeName.startsWith("t-translation-context-")) {
const attrName = attributeName.slice(22);
attrsTranslationCtx = attrsTranslationCtx || {};
attrsTranslationCtx[attrName] = value;
} else if (attributeName.startsWith("t-on-")) {
on = on || {};
on[attributeName.slice(5)] = value;
@@ -772,7 +870,7 @@ function parseComponent(node: Element, ctx: ParsingContext): AST | null {
}
}
slots = slots || {};
slots[name] = { content: slotAst, on, attrs, scope };
slots[name] = { content: slotAst, on, attrs, attrsTranslationCtx, scope };
}
// default slot
@@ -780,10 +878,25 @@ function parseComponent(node: Element, ctx: ParsingContext): AST | null {
slots = slots || {};
// t-set-slot="default" has priority over content
if (defaultContent && !slots.default) {
slots.default = { content: defaultContent, on, attrs: null, scope: defaultSlotScope };
slots.default = {
content: defaultContent,
on,
attrs: null,
attrsTranslationCtx: null,
scope: defaultSlotScope,
};
}
}
return { type: ASTType.TComponent, name, isDynamic, dynamicProps, props, slots, on };
return {
type: ASTType.TComponent,
name,
isDynamic,
dynamicProps,
props,
propsTranslationCtx,
slots,
on,
};
}
// -----------------------------------------------------------------------------
@@ -797,12 +910,17 @@ function parseTSlot(node: Element, ctx: ParsingContext): AST | null {
const name = node.getAttribute("t-slot")!;
node.removeAttribute("t-slot");
let attrs: Attrs | null = null;
let attrsTranslationCtx: Attrs | null = null;
let on: ASTComponent["on"] = null;
for (let attributeName of node.getAttributeNames()) {
const value = node.getAttribute(attributeName)!;
if (attributeName.startsWith("t-on-")) {
on = on || {};
on[attributeName.slice(5)] = value;
} else if (attributeName.startsWith("t-translation-context-")) {
const attrName = attributeName.slice(22);
attrsTranslationCtx = attrsTranslationCtx || {};
attrsTranslationCtx[attrName] = value;
} else {
attrs = attrs || {};
attrs[attributeName] = value;
@@ -812,20 +930,65 @@ function parseTSlot(node: Element, ctx: ParsingContext): AST | null {
type: ASTType.TSlot,
name,
attrs,
attrsTranslationCtx,
on,
defaultContent: parseChildNodes(node, ctx),
};
}
// -----------------------------------------------------------------------------
// Translation
// -----------------------------------------------------------------------------
function wrapInTTranslationAST(r: AST | null) {
const ast: ASTTranslation = { type: ASTType.TTranslation, content: r };
if (r?.hasNoRepresentation) {
ast.hasNoRepresentation = true;
}
return ast;
}
function parseTTranslation(node: Element, ctx: ParsingContext): AST | null {
if (node.getAttribute("t-translation") !== "off") {
return null;
}
node.removeAttribute("t-translation");
return {
type: ASTType.TTranslation,
content: parseNode(node, ctx),
const result = parseNode(node, ctx);
if (result?.type === ASTType.Multi) {
const children = result.content.map(wrapInTTranslationAST);
return makeASTMulti(children);
}
return wrapInTTranslationAST(result);
}
// -----------------------------------------------------------------------------
// Translation Context
// -----------------------------------------------------------------------------
function wrapInTTranslationContextAST(r: AST | null, translationCtx: string) {
const ast: ASTTranslationContext = {
type: ASTType.TTranslationContext,
content: r,
translationCtx,
};
if (r?.hasNoRepresentation) {
ast.hasNoRepresentation = true;
}
return ast;
}
function parseTTranslationContext(node: Element, ctx: ParsingContext): AST | null {
const translationCtx = node.getAttribute("t-translation-context");
if (!translationCtx) {
return null;
}
node.removeAttribute("t-translation-context");
const result = parseNode(node, ctx);
if (result?.type === ASTType.Multi) {
const children = result.content.map((c) => wrapInTTranslationContextAST(c, translationCtx));
return makeASTMulti(children);
}
return wrapInTTranslationContextAST(result, translationCtx);
}
// -----------------------------------------------------------------------------
@@ -874,6 +1037,14 @@ function parseChildren(node: Element, ctx: ParsingContext): AST[] {
return children;
}
function makeASTMulti(children: AST[]) {
const ast: ASTMulti = { type: ASTType.Multi, content: children };
if (children.every((c) => c.hasNoRepresentation)) {
ast.hasNoRepresentation = true;
}
return ast;
}
/**
* Parse all the child nodes of a given node and return an ast if possible.
* In the case there are multiple children, they are wrapped in a astmulti.
@@ -886,7 +1057,7 @@ function parseChildNodes(node: Element, ctx: ParsingContext): AST | null {
case 1:
return children[0];
default:
return { type: ASTType.Multi, content: children };
return makeASTMulti(children);
}
}
@@ -943,21 +1114,23 @@ function normalizeTIf(el: Element) {
*
* @param el the element containing the tree that should be normalized
*/
function normalizeTEsc(el: Element) {
const elements = [...el.querySelectorAll("[t-esc]")].filter(
(el) => el.tagName[0] === el.tagName[0].toUpperCase() || el.hasAttribute("t-component")
);
for (const el of elements) {
if (el.childNodes.length) {
throw new OwlError("Cannot have t-esc on a component that already has content");
function normalizeTEscTOut(el: Element) {
for (const d of ["t-esc", "t-out"]) {
const elements = [...el.querySelectorAll(`[${d}]`)].filter(
(el) => el.tagName[0] === el.tagName[0].toUpperCase() || el.hasAttribute("t-component")
);
for (const el of elements) {
if (el.childNodes.length) {
throw new OwlError(`Cannot have ${d} on a component that already has content`);
}
const value = el.getAttribute(d);
el.removeAttribute(d);
const t = el.ownerDocument.createElement("t");
if (value != null) {
t.setAttribute(d, value);
}
el.appendChild(t);
}
const value = el.getAttribute("t-esc");
el.removeAttribute("t-esc");
const t = el.ownerDocument.createElement("t");
if (value != null) {
t.setAttribute("t-esc", value);
}
el.appendChild(t);
}
}
@@ -969,42 +1142,5 @@ function normalizeTEsc(el: Element) {
*/
function normalizeXML(el: Element) {
normalizeTIf(el);
normalizeTEsc(el);
}
/**
* Parses an XML string into an XML document, throwing errors on parser errors
* instead of returning an XML document containing the parseerror.
*
* @param xml the string to parse
* @returns an XML document corresponding to the content of the string
*/
function parseXML(xml: string): XMLDocument {
const parser = new DOMParser();
const doc = parser.parseFromString(xml, "text/xml");
if (doc.getElementsByTagName("parsererror").length) {
let msg = "Invalid XML in template.";
const parsererrorText = doc.getElementsByTagName("parsererror")[0].textContent;
if (parsererrorText) {
msg += "\nThe parser has produced the following error message:\n" + parsererrorText;
const re = /\d+/g;
const firstMatch = re.exec(parsererrorText);
if (firstMatch) {
const lineNumber = Number(firstMatch[0]);
const line = xml.split("\n")[lineNumber - 1];
const secondMatch = re.exec(parsererrorText);
if (line && secondMatch) {
const columnIndex = Number(secondMatch[0]) - 1;
if (line[columnIndex]) {
msg +=
`\nThe error might be located at xml line ${lineNumber} column ${columnIndex}\n` +
`${line}\n${"-".repeat(columnIndex - 1)}^`;
}
}
}
}
throw new OwlError(msg);
}
return doc;
normalizeTEscTOut(el);
}
+89
View File
@@ -0,0 +1,89 @@
// -----------------------------------------------------------------------------
// This file exports a function that allows compiling templates ahead of time.
// It is used by the "compile_owl_template" command registered in the "bin"
// section of owl's package.json
// -----------------------------------------------------------------------------
import { readdir, readFile, stat } from "fs/promises";
import path from "path";
import "./setup_jsdom";
// Owl imports must be made after setting up jsdom in the global namespace
import { compile } from "..";
// -----------------------------------------------------------------------------
// helpers
// -----------------------------------------------------------------------------
async function getXmlFiles(paths: string[]): Promise<string[]> {
return (
await Promise.all(
paths.map(async (file) => {
const stats = await stat(path.join(file));
if (stats.isDirectory()) {
return await getXmlFiles(
(await readdir(file)).map((fileName) => path.join(file, fileName))
);
}
if (file.endsWith(".xml")) {
return file;
}
return [];
})
)
).flat();
}
// adapted from https://medium.com/@mhagemann/the-ultimate-way-to-slugify-a-url-string-in-javascript-b8e4a0d849e1
const a = "·-_,:;";
const p = new RegExp(a.split("").join("|"), "g");
function slugify(str: string) {
return str
.replace(/\//g, "") // remove /
.replace(/\./g, "_") // Replace . with _
.replace(p, (c) => "_") // Replace special characters
.replace(/&/g, "_and_") // Replace & with and
.replace(/[^\w\-]+/g, ""); // Remove all non-word characters
}
// -----------------------------------------------------------------------------
// main
// -----------------------------------------------------------------------------
export async function compileTemplates(paths: string[]) {
const files = await getXmlFiles(paths);
process.stdout.write(`Processing ${files.length} files`);
let xmlStrings = await Promise.all(files.map((file) => readFile(file, "utf8")));
const templates = [];
const errors = [];
for (let i = 0; i < files.length; i++) {
const fileName = files[i];
const fileContent = xmlStrings[i];
process.stdout.write(`.`);
const parser = new DOMParser();
const doc = parser.parseFromString(fileContent, "text/xml");
for (const template of doc.querySelectorAll("[t-name]")) {
const name = template.getAttribute("t-name");
if (template.hasAttribute("owl")) {
template.removeAttribute("owl");
}
const fnName = slugify(name!);
try {
const fn = compile(template).toString().replace("anonymous", fnName);
templates.push(`"${name}": ${fn},\n`);
} catch (e) {
errors.push({ name, fileName, e });
}
}
}
process.stdout.write(`\n`);
for (let { name, fileName, e } of errors) {
console.warn(`Error while compiling '${name}' (in file ${fileName})`);
console.error(e);
}
console.log(`${templates.length} templates compiled`);
return `export const templates = {\n ${templates.join("\n")} \n}`;
}
+13
View File
@@ -0,0 +1,13 @@
import jsdom from "jsdom";
// -----------------------------------------------------------------------------
// add global DOM stuff for compiler. Needs to be in a separate file so rollup
// doesn't hoist the owl imports above this block of code.
// -----------------------------------------------------------------------------
var document = new jsdom.JSDOM("", {});
var window = document.window;
global.document = window.document;
global.window = window as unknown as Window & typeof globalThis;
global.DOMParser = window.DOMParser;
global.Element = window.Element;
global.Node = window.Node;
+2
View File
@@ -12,5 +12,7 @@ TemplateSet.prototype._compileTemplate = function _compileTemplate(
dev: this.dev,
translateFn: this.translateFn,
translatableAttributes: this.translatableAttributes,
customDirectives: this.customDirectives,
hasGlobalValues: this.hasGlobalValues,
});
};
+70 -28
View File
@@ -1,12 +1,14 @@
import { version } from "../version";
import { Component, ComponentConstructor, Props } from "./component";
import { ComponentNode } from "./component_node";
import { nodeErrorHandlers, OwlError, handleError } from "./error_handling";
import { ComponentNode, saveCurrent } from "./component_node";
import { nodeErrorHandlers, handleError } from "./error_handling";
import { OwlError } from "../common/owl_error";
import { Fiber, RootFiber, MountOptions } from "./fibers";
import { Scheduler } from "./scheduler";
import { validateProps } from "./template_helpers";
import { TemplateSet, TemplateSetConfig } from "./template_set";
import { validateTarget } from "./utils";
import { toRaw, reactive } from "./reactivity";
// reimplement dev mode stuff see last change in 0f7a8289a6fb8387c3c1af41c6664b2a8448758f
@@ -14,24 +16,20 @@ export interface Env {
[key: string]: any;
}
export interface AppConfig<P, E> extends TemplateSetConfig {
name?: string;
export interface RootConfig<P, E> {
props?: P;
env?: E;
}
export interface AppConfig<P, E> extends TemplateSetConfig, RootConfig<P, E> {
name?: string;
test?: boolean;
warnIfNoStaticProps?: boolean;
}
let hasBeenLogged = false;
export const DEV_MSG = () => {
const hash = (window as any).owl ? (window as any).owl.__info__.hash : "master";
return `Owl is running in 'dev' mode.
This is not suitable for production use.
See https://github.com/odoo/owl/blob/${hash}/doc/reference/app.md#configuration for more information.`;
};
const apps = new Set<App>();
declare global {
interface Window {
@@ -39,15 +37,19 @@ declare global {
apps: Set<App>;
Fiber: typeof Fiber;
RootFiber: typeof RootFiber;
toRaw: typeof toRaw;
reactive: typeof reactive;
};
}
}
window.__OWL_DEVTOOLS__ ||= {
apps: new Set<App>(),
Fiber: Fiber,
RootFiber: RootFiber,
};
interface Root<P extends Props, E> {
node: ComponentNode<P, E>;
mount(target: HTMLElement | ShadowRoot, options?: MountOptions): Promise<Component<P, E>>;
destroy(): void;
}
window.__OWL_DEVTOOLS__ ||= { apps, Fiber, RootFiber, toRaw, reactive };
export class App<
T extends abstract new (...args: any) => any = any,
@@ -55,6 +57,7 @@ export class App<
E = any
> extends TemplateSet {
static validateTarget = validateTarget;
static apps = apps;
static version = version;
name: string;
@@ -62,6 +65,7 @@ export class App<
props: P;
env: E;
scheduler = new Scheduler();
subRoots: Set<ComponentNode> = new Set();
root: ComponentNode<P, E> | null = null;
warnIfNoStaticProps: boolean;
@@ -69,13 +73,13 @@ export class App<
super(config);
this.name = config.name || "";
this.Root = Root;
window.__OWL_DEVTOOLS__.apps.add(this);
apps.add(this);
if (config.test) {
this.dev = true;
}
this.warnIfNoStaticProps = config.warnIfNoStaticProps || false;
if (this.dev && !config.test && !hasBeenLogged) {
console.info(DEV_MSG());
console.info(`Owl is running in 'dev' mode.`);
hasBeenLogged = true;
}
const env = config.env || {};
@@ -88,14 +92,49 @@ export class App<
target: HTMLElement | ShadowRoot,
options?: MountOptions
): Promise<Component<P, E> & InstanceType<T>> {
App.validateTarget(target);
if (this.dev) {
validateProps(this.Root, this.props, { __owl__: { app: this } });
const root = this.createRoot(this.Root, { props: this.props });
this.root = root.node;
this.subRoots.delete(root.node);
return root.mount(target, options) as any;
}
createRoot<Props extends object, SubEnv = any>(
Root: ComponentConstructor<Props, E>,
config: RootConfig<Props, SubEnv> = {}
): Root<Props, SubEnv> {
const props = config.props || ({} as Props);
// hack to make sure the sub root get the sub env if necessary. for owl 3,
// would be nice to rethink the initialization process to make sure that
// we can create a ComponentNode and give it explicitely the env, instead
// of looking it up in the app
const env = this.env;
if (config.env) {
this.env = config.env as any;
}
const node = this.makeNode(this.Root, this.props);
const prom = this.mountNode(node, target, options);
this.root = node;
return prom;
const restore = saveCurrent();
const node = this.makeNode(Root, props);
restore();
if (config.env) {
this.env = env;
}
this.subRoots.add(node);
return {
node,
mount: (target: HTMLElement | ShadowRoot, options?: MountOptions) => {
App.validateTarget(target);
if (this.dev) {
validateProps(Root, props, { __owl__: { app: this } });
}
const prom = this.mountNode(node, target, options);
return prom;
},
destroy: () => {
this.subRoots.delete(node);
node.destroy();
this.scheduler.processTasks();
},
};
}
makeNode(Component: ComponentConstructor, props: any): ComponentNode {
@@ -131,10 +170,13 @@ export class App<
destroy() {
if (this.root) {
this.scheduler.flush();
for (let subroot of this.subRoots) {
subroot.destroy();
}
this.root.destroy();
this.scheduler.processTasks();
}
window.__OWL_DEVTOOLS__.apps.delete(this);
apps.delete(this);
}
createComponent<P extends Props>(
+25 -5
View File
@@ -36,10 +36,18 @@ export function createAttrUpdater(attr: string): Setter<HTMLElement> {
export function attrsSetter(this: HTMLElement, attrs: any) {
if (isArray(attrs)) {
setAttribute.call(this, attrs[0], attrs[1]);
if (attrs[0] === "class") {
setClass.call(this, attrs[1]);
} else {
setAttribute.call(this, attrs[0], attrs[1]);
}
} else {
for (let k in attrs) {
setAttribute.call(this, k, attrs[k]);
if (k === "class") {
setClass.call(this, attrs[k]);
} else {
setAttribute.call(this, k, attrs[k]);
}
}
}
}
@@ -52,7 +60,11 @@ export function attrsUpdater(this: HTMLElement, attrs: any, oldAttrs: any) {
if (val === oldAttrs[1]) {
return;
}
setAttribute.call(this, name, val);
if (name === "class") {
updateClass.call(this, val, oldAttrs[1]);
} else {
setAttribute.call(this, name, val);
}
} else {
removeAttribute.call(this, oldAttrs[0]);
setAttribute.call(this, name, val);
@@ -60,13 +72,21 @@ export function attrsUpdater(this: HTMLElement, attrs: any, oldAttrs: any) {
} else {
for (let k in oldAttrs) {
if (!(k in attrs)) {
removeAttribute.call(this, k);
if (k === "class") {
updateClass.call(this, "", oldAttrs[k]);
} else {
removeAttribute.call(this, k);
}
}
}
for (let k in attrs) {
const val = attrs[k];
if (val !== oldAttrs[k]) {
setAttribute.call(this, k, val);
if (k === "class") {
updateClass.call(this, val, oldAttrs[k]);
} else {
setAttribute.call(this, k, val);
}
}
}
}
+3 -7
View File
@@ -1,4 +1,4 @@
import { OwlError } from "../error_handling";
import { OwlError } from "../../common/owl_error";
import { attrsSetter, attrsUpdater, createAttrUpdater, setClass, updateClass } from "./attributes";
import { config } from "./config";
import { createEventHandler } from "./events";
@@ -144,12 +144,7 @@ function buildTree(
info.push({ type: "child", idx: index });
el = document.createTextNode("");
}
const attrs = (node as Element).attributes;
const ns = attrs.getNamedItem("block-ns");
if (ns) {
attrs.removeNamedItem("block-ns");
currentNS = ns.value;
}
currentNS ||= (node as Element).namespaceURI;
if (!el) {
el = currentNS
? document.createElementNS(currentNS, tagName)
@@ -165,6 +160,7 @@ function buildTree(
const fragment = document.createElement("template").content;
fragment.appendChild(el);
}
const attrs = (node as Element).attributes;
for (let i = 0; i < attrs.length; i++) {
const attrName = attrs[i].name;
const attrValue = attrs[i].value;
+1 -1
View File
@@ -23,7 +23,7 @@ export type ComponentConstructor<P extends Props = any, E = any> = (new (
export class Component<Props = any, Env = any> {
static template: string = "";
static props?: any;
static props?: Schema;
static defaultProps?: any;
props: Props;
+27 -2
View File
@@ -1,7 +1,8 @@
import type { App, Env } from "./app";
import { BDom, VNode } from "./blockdom";
import { Component, ComponentConstructor, Props } from "./component";
import { fibersInError, OwlError } from "./error_handling";
import { fibersInError } from "./error_handling";
import { OwlError } from "../common/owl_error";
import { Fiber, makeChildFiber, makeRootFiber, MountFiber, MountOptions } from "./fibers";
import { clearReactivesForCallback, getSubscriptions, reactive, targets } from "./reactivity";
import { STATUS } from "./status";
@@ -9,6 +10,13 @@ import { batched, Callback } from "./utils";
let currentNode: ComponentNode | null = null;
export function saveCurrent() {
let n = currentNode;
return () => {
currentNode = n;
};
}
export function getCurrent(): ComponentNode {
if (!currentNode) {
throw new OwlError("No active component (a hook function should only be called in 'setup')");
@@ -145,6 +153,9 @@ export class ComponentNode<P extends Props = any, E = any> implements VNode<Comp
}
async render(deep: boolean) {
if (this.status >= STATUS.CANCELLED) {
return;
}
let current = this.fiber;
if (current && (current.root!.locked || (current as any).bdom === true)) {
await Promise.resolve();
@@ -171,7 +182,7 @@ export class ComponentNode<P extends Props = any, E = any> implements VNode<Comp
this.app.scheduler.addFiber(fiber);
await Promise.resolve();
if (this.status === STATUS.DESTROYED) {
if (this.status >= STATUS.CANCELLED) {
return;
}
// We only want to actually render the component if the following two
@@ -190,6 +201,20 @@ export class ComponentNode<P extends Props = any, E = any> implements VNode<Comp
}
}
cancel() {
this._cancel();
delete this.parent!.children[this.parentKey!];
this.app.scheduler.scheduleDestroy(this);
}
_cancel() {
this.status = STATUS.CANCELLED;
const children = this.children;
for (let childKey in children) {
children[childKey]._cancel();
}
}
destroy() {
let shouldRemove = this.status === STATUS.MOUNTED;
this._destroy();
+13 -14
View File
@@ -1,11 +1,7 @@
import { OwlError } from "../common/owl_error";
import type { ComponentNode } from "./component_node";
import type { Fiber } from "./fibers";
// Custom error class that wraps error that happen in the owl lifecycle
export class OwlError extends Error {
cause?: any;
}
// Maps fibers to thrown errors
export const fibersInError: WeakMap<Fiber, any> = new WeakMap();
export const nodeErrorHandlers: WeakMap<ComponentNode, ((error: any) => void)[]> = new WeakMap();
@@ -51,17 +47,20 @@ export function handleError(params: ErrorParams) {
);
}
const node = "node" in params ? params.node : params.fiber.node;
const fiber = "fiber" in params ? params.fiber : node.fiber!;
const fiber = "fiber" in params ? params.fiber : node.fiber;
// resets the fibers on components if possible. This is important so that
// new renderings can be properly included in the initial one, if any.
let current: Fiber | null = fiber;
do {
current.node.fiber = current;
current = current.parent;
} while (current);
if (fiber) {
// resets the fibers on components if possible. This is important so that
// new renderings can be properly included in the initial one, if any.
let current: Fiber | null = fiber;
do {
current.node.fiber = current;
fibersInError.set(current, error);
current = current.parent;
} while (current);
fibersInError.set(fiber.root!, error);
fibersInError.set(fiber.root!, error);
}
const handled = _handleError(node, error);
if (!handled) {
+1 -1
View File
@@ -1,6 +1,6 @@
import { filterOutModifiersFromData } from "./blockdom/config";
import { STATUS } from "./status";
import { OwlError } from "./error_handling";
import { OwlError } from "../common/owl_error";
export const mainEventHandler = (data: any, ev: Event, currentTarget?: EventTarget | null) => {
const { data: _data, modifiers } = filterOutModifiersFromData(data);
+20 -4
View File
@@ -1,6 +1,7 @@
import { BDom, mount } from "./blockdom";
import type { ComponentNode } from "./component_node";
import { fibersInError, OwlError } from "./error_handling";
import { fibersInError } from "./error_handling";
import { OwlError } from "../common/owl_error";
import { STATUS } from "./status";
export function makeChildFiber(node: ComponentNode, parent: Fiber): Fiber {
@@ -29,6 +30,13 @@ export function makeRootFiber(node: ComponentNode): Fiber {
fibersInError.delete(current);
fibersInError.delete(root);
current.appliedToDom = false;
if (current instanceof RootFiber) {
// it is possible that this fiber is a fiber that crashed while being
// mounted, so the mounted list is possibly corrupted. We restore it to
// its normal initial state (which is empty list or a list with a mount
// fiber.
current.mounted = current instanceof MountFiber ? [current] : [];
}
}
return current;
}
@@ -55,8 +63,7 @@ function cancelFibers(fibers: Fiber[]): number {
let node = fiber.node;
fiber.render = throwOnRender;
if (node.status === STATUS.NEW) {
node.destroy();
delete node.parent!.children[node.parentKey!];
node.cancel();
}
node.fiber = null;
if (fiber.bdom) {
@@ -152,6 +159,7 @@ export class RootFiber extends Fiber {
const node = this.node;
this.locked = true;
let current: Fiber | undefined = undefined;
let mountedFibers = this.mounted;
try {
// Step 1: calling all willPatch lifecycle hooks
for (current of this.willPatch) {
@@ -173,7 +181,6 @@ export class RootFiber extends Fiber {
this.locked = false;
// Step 4: calling all mounted lifecycle hooks
let mountedFibers = this.mounted;
while ((current = mountedFibers.pop())) {
current = current;
if (current.appliedToDom) {
@@ -194,6 +201,15 @@ export class RootFiber extends Fiber {
}
}
} catch (e) {
// if mountedFibers is not empty, this means that a crash occured while
// calling the mounted hooks of some component. So, there may still be
// some component that have been mounted, but for which the mounted hooks
// have not been called. Here, we remove the willUnmount hooks for these
// specific component to prevent a worse situation (willUnmount being
// called even though mounted has not been called)
for (let fiber of mountedFibers) {
fiber.node.willUnmount = [];
}
this.locked = false;
node.app.handleError({ fiber: current || this, error: e });
}
+13 -6
View File
@@ -59,28 +59,35 @@ export function useChildSubEnv(envExtension: Env) {
// useEffect
// -----------------------------------------------------------------------------
type EffectDeps<T extends unknown[]> = T | (T extends [...infer H, never] ? EffectDeps<H> : never);
/**
* @param {...any} dependencies the dependencies computed by computeDependencies
* @template T
* @param {...T} dependencies the dependencies computed by computeDependencies
* @returns {void|(()=>void)} a cleanup function that reverses the side
* effects of the effect callback.
*/
type Effect = (...dependencies: any[]) => void | (() => void);
type Effect<T extends unknown[]> = (...dependencies: EffectDeps<T>) => void | (() => void);
/**
* This hook will run a callback when a component is mounted and patched, and
* will run a cleanup function before patching and before unmounting the
* the component.
*
* @param {Effect} effect the effect to run on component mount and/or patch
* @param {()=>any[]} [computeDependencies=()=>[NaN]] a callback to compute
* @template T
* @param {Effect<T>} effect the effect to run on component mount and/or patch
* @param {()=>[...T]} [computeDependencies=()=>[NaN]] a callback to compute
* dependencies that will decide if the effect needs to be cleaned up and
* run again. If the dependencies did not change, the effect will not run
* again. The default value returns an array containing only NaN because
* NaN !== NaN, which will cause the effect to rerun on every patch.
*/
export function useEffect(effect: Effect, computeDependencies: () => any[] = () => [NaN]) {
export function useEffect<T extends unknown[]>(
effect: Effect<T>,
computeDependencies: () => [...T] = () => [NaN] as never
) {
let cleanup: (() => void) | void;
let dependencies: any[];
let dependencies: T;
onMounted(() => {
dependencies = computeDependencies();
cleanup = effect(...dependencies);
+2 -2
View File
@@ -41,7 +41,7 @@ export { useComponent, useState } from "./component_node";
export { status } from "./status";
export { reactive, markRaw, toRaw } from "./reactivity";
export { useEffect, useEnv, useExternalListener, useRef, useChildSubEnv, useSubEnv } from "./hooks";
export { EventBus, whenReady, loadFile, markup } from "./utils";
export { batched, EventBus, htmlEscape, whenReady, loadFile, markup } from "./utils";
export {
onWillStart,
onMounted,
@@ -55,7 +55,7 @@ export {
onError,
} from "./lifecycle_hooks";
export { validate, validateType } from "./validation";
export { OwlError } from "./error_handling";
export { OwlError } from "../common/owl_error";
export const __info__ = {
version: App.version,
+33 -24
View File
@@ -1,43 +1,52 @@
import { getCurrent } from "./component_node";
import { nodeErrorHandlers, OwlError } from "./error_handling";
import { nodeErrorHandlers } from "./error_handling";
import { OwlError } from "../common/owl_error";
const TIMEOUT = Symbol("timeout");
const HOOK_TIMEOUT: { [key: string]: number } = {
onWillStart: 3000,
onWillUpdateProps: 3000,
};
function wrapError(fn: (...args: any[]) => any, hookName: string) {
const error = new OwlError(`The following error occurred in ${hookName}: `) as Error & {
const error = new OwlError() as Error & {
cause: any;
};
const timeoutError = new OwlError(`${hookName}'s promise hasn't resolved after 3 seconds`);
const timeoutError = new OwlError();
const node = getCurrent();
return (...args: any[]) => {
const onError = (cause: any) => {
error.cause = cause;
if (cause instanceof Error) {
error.message += `"${cause.message}"`;
} else {
error.message = `Something that is not an Error was thrown in ${hookName} (see this Error's "cause" property)`;
}
error.message =
cause instanceof Error
? `The following error occurred in ${hookName}: "${cause.message}"`
: `Something that is not an Error was thrown in ${hookName} (see this Error's "cause" property)`;
throw error;
};
let result;
try {
const result = fn(...args);
if (result instanceof Promise) {
if (hookName === "onWillStart" || hookName === "onWillUpdateProps") {
const fiber = node.fiber;
Promise.race([
result.catch(() => {}),
new Promise((resolve) => setTimeout(() => resolve(TIMEOUT), 3000)),
]).then((res) => {
if (res === TIMEOUT && node.fiber === fiber) {
console.warn(timeoutError);
}
});
}
return result.catch(onError);
}
return result;
result = fn(...args);
} catch (cause) {
onError(cause);
}
if (!(result instanceof Promise)) {
return result;
}
const timeout = HOOK_TIMEOUT[hookName];
if (timeout) {
const fiber = node.fiber;
Promise.race([
result.catch(() => {}),
new Promise((resolve) => setTimeout(() => resolve(TIMEOUT), timeout)),
]).then((res) => {
if (res === TIMEOUT && node.fiber === fiber && node.status <= 2) {
timeoutError.message = `${hookName}'s promise hasn't resolved after ${
timeout / 1000
} seconds`;
console.log(timeoutError);
}
});
}
return result.catch(onError);
};
}
+2 -2
View File
@@ -1,7 +1,7 @@
import { onMounted, onWillUnmount } from "./lifecycle_hooks";
import { BDom, text, VNode } from "./blockdom";
import { Component } from "./component";
import { OwlError } from "./error_handling";
import { OwlError } from "../common/owl_error";
const VText: any = text("").constructor;
@@ -65,7 +65,7 @@ export class Portal extends Component {
type: String,
},
slots: true,
};
} as const;
setup() {
const node: any = this.__owl__;
+8 -7
View File
@@ -1,5 +1,5 @@
import type { Callback } from "./utils";
import { OwlError } from "./error_handling";
import { OwlError } from "../common/owl_error";
// Special key to subscribe to, to be notified of key creation/deletion
const KEYCHANGES = Symbol("Key changes");
@@ -20,8 +20,9 @@ type CollectionRawType = "Set" | "Map" | "WeakMap";
const objectToString = Object.prototype.toString;
const objectHasOwnProperty = Object.prototype.hasOwnProperty;
const SUPPORTED_RAW_TYPES = new Set(["Object", "Array", "Set", "Map", "WeakMap"]);
const COLLECTION_RAWTYPES = new Set(["Set", "Map", "WeakMap"]);
// Use arrays because Array.includes is faster than Set.has for small arrays
const SUPPORTED_RAW_TYPES = ["Object", "Array", "Set", "Map", "WeakMap"];
const COLLECTION_RAW_TYPES = ["Set", "Map", "WeakMap"];
/**
* extract "RawType" from strings like "[object RawType]" => this lets us ignore
@@ -45,7 +46,7 @@ function canBeMadeReactive(value: any): boolean {
if (typeof value !== "object") {
return false;
}
return SUPPORTED_RAW_TYPES.has(rawType(value));
return SUPPORTED_RAW_TYPES.includes(rawType(value));
}
/**
* Creates a reactive from the given object/callback if possible and returns it,
@@ -220,7 +221,7 @@ export function reactive<T extends Target>(target: T, callback: Callback = NO_CA
const reactivesForTarget = reactiveCache.get(target)!;
if (!reactivesForTarget.has(callback)) {
const targetRawType = rawType(target);
const handler = COLLECTION_RAWTYPES.has(targetRawType)
const handler = COLLECTION_RAW_TYPES.includes(targetRawType)
? collectionsProxyHandler(target as Collection, callback, targetRawType as CollectionRawType)
: basicProxyHandler<T>(callback);
const proxy = new Proxy(target, handler as ProxyHandler<T>) as Reactive<T>;
@@ -249,7 +250,7 @@ function basicProxyHandler<T extends Target>(callback: Callback): ProxyHandler<T
set(target, key, value, receiver) {
const hadKey = objectHasOwnProperty.call(target, key);
const originalValue = Reflect.get(target, key, receiver);
const ret = Reflect.set(target, key, value, receiver);
const ret = Reflect.set(target, key, toRaw(value), receiver);
if (!hadKey && objectHasOwnProperty.call(target, key)) {
notifyReactives(target, KEYCHANGES);
}
@@ -368,7 +369,7 @@ function delegateAndNotify(
if (hadKey !== hasKey) {
notifyReactives(target, KEYCHANGES);
}
if (originalValue !== value) {
if (originalValue !== target[getterName](key)) {
notifyReactives(target, key);
}
return ret;
+40 -10
View File
@@ -1,3 +1,4 @@
import type { ComponentNode } from "./component_node";
import { fibersInError } from "./error_handling";
import { Fiber, RootFiber } from "./fibers";
import { STATUS } from "./status";
@@ -14,6 +15,8 @@ export class Scheduler {
requestAnimationFrame: Window["requestAnimationFrame"];
frame: number = 0;
delayedRenders: Fiber[] = [];
cancelledNodes: Set<ComponentNode> = new Set();
processing = false;
constructor() {
this.requestAnimationFrame = Scheduler.requestAnimationFrame;
@@ -23,6 +26,13 @@ export class Scheduler {
this.tasks.add(fiber.root!);
}
scheduleDestroy(node: ComponentNode) {
this.cancelledNodes.add(node);
if (this.frame === 0) {
this.frame = this.requestAnimationFrame(() => this.processTasks());
}
}
/**
* Process all current tasks. This only applies to the fibers that are ready.
* Other tasks are left unchanged.
@@ -39,18 +49,31 @@ export class Scheduler {
}
if (this.frame === 0) {
this.frame = this.requestAnimationFrame(() => {
this.frame = 0;
this.tasks.forEach((fiber) => this.processFiber(fiber));
for (let task of this.tasks) {
if (task.node.status === STATUS.DESTROYED) {
this.tasks.delete(task);
}
}
});
this.frame = this.requestAnimationFrame(() => this.processTasks());
}
}
processTasks() {
if (this.processing) {
return;
}
this.processing = true;
this.frame = 0;
for (let node of this.cancelledNodes) {
node._destroy();
}
this.cancelledNodes.clear();
for (let task of this.tasks) {
this.processFiber(task);
}
for (let task of this.tasks) {
if (task.node.status === STATUS.DESTROYED) {
this.tasks.delete(task);
}
}
this.processing = false;
}
processFiber(fiber: RootFiber) {
if (fiber.root !== fiber) {
this.tasks.delete(fiber);
@@ -70,7 +93,14 @@ export class Scheduler {
if (!hasError) {
fiber.complete();
}
this.tasks.delete(fiber);
// at this point, the fiber should have been applied to the DOM, so we can
// remove it from the task list. If it is not the case, it means that there
// was an error and an error handler triggered a new rendering that recycled
// the fiber, so in that case, we actually want to keep the fiber around,
// otherwise it will just be ignored.
if (fiber.appliedToDom) {
this.tasks.delete(fiber);
}
}
}
}
+6 -1
View File
@@ -7,15 +7,20 @@ import type { Component } from "./component";
export const enum STATUS {
NEW,
MOUNTED, // is ready, and in DOM. It has a valid el
// component has been created, but has been replaced by a newer component before being mounted
// it is cancelled until the next animation frame where it will be destroyed
CANCELLED,
DESTROYED,
}
type STATUS_DESCR = "new" | "mounted" | "destroyed";
type STATUS_DESCR = "new" | "mounted" | "cancelled" | "destroyed";
export function status(component: Component): STATUS_DESCR {
switch (component.__owl__.status) {
case STATUS.NEW:
return "new";
case STATUS.CANCELLED:
return "cancelled";
case STATUS.MOUNTED:
return "mounted";
case STATUS.DESTROYED:
+14 -8
View File
@@ -4,7 +4,7 @@ import { html } from "./blockdom/index";
import { isOptional, validateSchema } from "./validation";
import type { ComponentConstructor } from "./component";
import { markRaw } from "./reactivity";
import { OwlError } from "./error_handling";
import { OwlError } from "../common/owl_error";
import type { ComponentNode } from "./component_node";
const ObjectCreate = Object.create;
@@ -60,18 +60,24 @@ function withKey(elem: any, k: string) {
return elem;
}
function prepareList(collection: any): [any[], any[], number, any[]] {
let keys: any[];
let values: any[];
function prepareList(collection: unknown): [unknown[], unknown[], number, undefined[]] {
let keys: unknown[];
let values: unknown[];
if (Array.isArray(collection)) {
keys = collection;
values = collection;
} else if (collection) {
values = Object.keys(collection);
keys = Object.values(collection);
} else if (collection instanceof Map) {
keys = [...collection.keys()];
values = [...collection.values()];
} else if (Symbol.iterator in Object(collection)) {
keys = [...(<Iterable<unknown>>collection)];
values = keys;
} else if (collection && typeof collection === "object") {
values = Object.values(collection);
keys = Object.keys(collection);
} else {
throw new OwlError("Invalid loop expression");
throw new OwlError(`Invalid loop expression: "${collection}" is not iterable`);
}
const n = values.length;
return [keys, values, n, new Array(n)];
+30 -37
View File
@@ -3,45 +3,20 @@ import { comment, createBlock, html, list, multi, text, toggler } from "./blockd
import { getCurrent } from "./component_node";
import { Portal, portalTemplate } from "./portal";
import { helpers } from "./template_helpers";
import { OwlError } from "./error_handling";
import { OwlError } from "../common/owl_error";
import { parseXML } from "../common/utils";
import type { customDirectives } from "../common/types";
const bdom = { text, createBlock, list, multi, html, toggler, comment };
function parseXML(xml: string): Document {
const parser = new DOMParser();
const doc = parser.parseFromString(xml, "text/xml");
if (doc.getElementsByTagName("parsererror").length) {
let msg = "Invalid XML in template.";
const parsererrorText = doc.getElementsByTagName("parsererror")[0].textContent;
if (parsererrorText) {
msg += "\nThe parser has produced the following error message:\n" + parsererrorText;
const re = /\d+/g;
const firstMatch = re.exec(parsererrorText);
if (firstMatch) {
const lineNumber = Number(firstMatch[0]);
const line = xml.split("\n")[lineNumber - 1];
const secondMatch = re.exec(parsererrorText);
if (line && secondMatch) {
const columnIndex = Number(secondMatch[0]) - 1;
if (line[columnIndex]) {
msg +=
`\nThe error might be located at xml line ${lineNumber} column ${columnIndex}\n` +
`${line}\n${"-".repeat(columnIndex - 1)}^`;
}
}
}
}
throw new OwlError(msg);
}
return doc;
}
export interface TemplateSetConfig {
dev?: boolean;
translatableAttributes?: string[];
translateFn?: (s: string) => string;
templates?: string | Document;
translateFn?: (s: string, translationCtx: string) => string;
templates?: string | Document | Record<string, string>;
getTemplate?: (s: string) => Element | Function | string | void;
customDirectives?: customDirectives;
globalValues?: object;
}
export class TemplateSet {
@@ -51,21 +26,39 @@ export class TemplateSet {
dev: boolean;
rawTemplates: typeof globalTemplates = Object.create(globalTemplates);
templates: { [name: string]: Template } = {};
translateFn?: (s: string) => string;
getRawTemplate?: (s: string) => Element | Function | string | void;
translateFn?: (s: string, translationCtx: string) => string;
translatableAttributes?: string[];
Portal = Portal;
customDirectives: customDirectives;
runtimeUtils: object;
hasGlobalValues: boolean;
constructor(config: TemplateSetConfig = {}) {
this.dev = config.dev || false;
this.translateFn = config.translateFn;
this.translatableAttributes = config.translatableAttributes;
if (config.templates) {
this.addTemplates(config.templates);
if (config.templates instanceof Document || typeof config.templates === "string") {
this.addTemplates(config.templates);
} else {
for (const name in config.templates) {
this.addTemplate(name, config.templates[name]);
}
}
}
this.getRawTemplate = config.getTemplate;
this.customDirectives = config.customDirectives || {};
this.runtimeUtils = { ...helpers, __globals__: config.globalValues || {} };
this.hasGlobalValues = Boolean(config.globalValues && Object.keys(config.globalValues).length);
}
addTemplate(name: string, template: string | Element) {
if (name in this.rawTemplates) {
// this check can be expensive, just silently ignore double definitions outside dev mode
if (!this.dev) {
return;
}
const rawTemplate = this.rawTemplates[name];
const currentAsString =
typeof rawTemplate === "string"
@@ -96,7 +89,7 @@ export class TemplateSet {
getTemplate(name: string): Template {
if (!(name in this.templates)) {
const rawTemplate = this.rawTemplates[name];
const rawTemplate = this.getRawTemplate?.(name) || this.rawTemplates[name];
if (rawTemplate === undefined) {
let extraInfo = "";
try {
@@ -113,7 +106,7 @@ export class TemplateSet {
this.templates[name] = function (context, parent) {
return templates[name].call(this, context, parent);
};
const template = templateFn(this, bdom, helpers);
const template = templateFn(this, bdom, this.runtimeUtils);
this.templates[name] = template;
}
return this.templates[name];
+82 -19
View File
@@ -1,4 +1,4 @@
import { OwlError } from "./error_handling";
import { OwlError } from "../common/owl_error";
export type Callback = () => void;
/**
@@ -9,20 +9,13 @@ export type Callback = () => void;
* @returns a batched version of the original callback
*/
export function batched(callback: Callback): Callback {
let called = false;
return async () => {
// This await blocks all calls to the callback here, then releases them sequentially
// in the next microtick. This line decides the granularity of the batch.
await Promise.resolve();
if (!called) {
called = true;
// wait for all calls in this microtick to fall through before resetting "called"
// so that only the first call to the batched function calls the original callback.
// Schedule this before calling the callback so that calls to the batched function
// within the callback will proceed only after resetting called to false, and have
// a chance to execute the callback again
Promise.resolve().then(() => (called = false));
callback();
let scheduled = false;
return async (...args) => {
if (!scheduled) {
scheduled = true;
await Promise.resolve();
scheduled = false;
callback(...args);
}
};
}
@@ -42,13 +35,43 @@ export function inOwnerDocument(el?: HTMLElement) {
return rootNode instanceof ShadowRoot && el.ownerDocument.contains(rootNode.host);
}
/**
* Determine whether the given element is contained in a specific root documnet:
* either directly or with a shadow root in between or in an iframe.
*/
function isAttachedToDocument(
element: HTMLElement | ShadowRoot,
documentElement: Document
): boolean {
let current: Node = element;
const shadowRoot = documentElement.defaultView!.ShadowRoot;
while (current) {
if (current === documentElement) {
return true;
}
if (current.parentNode) {
current = current.parentNode;
} else if (current instanceof shadowRoot && current.host) {
current = current.host;
} else {
return false;
}
}
return false;
}
export function validateTarget(target: HTMLElement | ShadowRoot) {
// Get the document and HTMLElement corresponding to the target to allow mounting in iframes
const document = target && target.ownerDocument;
if (document) {
const HTMLElement = document.defaultView!.HTMLElement;
if (!document.defaultView) {
throw new OwlError(
"Cannot mount a component: the target document is not attached to a window (defaultView is missing)"
);
}
const HTMLElement = document.defaultView.HTMLElement;
if (target instanceof HTMLElement || target instanceof ShadowRoot) {
if (!document.body.contains(target instanceof HTMLElement ? target : target.host)) {
if (!isAttachedToDocument(target, document)) {
throw new OwlError("Cannot mount a component on a detached dom node");
}
return;
@@ -88,10 +111,50 @@ export async function loadFile(url: string): Promise<string> {
*/
export class Markup extends String {}
export function htmlEscape(str: any): Markup {
if (str instanceof Markup) {
return str;
}
if (str === undefined) {
return markup("");
}
if (typeof str === "number") {
return markup(String(str));
}
[
["&", "&amp;"],
["<", "&lt;"],
[">", "&gt;"],
["'", "&#x27;"],
['"', "&quot;"],
["`", "&#x60;"],
].forEach((pairs) => {
str = String(str).replace(new RegExp(pairs[0], "g"), pairs[1]);
});
return markup(str);
}
/*
* Marks a value as safe, that is, a value that can be injected as HTML directly.
* It should be used to wrap the value passed to a t-out directive to allow a raw rendering.
*
* If called as a tag function, the interpolated strings are escaped.
*/
export function markup(value: any) {
return new Markup(value);
export function markup(strings: TemplateStringsArray, ...placeholders: unknown[]): Markup;
export function markup(value: string): Markup;
export function markup(
valueOrStrings: string | TemplateStringsArray,
...placeholders: unknown[]
): Markup {
if (!Array.isArray(valueOrStrings)) {
return new Markup(valueOrStrings);
}
const strings = valueOrStrings;
let acc = "";
let i = 0;
for (; i < placeholders.length; ++i) {
acc += strings[i] + htmlEscape(placeholders[i]);
}
acc += strings[i];
return new Markup(acc);
}
+2 -10
View File
@@ -1,15 +1,7 @@
import { OwlError } from "./error_handling";
import { OwlError } from "../common/owl_error";
import { toRaw } from "./reactivity";
type BaseType =
| typeof String
| typeof Boolean
| typeof Number
| typeof Date
| typeof Object
| typeof Array
| true
| "*";
type BaseType = { new (...args: any[]): any } | true | "*";
interface TypeInfo {
type?: TypeDescription;
+1 -1
View File
@@ -1,2 +1,2 @@
// do not modify manually. This file is generated by the release script.
export const version = "2.1.3";
export const version = "2.8.1";
+1 -1
View File
@@ -353,7 +353,7 @@ exports[`Reactivity: useState useless atoms should be deleted 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(Object.keys(ctx['state']));;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`id\`] = v_block2[i1];
ctx[\`id\`] = k_block2[i1];
const key1 = ctx['id'];
c_block2[i1] = withKey(comp1({id: ctx['id']}, key + \`__1__\${key1}\`, node, this, null), key1);
}
+83
View File
@@ -15,6 +15,76 @@ exports[`app App supports env with getters/setters 1`] = `
}"
`;
exports[`app app: clear scheduler tasks and destroy cancelled nodes immediately on destroy 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
const comp1 = app.createComponent(\`B\`, true, false, false, []);
return function template(ctx, node, key = \\"\\") {
let b2, b3;
b2 = text(\`A\`);
if (ctx['state'].value) {
b3 = comp1({}, key + \`__1\`, node, this, null);
}
return multi([b2, b3]);
}
}"
`;
exports[`app app: clear scheduler tasks and destroy cancelled nodes immediately on destroy 3`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(\`B\`);
}
}"
`;
exports[`app can add functions to the bdom 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { __globals__ } = helpers;
let block1 = createBlock(\`<div class=\\"my-div\\" block-handler-0=\\"click\\"/>\`);
return function template(ctx, node, key = \\"\\") {
let hdlr1 = [()=>__globals__.plop('click'), ctx];
return block1([hdlr1]);
}
}"
`;
exports[`app can call processTask twice in a row without crashing 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
const comp1 = app.createComponent(\`Child\`, true, false, false, []);
return function template(ctx, node, key = \\"\\") {
const b2 = text(\`parent\`);
const b3 = comp1({}, key + \`__1\`, node, this, null);
return multi([b2, b3]);
}
}"
`;
exports[`app can call processTask twice in a row without crashing 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div/>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
exports[`app can configure an app with props 1`] = `
"function anonymous(app, bdom, helpers
) {
@@ -29,6 +99,19 @@ exports[`app can configure an app with props 1`] = `
}"
`;
exports[`app can load templates from an object name-string 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div class=\\"hello\\">hello</div>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
exports[`app can mount app in an iframe 1`] = `
"function anonymous(app, bdom, helpers
) {
@@ -0,0 +1,210 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`destroy a subroot while another component is mounted in main app 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
const comp1 = app.createComponent(\`ChildB\`, true, false, false, []);
const comp2 = app.createComponent(\`ChildA\`, true, false, false, []);
return function template(ctx, node, key = \\"\\") {
let b2, b3;
if (ctx['state'].flag) {
b2 = comp1({}, key + \`__1\`, node, this, null);
} else {
b3 = comp2({}, key + \`__2\`, node, this, null);
}
return multi([b2, b3]);
}
}"
`;
exports[`destroy a subroot while another component is mounted in main app 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block3 = createBlock(\`<div block-ref=\\"0\\"/>\`);
return function template(ctx, node, key = \\"\\") {
const b2 = text(\`a\`);
let ref1 = (el) => this.__owl__.setRef((\`elem\`), el);
const b3 = block3([ref1]);
return multi([b2, b3]);
}
}"
`;
exports[`destroy a subroot while another component is mounted in main app 3`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(\`c\`);
}
}"
`;
exports[`destroy a subroot while another component is mounted in main app 4`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(\`b\`);
}
}"
`;
exports[`subroot by default, env is the same in sub root 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div>main app</div>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
exports[`subroot by default, env is the same in sub root 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div>sub root</div>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
exports[`subroot can create a root in a setup function, then use a hook 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(\`a\`);
}
}"
`;
exports[`subroot can create a root in a setup function, then use a hook 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(\`c\`);
}
}"
`;
exports[`subroot can mount subroot 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div>main app</div>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
exports[`subroot can mount subroot 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div>sub root</div>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
exports[`subroot can mount subroot inside own dom 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div>main app</div>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
exports[`subroot can mount subroot inside own dom 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div>sub root</div>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
exports[`subroot env can be specified for sub roots 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div>main app</div>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
exports[`subroot env can be specified for sub roots 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div>sub root</div>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
exports[`subroot subcomponents can be destroyed, and it properly cleanup the subroots 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div>main app</div>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
exports[`subroot subcomponents can be destroyed, and it properly cleanup the subroots 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div>sub root</div>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
+127 -2
View File
@@ -1,6 +1,15 @@
import { App, Component, mount, xml } from "../../src";
import { App, Component, mount, onWillPatch, onWillStart, useState, xml } from "../../src";
import { status } from "../../src/runtime/status";
import { makeTestFixture, snapshotEverything, nextTick, elem } from "../helpers";
import {
makeTestFixture,
snapshotEverything,
nextTick,
elem,
useLogLifecycle,
makeDeferred,
nextMicroTick,
steps,
} from "../helpers";
let fixture: HTMLElement;
@@ -94,4 +103,120 @@ describe("app", () => {
expect(iframeDoc.contains(div)).toBe(false);
expect(status(comp)).toBe("destroyed");
});
test("app: clear scheduler tasks and destroy cancelled nodes immediately on destroy", async () => {
let def = makeDeferred();
class B extends Component {
static template = xml`B`;
setup() {
useLogLifecycle();
onWillStart(() => def);
}
}
class A extends Component {
static template = xml`A<t t-if="state.value"><B/></t>`;
static components = { B };
state = useState({ value: false });
setup() {
useLogLifecycle();
}
}
const app = new App(A);
const comp = await app.mount(fixture);
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"A:setup",
"A:willStart",
"A:willRender",
"A:rendered",
"A:mounted",
]
`);
comp.state.value = true;
await nextTick();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"A:willRender",
"B:setup",
"B:willStart",
"A:rendered",
]
`);
// rerender to force the instantiation of a new B component (and cancelling the first)
comp.render();
await nextMicroTick();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"A:willRender",
"B:setup",
"B:willStart",
"A:rendered",
]
`);
app.destroy();
expect(steps.splice(0)).toMatchInlineSnapshot(`
Array [
"A:willUnmount",
"B:willDestroy",
"A:willDestroy",
"B:willDestroy",
]
`);
});
test("can load templates from an object name-string", async () => {
const templates = {
hello: `<div class="hello">hello</div>`,
world: `<div>world</div>`,
};
class SomeComponent extends Component {
static template = "hello";
}
const app = new App(SomeComponent, { templates });
await app.mount(fixture);
expect(fixture.querySelector(".hello")).toBeDefined();
// Only the "hello" template is used, so the "world" template is not yet loaded
expect(Object.keys(app.templates)).toEqual(["hello"]);
expect(Object.keys(app.rawTemplates)).toEqual(["hello", "world"]);
});
test("can call processTask twice in a row without crashing", async () => {
class Child extends Component {
static template = xml`<div/>`;
setup() {
onWillPatch(() => app.scheduler.processTasks());
}
}
class SomeComponent extends Component {
static template = xml`parent<Child/>`;
static components = { Child };
}
const app = new App(SomeComponent);
await app.mount(fixture);
expect(fixture.innerHTML).toBe("parent<div></div>");
});
test("can add functions to the bdom", async () => {
const steps: string[] = [];
class SomeComponent extends Component {
static template = xml`<div t-on-click="() => __globals__.plop('click')" class="my-div"/>`;
}
const app = new App(SomeComponent, {
globalValues: {
plop: (string: any) => {
steps.push(string);
},
},
});
await app.mount(fixture);
expect(fixture.innerHTML).toBe(`<div class="my-div"></div>`);
fixture.querySelector("div")!.click();
expect(steps).toEqual(["click"]);
});
});
+176
View File
@@ -0,0 +1,176 @@
import { App, Component, onMounted, onWillDestroy, useRef, useState, xml } from "../../src";
import { status } from "../../src/runtime/status";
import { makeTestFixture, nextTick, snapshotEverything } from "../helpers";
let fixture: HTMLElement;
snapshotEverything();
beforeEach(() => {
fixture = makeTestFixture();
});
class SomeComponent extends Component {
static template = xml`<div>main app</div>`;
}
class SubComponent extends Component {
static template = xml`<div>sub root</div>`;
}
describe("subroot", () => {
test("can mount subroot", async () => {
const app = new App(SomeComponent);
const comp = await app.mount(fixture);
expect(fixture.innerHTML).toBe("<div>main app</div>");
const subRoot = app.createRoot(SubComponent);
const subcomp = await subRoot.mount(fixture);
expect(fixture.innerHTML).toBe("<div>main app</div><div>sub root</div>");
app.destroy();
expect(fixture.innerHTML).toBe("");
expect(status(comp)).toBe("destroyed");
expect(status(subcomp)).toBe("destroyed");
});
test("can mount subroot inside own dom", async () => {
const app = new App(SomeComponent);
const comp = await app.mount(fixture);
expect(fixture.innerHTML).toBe("<div>main app</div>");
const subRoot = app.createRoot(SubComponent);
const subcomp = await subRoot.mount(fixture.querySelector("div")!);
expect(fixture.innerHTML).toBe("<div>main app<div>sub root</div></div>");
app.destroy();
expect(fixture.innerHTML).toBe("");
expect(status(comp)).toBe("destroyed");
expect(status(subcomp)).toBe("destroyed");
});
test("by default, env is the same in sub root", async () => {
let env, subenv;
class SC extends SomeComponent {
setup() {
env = this.env;
}
}
class Sub extends SubComponent {
setup() {
subenv = this.env;
}
}
const app = new App(SC);
await app.mount(fixture);
const subRoot = app.createRoot(Sub);
await subRoot.mount(fixture);
expect(env).toBeDefined();
expect(subenv).toBeDefined();
expect(env).toBe(subenv);
});
test("env can be specified for sub roots", async () => {
const env1 = { env1: true };
const env2 = {};
let someComponentEnv: any, subComponentEnv: any;
class SC extends SomeComponent {
setup() {
someComponentEnv = this.env;
}
}
class Sub extends SubComponent {
setup() {
subComponentEnv = this.env;
}
}
const app = new App(SC, { env: env1 });
await app.mount(fixture);
const subRoot = app.createRoot(Sub, { env: env2 });
await subRoot.mount(fixture);
// because env is different in app => it is given a sub object, frozen and all
// not sure it is a good idea, but it's the way owl 2 works. maybe we should
// avoid doing anything with the main env and let user code do it if they
// want. in that case, we can change the test here to assert that they are equal
expect(someComponentEnv).not.toBe(env1);
expect(someComponentEnv!.env1).toBe(true);
expect(subComponentEnv).toBe(env2);
});
test("subcomponents can be destroyed, and it properly cleanup the subroots", async () => {
const app = new App(SomeComponent);
const comp = await app.mount(fixture);
expect(fixture.innerHTML).toBe("<div>main app</div>");
const root = app.createRoot(SubComponent);
const subcomp = await root.mount(fixture.querySelector("div")!);
expect(fixture.innerHTML).toBe("<div>main app<div>sub root</div></div>");
root.destroy();
expect(fixture.innerHTML).toBe("<div>main app</div>");
expect(status(comp)).not.toBe("destroyed");
expect(status(subcomp)).toBe("destroyed");
});
test("can create a root in a setup function, then use a hook", async () => {
class C extends Component {
static template = xml`c`;
}
class A extends Component {
static template = xml`a`;
state: any;
setup() {
app.createRoot(C);
this.state = useState({ value: 1 });
}
}
const app = new App(A);
await app.mount(fixture);
expect(fixture.innerHTML).toBe("a");
});
});
test("destroy a subroot while another component is mounted in main app", async () => {
class C extends Component {
static template = xml`c`;
}
class ChildA extends Component {
static template = xml`a<div t-ref="elem"></div>`;
ref: any;
setup() {
this.ref = useRef("elem");
let root = app.createRoot(C);
onMounted(() => {
root.mount(this.ref.el);
});
onWillDestroy(() => {
root.destroy();
});
}
}
class ChildB extends Component {
static template = xml`b`;
}
class SomeComponent extends Component {
static template = xml`
<t t-if="state.flag"><ChildB/></t>
<t t-else=""><ChildA/></t>
`;
static components = { ChildA, ChildB };
state = useState({ flag: false });
}
const app = new App(SomeComponent);
const comp = await app.mount(fixture);
expect(fixture.innerHTML).toBe("a<div></div>");
await nextTick();
expect(fixture.innerHTML).toBe("a<div>c</div>");
comp.state.flag = true;
await nextTick();
expect(fixture.innerHTML).toBe("b");
});
+4 -2
View File
@@ -244,12 +244,14 @@ describe("misc", () => {
});
test("namespace is not propagated to siblings", () => {
const block = createBlock(`<div><svg block-ns="someNameSpace"><g/></svg><div></div></div>`);
const block = createBlock(`<div><svg xmlns="someNameSpace"><g/></svg><div></div></div>`);
const fixture = makeTestFixture();
mount(block(), fixture);
expect(fixture.innerHTML).toBe("<div><svg><g></g></svg><div></div></div>");
expect(fixture.innerHTML).toBe(
'<div><svg xmlns="someNameSpace"><g></g></svg><div></div></div>'
);
expect(fixture.querySelector("svg")!.namespaceURI).toBe("someNameSpace");
expect(fixture.querySelector("g")!.namespaceURI).toBe("someNameSpace");
const allDivs = fixture.querySelectorAll("div");
+31
View File
@@ -145,3 +145,34 @@ test("class attribute (with a preexisting value", async () => {
patch(tree, block([""]));
expect(fixture.innerHTML).toBe(`<div class="tomato"></div>`);
});
test("block-class attributes with preexisting class attribute", async () => {
const block = createBlock('<div block-attributes="0" class="owl"></div>');
const tree = block([{ class: "eagle" }]);
mount(tree, fixture);
expect(fixture.innerHTML).toBe(`<div class="owl eagle"></div>`);
patch(tree, block([{ class: "falcon" }]));
expect(fixture.innerHTML).toBe(`<div class="owl falcon"></div>`);
patch(tree, block([{}]));
expect(fixture.innerHTML).toBe(`<div class="owl"></div>`);
});
test("block-class attributes (array syntax) with preexisting class attribute", async () => {
const block = createBlock('<div block-attributes="0" class="owl"></div>');
const tree = block([["class", "eagle"]]);
mount(tree, fixture);
expect(fixture.innerHTML).toBe(`<div class="owl eagle"></div>`);
patch(tree, block([["class", "falcon"]]));
expect(fixture.innerHTML).toBe(`<div class="owl falcon"></div>`);
patch(tree, block([["class", ""]]));
expect(fixture.innerHTML).toBe(`<div class="owl"></div>`);
patch(tree, block([["class", "buzzard"]]));
expect(fixture.innerHTML).toBe(`<div class="owl buzzard"></div>`);
});
+7 -7
View File
@@ -30,22 +30,22 @@ describe("namespace", () => {
expect(fixture.firstElementChild!.namespaceURI).toBe(XHTML_URI);
});
test("namespace can be changed with block-ns", () => {
const block = createBlock(`<tag block-ns="${SVG_URI}"/>`);
test("namespace can be changed with xmlns", () => {
const block = createBlock(`<tag xmlns="${SVG_URI}"/>`);
const tree = block();
mount(tree, fixture);
expect(fixture.innerHTML).toBe("<tag></tag>");
expect(fixture.innerHTML).toBe(`<tag xmlns="${SVG_URI}"></tag>`);
expect(fixture.firstElementChild!.namespaceURI).toBe(SVG_URI);
});
test("namespace is kept for children", () => {
const block = createBlock(
`<parent block-ns="${SVG_URI}"><child><subchild/></child><child/></parent>`
`<parent xmlns="${SVG_URI}"><child><subchild/></child><child/></parent>`
);
const tree = block();
mount(tree, fixture);
expect(fixture.innerHTML).toBe(
"<parent><child><subchild></subchild></child><child></child></parent>"
`<parent xmlns="${SVG_URI}"><child><subchild></subchild></child><child></child></parent>`
);
const parent = fixture.firstElementChild!;
const child1 = parent.firstElementChild!;
@@ -58,10 +58,10 @@ describe("namespace", () => {
});
test("various namespaces in same block", () => {
const block = createBlock(`<none><one block-ns="one"/><two block-ns="two"/></none>`);
const block = createBlock(`<none><one xmlns="one"/><two xmlns="two"/></none>`);
const tree = block();
mount(tree, fixture);
expect(fixture.innerHTML).toBe("<none><one></one><two></two></none>");
expect(fixture.innerHTML).toBe('<none><one xmlns="one"></one><two xmlns="two"></two></none>');
const none = fixture.firstElementChild!;
const one = none.firstElementChild!;
const two = one.nextElementSibling!;
@@ -707,6 +707,123 @@ exports[`attributes updating classes (with obj notation) 1`] = `
}"
`;
exports[`attributes various combinations of class, t-att-class, and t-att 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div block-attributes=\\"0\\" class=\\"c\\">content</div>\`);
return function template(ctx, node, key = \\"\\") {
let attr1 = {class:'a'};
return block1([attr1]);
}
}"
`;
exports[`attributes various combinations of class, t-att-class, and t-att 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div block-attributes=\\"0\\" block-attribute-1=\\"class\\" class=\\"c\\">content</div>\`);
return function template(ctx, node, key = \\"\\") {
let attr1 = {class:'a'};
let attr2 = {'b':true};
return block1([attr1, attr2]);
}
}"
`;
exports[`attributes various combinations of class, t-att-class, and t-att 3`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div block-attributes=\\"0\\" class=\\"c\\" block-attribute-1=\\"class\\">content</div>\`);
return function template(ctx, node, key = \\"\\") {
let attr1 = {class:'a'};
let attr2 = {'b':true};
return block1([attr1, attr2]);
}
}"
`;
exports[`attributes various combinations of class, t-att-class, and t-att 4`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div class=\\"c\\" block-attributes=\\"0\\" block-attribute-1=\\"class\\">content</div>\`);
return function template(ctx, node, key = \\"\\") {
let attr1 = {class:'a'};
let attr2 = {'b':true};
return block1([attr1, attr2]);
}
}"
`;
exports[`attributes various combinations of class, t-att-class, and t-att 5`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div class=\\"c\\" block-attribute-0=\\"class\\" block-attributes=\\"1\\">content</div>\`);
return function template(ctx, node, key = \\"\\") {
let attr1 = {'b':true};
let attr2 = {class:'a'};
return block1([attr1, attr2]);
}
}"
`;
exports[`attributes various combinations of class, t-att-class, and t-att 6`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div class=\\"c\\" block-attribute-0=\\"class\\">content</div>\`);
return function template(ctx, node, key = \\"\\") {
let attr1 = {'b':true};
return block1([attr1]);
}
}"
`;
exports[`attributes various combinations of class, t-att-class, and t-att 7`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div class=\\"c\\" block-attribute-0=\\"class\\">content</div>\`);
return function template(ctx, node, key = \\"\\") {
let attr1 = ('b');
return block1([attr1]);
}
}"
`;
exports[`attributes various combinations of class, t-att-class, and t-att 8`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div block-attributes=\\"0\\" block-attribute-1=\\"class\\">content</div>\`);
return function template(ctx, node, key = \\"\\") {
let attr1 = {class:'a'};
let attr2 = {'b':true};
return block1([attr1, attr2]);
}
}"
`;
exports[`attributes various escapes 1`] = `
"function anonymous(app, bdom, helpers
) {
@@ -1,5 +1,38 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`comments comment node with backslash at top level 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return comment(\` \\\\\\\\ \`);
}
}"
`;
exports[`comments comment node with backtick at top-level 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return comment(\` \\\\\` \`);
}
}"
`;
exports[`comments comment node with interpolation sigil at top level 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return comment(\` \\\\\${very cool} \`);
}
}"
`;
exports[`comments only a comment 1`] = `
"function anonymous(app, bdom, helpers
) {
@@ -34,7 +67,7 @@ exports[`comments properly handle comments between t-if/t-else 1`] = `
let block3 = createBlock(\`<span>owl</span>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (true) {
b2 = block2();
} else {
@@ -72,7 +72,7 @@ exports[`t-on can bind handlers with empty object (with non empty inner string)
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(['someval']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`action\`] = v_block2[i1];
ctx[\`action\`] = k_block2[i1];
ctx[\`action_index\`] = i1;
const key1 = ctx['action_index'];
const v1 = ctx['activate'];
@@ -142,7 +142,7 @@ exports[`t-on handler is bound to proper owner, part 2 1`] = `
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList([1]);;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`value\`] = v_block1[i1];
ctx[\`value\`] = k_block1[i1];
const key1 = ctx['value'];
let hdlr1 = [ctx['add'], ctx];
c_block1[i1] = withKey(block2([hdlr1]), key1);
@@ -189,11 +189,11 @@ exports[`t-on handler is bound to proper owner, part 4 1`] = `
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList([1]);;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`value\`] = v_block1[i1];
ctx[\`value\`] = k_block1[i1];
ctx[\`value_first\`] = i1 === 0;
ctx[\`value_last\`] = i1 === v_block1.length - 1;
ctx[\`value_last\`] = i1 === k_block1.length - 1;
ctx[\`value_index\`] = i1;
ctx[\`value_value\`] = k_block1[i1];
ctx[\`value_value\`] = v_block1[i1];
const key1 = ctx['value'];
c_block1[i1] = withKey(callTemplate_1.call(this, ctx, node, key + \`__1__\${key1}\`), key1);
}
@@ -348,7 +348,7 @@ exports[`t-on t-on modifiers (native listener) t-on with prevent modifier in t-f
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['projects']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`project\`] = v_block2[i1];
ctx[\`project\`] = k_block2[i1];
const key1 = ctx['project'];
const v1 = ctx['onEdit'];
const v2 = ctx['project'];
+21 -21
View File
@@ -18,7 +18,7 @@ exports[`misc complex template 1`] = `
let block13 = createBlock(\`<i class=\\"fa fa-fw fa-clock-o\\" title=\\"This commit is the head of a base branch\\"/>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3,b4,b6,b8;
let b2, b3, b4, b6, b8;
let attr1 = \`batch_tile \${ctx['options'].more?'more':'nomore'}\`;
let attr2 = \`card bg-\${ctx['klass']}-light\`;
let attr3 = \`/runbot/batch/\${ctx['batch'].id}\`;
@@ -33,7 +33,7 @@ exports[`misc complex template 1`] = `
ctx = Object.create(ctx);
const [k_block4, v_block4, l_block4, c_block4] = prepareList(ctx['batch'].slot_ids.filter(_slot=>_slot.build_id.id&&!_slot.trigger_id.manual&&(ctx['options'].trigger_display[_slot.trigger_id.id])));;
for (let i1 = 0; i1 < l_block4; i1++) {
ctx[\`slot\`] = v_block4[i1];
ctx[\`slot\`] = k_block4[i1];
const key1 = ctx['slot'].id;
c_block4[i1] = withKey(comp1({class: ctx['slot_container'],slot: ctx['slot']}, key + \`__1__\${key1}\`, node, this, null), key1);
}
@@ -42,7 +42,7 @@ exports[`misc complex template 1`] = `
ctx = Object.create(ctx);
const [k_block6, v_block6, l_block6, c_block6] = prepareList([1,2,3,4]);;
for (let i1 = 0; i1 < l_block6; i1++) {
ctx[\`x\`] = v_block6[i1];
ctx[\`x\`] = k_block6[i1];
const key1 = ctx['x'];
c_block6[i1] = withKey(block7(), key1);
}
@@ -51,9 +51,9 @@ exports[`misc complex template 1`] = `
ctx = Object.create(ctx);
const [k_block8, v_block8, l_block8, c_block8] = prepareList(ctx['commit_links']);;
for (let i1 = 0; i1 < l_block8; i1++) {
ctx[\`commit_link\`] = v_block8[i1];
ctx[\`commit_link\`] = k_block8[i1];
const key1 = ctx['commit_link'].id;
let b10,b11,b12,b13;
let b10, b11, b12, b13;
let attr5 = \`/runbot/commit/\${ctx['commit_link'].commit_id}\`;
let attr6 = \`badge badge-light batch_commit match_type_\${ctx['commit_link'].match_type}\`;
if (ctx['commit_link'].match_type=='new') {
@@ -99,11 +99,11 @@ exports[`misc global 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList([4,5,6]);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`value\`] = v_block2[i1];
ctx[\`value\`] = k_block2[i1];
ctx[\`value_first\`] = i1 === 0;
ctx[\`value_last\`] = i1 === v_block2.length - 1;
ctx[\`value_last\`] = i1 === k_block2.length - 1;
ctx[\`value_index\`] = i1;
ctx[\`value_value\`] = k_block2[i1];
ctx[\`value_value\`] = v_block2[i1];
const key1 = ctx['value'];
let txt1 = ctx['value'];
const b4 = block4([txt1]);
@@ -112,16 +112,16 @@ exports[`misc global 1`] = `
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
setContextValue(ctx, \\"foo\\", 'aaa');
const b6 = callTemplate_1.call(this, ctx, node, key + \`__1__\${key1}\`);
const b7 = callTemplate_1.call(this, ctx, node, key + \`__1__\${key1}\`);
ctx = ctx.__proto__;
const b7 = callTemplate_2.call(this, ctx, node, key + \`__2__\${key1}\`);
const b8 = callTemplate_2.call(this, ctx, node, key + \`__2__\${key1}\`);
setContextValue(ctx, \\"foo\\", 'bbb');
const b8 = callTemplate_3.call(this, ctx, node, key + \`__3__\${key1}\`);
const b5 = multi([b6, b7, b8]);
ctx[zero] = b5;
const b9 = callTemplate_4.call(this, ctx, node, key + \`__4__\${key1}\`);
const b9 = callTemplate_3.call(this, ctx, node, key + \`__3__\${key1}\`);
const b6 = multi([b7, b8, b9]);
ctx[zero] = b6;
const b5 = callTemplate_4.call(this, ctx, node, key + \`__4__\${key1}\`);
ctx = ctx.__proto__;
c_block2[i1] = withKey(multi([b4, b9]), key1);
c_block2[i1] = withKey(multi([b4, b5]), key1);
}
ctx = ctx.__proto__;
const b2 = list(c_block2);
@@ -217,13 +217,13 @@ exports[`misc other complex template 1`] = `
let block25 = createBlock(\`<div><block-child-0/><block-child-1/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b4,b14,b17,b22,b23,b24,b25;
let b2, b4, b14, b17, b22, b23, b24, b25;
let attr1 = \`/runbot/\${ctx['project'].slug}\`;
let txt1 = ctx['project'].name;
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['projects']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`project\`] = v_block2[i1];
ctx[\`project\`] = k_block2[i1];
const key1 = ctx['project'].id;
let hdlr1 = [ctx['selectProject'](ctx['project']), ctx];
let txt2 = ctx['project'].name;
@@ -232,12 +232,12 @@ exports[`misc other complex template 1`] = `
ctx = ctx.__proto__;
b2 = list(c_block2);
if (ctx['user']) {
let b5,b6;
let b5, b6;
if (ctx['user'].public) {
let attr2 = \`/web/login?redirect=/\`;
b5 = block5([attr2]);
} else {
let b7,b10,b13;
let b7, b10, b13;
if (ctx['nb_assigned_errors']&&ctx['nb_assigned_errors']>0) {
let attr3 = \`You have \${ctx['nb_assigned_errors']} random bug assigned\`;
let txt3 = ctx['nb_assigned_errors'];
@@ -263,7 +263,7 @@ exports[`misc other complex template 1`] = `
ctx = Object.create(ctx);
const [k_block15, v_block15, l_block15, c_block15] = prepareList(ctx['categories']);;
for (let i1 = 0; i1 < l_block15; i1++) {
ctx[\`category\`] = v_block15[i1];
ctx[\`category\`] = k_block15[i1];
const key1 = ctx['category'].id;
let attr6 = ctx['category'].id;
let prop1 = new Boolean(ctx['category'].id==ctx['options'].active_category_id);
@@ -284,7 +284,7 @@ exports[`misc other complex template 1`] = `
ctx = Object.create(ctx);
const [k_block18, v_block18, l_block18, c_block18] = prepareList(ctx['triggers']);;
for (let i1 = 0; i1 < l_block18; i1++) {
ctx[\`trigger\`] = v_block18[i1];
ctx[\`trigger\`] = k_block18[i1];
const key1 = ctx['trigger'].id;
let b20;
if (!ctx['trigger'].manual&&ctx['trigger'].project_id===ctx['project'].id&&ctx['trigger'].category_id===ctx['options'].active_category_id) {
@@ -12,7 +12,7 @@ exports[`memory t-foreach does not leak stuff in global scope 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList([3,2,1]);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`item\`] = v_block2[i1];
ctx[\`item\`] = k_block2[i1];
ctx[\`item_index\`] = i1;
const key1 = ctx['item_index'];
c_block2[i1] = withKey(text(ctx['item']), key1);
@@ -341,6 +341,39 @@ exports[`simple templates, mostly static template with t tag with multiple conte
}"
`;
exports[`simple templates, mostly static text node with backslash at top level 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(\`\\\\\\\\\`);
}
}"
`;
exports[`simple templates, mostly static text node with backtick at top-level 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(\`\\\\\`\`);
}
}"
`;
exports[`simple templates, mostly static text node with interpolation sigil at top level 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(\`\\\\\${very cool}\`);
}
}"
`;
exports[`simple templates, mostly static two t-escs next to each other 1`] = `
"function anonymous(app, bdom, helpers
) {
+11 -11
View File
@@ -5,7 +5,7 @@ exports[`properly support svg add proper namespace to g tags 1`] = `
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<g block-ns=\\"http://www.w3.org/2000/svg\\"><circle cx=\\"50\\" cy=\\"50\\" r=\\"4\\" stroke=\\"green\\" stroke-width=\\"1\\" fill=\\"yellow\\"/> </g>\`);
let block1 = createBlock(\`<g xmlns=\\"http://www.w3.org/2000/svg\\"><circle cx=\\"50\\" cy=\\"50\\" r=\\"4\\" stroke=\\"green\\" stroke-width=\\"1\\" fill=\\"yellow\\"/> </g>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
@@ -18,7 +18,7 @@ exports[`properly support svg add proper namespace to svg 1`] = `
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<svg block-ns=\\"http://www.w3.org/2000/svg\\" width=\\"100px\\" height=\\"90px\\"><circle cx=\\"50\\" cy=\\"50\\" r=\\"4\\" stroke=\\"green\\" stroke-width=\\"1\\" fill=\\"yellow\\"/> </svg>\`);
let block1 = createBlock(\`<svg xmlns=\\"http://www.w3.org/2000/svg\\" width=\\"100px\\" height=\\"90px\\"><circle cx=\\"50\\" cy=\\"50\\" r=\\"4\\" stroke=\\"green\\" stroke-width=\\"1\\" fill=\\"yellow\\"/> </svg>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
@@ -31,7 +31,7 @@ exports[`properly support svg namespace to g tags not added if already in svg na
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<svg block-ns=\\"http://www.w3.org/2000/svg\\"><g/></svg>\`);
let block1 = createBlock(\`<svg xmlns=\\"http://www.w3.org/2000/svg\\"><g/></svg>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
@@ -44,7 +44,7 @@ exports[`properly support svg namespace to svg tags added even if already in svg
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<svg block-ns=\\"http://www.w3.org/2000/svg\\"><svg/></svg>\`);
let block1 = createBlock(\`<svg xmlns=\\"http://www.w3.org/2000/svg\\"><svg/></svg>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
@@ -58,8 +58,8 @@ exports[`properly support svg svg creates new block if it is within html -- 2 1`
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div><block-child-0/></div>\`);
let block2 = createBlock(\`<svg block-ns=\\"http://www.w3.org/2000/svg\\"><polygon fill=\\"#000000\\" points=\\"0 0 4 4 8 0\\" transform=\\"translate(5 7)\\"/><block-child-0/></svg>\`);
let block3 = createBlock(\`<path block-ns=\\"http://www.w3.org/2000/svg\\"/>\`);
let block2 = createBlock(\`<svg xmlns=\\"http://www.w3.org/2000/svg\\"><polygon fill=\\"#000000\\" points=\\"0 0 4 4 8 0\\" transform=\\"translate(5 7)\\"/><block-child-0 xmlns=\\"\\"/></svg>\`);
let block3 = createBlock(\`<path xmlns=\\"http://www.w3.org/2000/svg\\"/>\`);
return function template(ctx, node, key = \\"\\") {
let b3;
@@ -78,7 +78,7 @@ exports[`properly support svg svg creates new block if it is within html 1`] = `
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div><block-child-0/></div>\`);
let block2 = createBlock(\`<svg block-ns=\\"http://www.w3.org/2000/svg\\"><polygon fill=\\"#000000\\" points=\\"0 0 4 4 8 0\\" transform=\\"translate(5 7)\\"/></svg>\`);
let block2 = createBlock(\`<svg xmlns=\\"http://www.w3.org/2000/svg\\"><polygon fill=\\"#000000\\" points=\\"0 0 4 4 8 0\\" transform=\\"translate(5 7)\\"/></svg>\`);
return function template(ctx, node, key = \\"\\") {
const b2 = block2();
@@ -93,7 +93,7 @@ exports[`properly support svg svg namespace added to sub templates if root tag i
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
const callTemplate_1 = app.getTemplate(\`path\`);
let block1 = createBlock(\`<svg block-ns=\\"http://www.w3.org/2000/svg\\"><block-child-0/></svg>\`);
let block1 = createBlock(\`<svg xmlns=\\"http://www.w3.org/2000/svg\\"><block-child-0 xmlns=\\"\\"/></svg>\`);
return function template(ctx, node, key = \\"\\") {
const b2 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
@@ -107,7 +107,7 @@ exports[`properly support svg svg namespace added to sub templates if root tag i
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<path block-ns=\\"http://www.w3.org/2000/svg\\"/>\`);
let block1 = createBlock(\`<path xmlns=\\"http://www.w3.org/2000/svg\\"/>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
@@ -120,8 +120,8 @@ exports[`properly support svg svg namespace added to sub-blocks 1`] = `
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<svg block-ns=\\"http://www.w3.org/2000/svg\\"><block-child-0/></svg>\`);
let block2 = createBlock(\`<path block-ns=\\"http://www.w3.org/2000/svg\\"/>\`);
let block1 = createBlock(\`<svg xmlns=\\"http://www.w3.org/2000/svg\\"><block-child-0 xmlns=\\"\\"/></svg>\`);
let block2 = createBlock(\`<path xmlns=\\"http://www.w3.org/2000/svg\\"/>\`);
return function template(ctx, node, key = \\"\\") {
let b2;
+203 -75
View File
@@ -61,19 +61,19 @@ exports[`t-call (template calling) call with several sub nodes on same line 1`]
const callTemplate_1 = app.getTemplate(\`sub\`);
let block1 = createBlock(\`<div><block-child-0/></div>\`);
let block3 = createBlock(\`<span>hey</span>\`);
let block5 = createBlock(\`<span>yay</span>\`);
let block4 = createBlock(\`<span>hey</span>\`);
let block6 = createBlock(\`<span>yay</span>\`);
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
const b3 = block3();
const b4 = text(\` \`);
const b5 = block5();
const b2 = multi([b3, b4, b5]);
ctx[zero] = b2;
const b6 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
return block1([], [b6]);
const b4 = block4();
const b5 = text(\` \`);
const b6 = block6();
const b3 = multi([b4, b5, b6]);
ctx[zero] = b3;
const b2 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
return block1([], [b2]);
}
}"
`;
@@ -101,19 +101,19 @@ exports[`t-call (template calling) cascading t-call t-out='0' 1`] = `
const callTemplate_1 = app.getTemplate(\`subTemplate\`);
let block1 = createBlock(\`<div><block-child-0/></div>\`);
let block3 = createBlock(\`<span>hey</span>\`);
let block5 = createBlock(\`<span>yay</span>\`);
let block4 = createBlock(\`<span>hey</span>\`);
let block6 = createBlock(\`<span>yay</span>\`);
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
const b3 = block3();
const b4 = text(\` \`);
const b5 = block5();
const b2 = multi([b3, b4, b5]);
ctx[zero] = b2;
const b6 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
return block1([], [b6]);
const b4 = block4();
const b5 = text(\` \`);
const b6 = block6();
const b3 = multi([b4, b5, b6]);
ctx[zero] = b3;
const b2 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
return block1([], [b2]);
}
}"
`;
@@ -126,17 +126,17 @@ exports[`t-call (template calling) cascading t-call t-out='0' 2`] = `
const callTemplate_1 = app.getTemplate(\`subSubTemplate\`);
let block1 = createBlock(\`<div><block-child-0/></div>\`);
let block3 = createBlock(\`<span>cascade 0</span>\`);
let block4 = createBlock(\`<span>cascade 0</span>\`);
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
const b3 = block3();
const b4 = ctx[zero];
const b2 = multi([b3, b4]);
ctx[zero] = b2;
const b5 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
return block1([], [b5]);
const b4 = block4();
const b5 = ctx[zero];
const b3 = multi([b4, b5]);
ctx[zero] = b3;
const b2 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
return block1([], [b2]);
}
}"
`;
@@ -149,17 +149,17 @@ exports[`t-call (template calling) cascading t-call t-out='0' 3`] = `
const callTemplate_1 = app.getTemplate(\`finalTemplate\`);
let block1 = createBlock(\`<div><block-child-0/></div>\`);
let block3 = createBlock(\`<span>cascade 1</span>\`);
let block4 = createBlock(\`<span>cascade 1</span>\`);
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
const b3 = block3();
const b4 = ctx[zero];
const b2 = multi([b3, b4]);
ctx[zero] = b2;
const b5 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
return block1([], [b5]);
const b4 = block4();
const b5 = ctx[zero];
const b3 = multi([b4, b5]);
ctx[zero] = b3;
const b2 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
return block1([], [b2]);
}
}"
`;
@@ -186,17 +186,17 @@ exports[`t-call (template calling) cascading t-call t-out='0', without external
let { isBoundary, zero } = helpers;
const callTemplate_1 = app.getTemplate(\`subTemplate\`);
let block2 = createBlock(\`<span>hey</span>\`);
let block4 = createBlock(\`<span>yay</span>\`);
let block3 = createBlock(\`<span>hey</span>\`);
let block5 = createBlock(\`<span>yay</span>\`);
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
const b2 = block2();
const b3 = text(\` \`);
const b4 = block4();
const b1 = multi([b2, b3, b4]);
ctx[zero] = b1;
const b3 = block3();
const b4 = text(\` \`);
const b5 = block5();
const b2 = multi([b3, b4, b5]);
ctx[zero] = b2;
return callTemplate_1.call(this, ctx, node, key + \`__1\`);
}
}"
@@ -209,15 +209,15 @@ exports[`t-call (template calling) cascading t-call t-out='0', without external
let { isBoundary, zero } = helpers;
const callTemplate_1 = app.getTemplate(\`subSubTemplate\`);
let block2 = createBlock(\`<span>cascade 0</span>\`);
let block3 = createBlock(\`<span>cascade 0</span>\`);
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
const b2 = block2();
const b3 = ctx[zero];
const b1 = multi([b2, b3]);
ctx[zero] = b1;
const b3 = block3();
const b4 = ctx[zero];
const b2 = multi([b3, b4]);
ctx[zero] = b2;
return callTemplate_1.call(this, ctx, node, key + \`__1\`);
}
}"
@@ -230,15 +230,15 @@ exports[`t-call (template calling) cascading t-call t-out='0', without external
let { isBoundary, zero } = helpers;
const callTemplate_1 = app.getTemplate(\`finalTemplate\`);
let block2 = createBlock(\`<span>cascade 1</span>\`);
let block3 = createBlock(\`<span>cascade 1</span>\`);
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
const b2 = block2();
const b3 = ctx[zero];
const b1 = multi([b2, b3]);
ctx[zero] = b1;
const b3 = block3();
const b4 = ctx[zero];
const b2 = multi([b3, b4]);
ctx[zero] = b2;
return callTemplate_1.call(this, ctx, node, key + \`__1\`);
}
}"
@@ -342,15 +342,15 @@ exports[`t-call (template calling) nested t-calls with magic variable 0 1`] = `
const callTemplate_1 = app.getTemplate(\`grandchild\`);
const callTemplate_2 = app.getTemplate(\`child\`);
let block1 = createBlock(\`<p>Some content...</p>\`);
let block3 = createBlock(\`<p>Some content...</p>\`);
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
const b1 = block1();
ctx[zero] = b1;
const b3 = block3();
ctx[zero] = b3;
const b2 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
ctx = ctx.__proto__;
ctx[zero] = b2;
@@ -440,11 +440,11 @@ exports[`t-call (template calling) recursive template, part 2 2`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['node'].children||[]);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`subtree\`] = v_block2[i1];
ctx[\`subtree\`] = k_block2[i1];
ctx[\`subtree_first\`] = i1 === 0;
ctx[\`subtree_last\`] = i1 === v_block2.length - 1;
ctx[\`subtree_last\`] = i1 === k_block2.length - 1;
ctx[\`subtree_index\`] = i1;
ctx[\`subtree_value\`] = k_block2[i1];
ctx[\`subtree_value\`] = v_block2[i1];
const key1 = ctx['subtree_index'];
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
@@ -495,11 +495,11 @@ exports[`t-call (template calling) recursive template, part 3 2`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['node'].children||[]);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`subtree\`] = v_block2[i1];
ctx[\`subtree\`] = k_block2[i1];
ctx[\`subtree_first\`] = i1 === 0;
ctx[\`subtree_last\`] = i1 === v_block2.length - 1;
ctx[\`subtree_last\`] = i1 === k_block2.length - 1;
ctx[\`subtree_index\`] = i1;
ctx[\`subtree_value\`] = k_block2[i1];
ctx[\`subtree_value\`] = v_block2[i1];
const key1 = ctx['subtree_index'];
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
@@ -553,11 +553,11 @@ exports[`t-call (template calling) recursive template, part 4: with t-set recurs
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['node'].children||[]);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`subtree\`] = v_block2[i1];
ctx[\`subtree\`] = k_block2[i1];
ctx[\`subtree_first\`] = i1 === 0;
ctx[\`subtree_last\`] = i1 === v_block2.length - 1;
ctx[\`subtree_last\`] = i1 === k_block2.length - 1;
ctx[\`subtree_index\`] = i1;
ctx[\`subtree_value\`] = k_block2[i1];
ctx[\`subtree_value\`] = v_block2[i1];
const key1 = ctx['subtree_index'];
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
@@ -571,6 +571,134 @@ exports[`t-call (template calling) recursive template, part 4: with t-set recurs
}"
`;
exports[`t-call (template calling) root t-call with body: t-foreach 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { isBoundary, prepareList, withKey, zero } = helpers;
const callTemplate_1 = app.getTemplate(\`subTemplate\`);
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList([1]);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`i\`] = k_block2[i1];
const key1 = ctx['i'];
c_block2[i1] = withKey(text(\`1\`), key1);
}
ctx = ctx.__proto__;
const b2 = list(c_block2);
ctx[zero] = b2;
return callTemplate_1.call(this, ctx, node, key + \`__1\`);
}
}"
`;
exports[`t-call (template calling) root t-call with body: t-foreach 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(\`sub\`);
}
}"
`;
exports[`t-call (template calling) root t-call with body: t-if false 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { isBoundary, zero } = helpers;
const callTemplate_1 = app.getTemplate(\`subTemplate\`);
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
let b3;
if (false) {
b3 = text(\`zero\`);
}
const b2 = multi([b3]);
ctx[zero] = b2;
return callTemplate_1.call(this, ctx, node, key + \`__1\`);
}
}"
`;
exports[`t-call (template calling) root t-call with body: t-if false 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(\`sub\`);
}
}"
`;
exports[`t-call (template calling) root t-call with body: t-if true 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { isBoundary, zero } = helpers;
const callTemplate_1 = app.getTemplate(\`subTemplate\`);
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
let b3;
if (true) {
b3 = text(\`zero\`);
}
const b2 = multi([b3]);
ctx[zero] = b2;
return callTemplate_1.call(this, ctx, node, key + \`__1\`);
}
}"
`;
exports[`t-call (template calling) root t-call with body: t-if true 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(\`sub\`);
}
}"
`;
exports[`t-call (template calling) root t-call with body: t-out with default 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { isBoundary, safeOutput, zero } = helpers;
const callTemplate_1 = app.getTemplate(\`subTemplate\`);
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
const b2 = safeOutput(ctx['nothing']);
ctx[zero] = b2;
return callTemplate_1.call(this, ctx, node, key + \`__1\`);
}
}"
`;
exports[`t-call (template calling) root t-call with body: t-out with default 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
return text(\`sub\`);
}
}"
`;
exports[`t-call (template calling) scoped parameters 1`] = `
"function anonymous(app, bdom, helpers
) {
@@ -705,13 +833,13 @@ exports[`t-call (template calling) t-call with body content as root of a templat
let { isBoundary, zero } = helpers;
const callTemplate_1 = app.getTemplate(\`antony\`);
let block1 = createBlock(\`<p>antony</p>\`);
let block2 = createBlock(\`<p>antony</p>\`);
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
const b1 = block1();
ctx[zero] = b1;
const b2 = block2();
ctx[zero] = b2;
return callTemplate_1.call(this, ctx, node, key + \`__1\`);
}
}"
@@ -813,11 +941,11 @@ exports[`t-call (template calling) t-call with t-set inside and outside 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['list']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`v\`] = v_block2[i1];
ctx[\`v\`] = k_block2[i1];
ctx[\`v_first\`] = i1 === 0;
ctx[\`v_last\`] = i1 === v_block2.length - 1;
ctx[\`v_last\`] = i1 === k_block2.length - 1;
ctx[\`v_index\`] = i1;
ctx[\`v_value\`] = k_block2[i1];
ctx[\`v_value\`] = v_block2[i1];
const key1 = ctx['v_index'];
setContextValue(ctx, \\"val\\", ctx['v'].val);
ctx = Object.create(ctx);
@@ -880,11 +1008,11 @@ exports[`t-call (template calling) t-call with t-set inside and outside. 2 2`] =
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['list']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`v\`] = v_block2[i1];
ctx[\`v\`] = k_block2[i1];
ctx[\`v_first\`] = i1 === 0;
ctx[\`v_last\`] = i1 === v_block2.length - 1;
ctx[\`v_last\`] = i1 === k_block2.length - 1;
ctx[\`v_index\`] = i1;
ctx[\`v_value\`] = k_block2[i1];
ctx[\`v_value\`] = v_block2[i1];
const key1 = ctx['v_index'];
setContextValue(ctx, \\"val\\", ctx['v'].val);
ctx = Object.create(ctx);
@@ -928,7 +1056,7 @@ exports[`t-call (template calling) t-call, conditional and t-set in t-call body
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1
let b2,b3;
let b2, b3;
setContextValue(ctx, \\"v1\\", 'elif');
if (ctx['v1']==='if') {
b2 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
@@ -1075,8 +1203,8 @@ exports[`t-call (template calling) with unused body 1`] = `
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
const b1 = text(\`WHEEE\`);
ctx[zero] = b1;
const b2 = text(\`WHEEE\`);
ctx[zero] = b2;
return callTemplate_1.call(this, ctx, node, key + \`__1\`);
}
}"
@@ -1136,8 +1264,8 @@ exports[`t-call (template calling) with used body 1`] = `
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
const b1 = text(\`ok\`);
ctx[zero] = b1;
const b2 = text(\`ok\`);
ctx[zero] = b2;
return callTemplate_1.call(this, ctx, node, key + \`__1\`);
}
}"
@@ -0,0 +1,29 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`t-custom can use t-custom directive on a node 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div class=\\"my-div\\" block-handler-0=\\"click\\"/>\`);
return function template(ctx, node, key = \\"\\") {
let hdlr1 = [ctx['click'], ctx];
return block1([hdlr1]);
}
}"
`;
exports[`t-custom can use t-custom directive with modifiers on a node 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div class=\\"my-div\\" block-handler-0=\\"click\\"/>\`);
return function template(ctx, node, key = \\"\\") {
let hdlr1 = [ctx['click'], ctx];
return block1([hdlr1]);
}
}"
`;
@@ -49,6 +49,27 @@ exports[`debugging t-debug on sub template 2`] = `
}"
`;
exports[`debugging t-debug: interaction with t-set 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { isBoundary, withDefault, setContextValue } = helpers;
let block1 = createBlock(\`<span><block-text-0/></span>\`);
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1
debugger;
setContextValue(ctx, \\"foo\\", 42);
debugger;
setContextValue(ctx, \\"bar\\", 49);
let txt1 = ctx['foo']+ctx['bar'];
return block1([txt1]);
}
}"
`;
exports[`debugging t-log 1`] = `
"function anonymous(app, bdom, helpers
) {
@@ -66,3 +87,24 @@ exports[`debugging t-log 1`] = `
}
}"
`;
exports[`debugging t-log: interaction with t-set 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { isBoundary, withDefault, setContextValue } = helpers;
let block1 = createBlock(\`<span><block-text-0/></span>\`);
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1
console.log(ctx['foo']);
setContextValue(ctx, \\"foo\\", 42);
console.log(ctx['bar']);
setContextValue(ctx, \\"bar\\", 49);
let txt1 = ctx['foo']+ctx['bar'];
return block1([txt1]);
}
}"
`;
@@ -1,5 +1,41 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`t-esc default with backslash at top level 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { withDefault } = helpers;
return function template(ctx, node, key = \\"\\") {
return text(withDefault(undefined, \`\\\\\\\\\`));
}
}"
`;
exports[`t-esc default with backtick at top-level 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { withDefault } = helpers;
return function template(ctx, node, key = \\"\\") {
return text(withDefault(undefined, \`\\\\\`\`));
}
}"
`;
exports[`t-esc default with interpolation sigil at top level 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { withDefault } = helpers;
return function template(ctx, node, key = \\"\\") {
return text(withDefault(undefined, \`\\\\\${very cool}\`));
}
}"
`;
exports[`t-esc div with falsy values 1`] = `
"function anonymous(app, bdom, helpers
) {
@@ -180,15 +216,15 @@ exports[`t-esc t-esc=0 is escaped 1`] = `
const callTemplate_1 = app.getTemplate(\`sub\`);
let block1 = createBlock(\`<div><block-child-0/></div>\`);
let block2 = createBlock(\`<p>escaped</p>\`);
let block3 = createBlock(\`<p>escaped</p>\`);
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
const b2 = block2();
ctx[zero] = b2;
const b3 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
return block1([], [b3]);
const b3 = block3();
ctx[zero] = b3;
const b2 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
return block1([], [b2]);
}
}"
`;
@@ -12,7 +12,7 @@ exports[`t-foreach does not pollute the rendering context 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList([1]);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`item\`] = v_block2[i1];
ctx[\`item\`] = k_block2[i1];
const key1 = ctx['item'];
c_block2[i1] = withKey(text(ctx['item']), key1);
}
@@ -35,7 +35,7 @@ exports[`t-foreach iterate on items (on a element node) 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList([1,2]);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`item\`] = v_block2[i1];
ctx[\`item\`] = k_block2[i1];
const key1 = ctx['item'];
let txt1 = ctx['item'];
c_block2[i1] = withKey(block3([txt1]), key1);
@@ -58,9 +58,9 @@ exports[`t-foreach iterate on items 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList([3,2,1]);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`item\`] = v_block2[i1];
ctx[\`item\`] = k_block2[i1];
ctx[\`item_index\`] = i1;
ctx[\`item_value\`] = k_block2[i1];
ctx[\`item_value\`] = v_block2[i1];
const key1 = ctx['item'];
const b4 = text(\` [\`);
const b5 = text(ctx['item_index']);
@@ -77,6 +77,62 @@ exports[`t-foreach iterate on items 1`] = `
}"
`;
exports[`t-foreach iterate, Map param 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { prepareList, withKey } = helpers;
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList(ctx['value']);;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`item\`] = k_block1[i1];
ctx[\`item_index\`] = i1;
ctx[\`item_value\`] = v_block1[i1];
const key1 = ctx['item_index'];
const b3 = text(\` [\`);
const b4 = text(ctx['item_index']);
const b5 = text(\`: \`);
const b6 = text(ctx['item']);
const b7 = text(\` \`);
const b8 = text(ctx['item_value']);
const b9 = text(\`] \`);
c_block1[i1] = withKey(multi([b3, b4, b5, b6, b7, b8, b9]), key1);
}
return list(c_block1);
}
}"
`;
exports[`t-foreach iterate, Set param 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { prepareList, withKey } = helpers;
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList(ctx['value']);;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`item\`] = k_block1[i1];
ctx[\`item_index\`] = i1;
ctx[\`item_value\`] = v_block1[i1];
const key1 = ctx['item_index'];
const b3 = text(\` [\`);
const b4 = text(ctx['item_index']);
const b5 = text(\`: \`);
const b6 = text(ctx['item']);
const b7 = text(\` \`);
const b8 = text(ctx['item_value']);
const b9 = text(\`] \`);
c_block1[i1] = withKey(multi([b3, b4, b5, b6, b7, b8, b9]), key1);
}
return list(c_block1);
}
}"
`;
exports[`t-foreach iterate, dict param 1`] = `
"function anonymous(app, bdom, helpers
) {
@@ -89,9 +145,9 @@ exports[`t-foreach iterate, dict param 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['value']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`item\`] = v_block2[i1];
ctx[\`item\`] = k_block2[i1];
ctx[\`item_index\`] = i1;
ctx[\`item_value\`] = k_block2[i1];
ctx[\`item_value\`] = v_block2[i1];
const key1 = ctx['item_index'];
const b4 = text(\` [\`);
const b5 = text(ctx['item_index']);
@@ -108,6 +164,62 @@ exports[`t-foreach iterate, dict param 1`] = `
}"
`;
exports[`t-foreach iterate, generator param 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { prepareList, withKey } = helpers;
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList(ctx['gen']());;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`item\`] = k_block1[i1];
ctx[\`item_index\`] = i1;
ctx[\`item_value\`] = v_block1[i1];
const key1 = ctx['item_index'];
const b3 = text(\` [\`);
const b4 = text(ctx['item_index']);
const b5 = text(\`: \`);
const b6 = text(ctx['item']);
const b7 = text(\` \`);
const b8 = text(ctx['item_value']);
const b9 = text(\`] \`);
c_block1[i1] = withKey(multi([b3, b4, b5, b6, b7, b8, b9]), key1);
}
return list(c_block1);
}
}"
`;
exports[`t-foreach iterate, iterable param 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { prepareList, withKey } = helpers;
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList(ctx['map'].values());;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`item\`] = k_block1[i1];
ctx[\`item_index\`] = i1;
ctx[\`item_value\`] = v_block1[i1];
const key1 = ctx['item_index'];
const b3 = text(\` [\`);
const b4 = text(ctx['item_index']);
const b5 = text(\`: \`);
const b6 = text(ctx['item']);
const b7 = text(\` \`);
const b8 = text(ctx['item_value']);
const b9 = text(\`] \`);
c_block1[i1] = withKey(multi([b3, b4, b5, b6, b7, b8, b9]), key1);
}
return list(c_block1);
}
}"
`;
exports[`t-foreach iterate, position 1`] = `
"function anonymous(app, bdom, helpers
) {
@@ -120,12 +232,12 @@ exports[`t-foreach iterate, position 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(Array(5));;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`elem\`] = v_block2[i1];
ctx[\`elem\`] = k_block2[i1];
ctx[\`elem_first\`] = i1 === 0;
ctx[\`elem_last\`] = i1 === v_block2.length - 1;
ctx[\`elem_last\`] = i1 === k_block2.length - 1;
ctx[\`elem_index\`] = i1;
const key1 = ctx['elem'];
let b4,b5,b6,b7,b8,b9;
let b4, b5, b6, b7, b8, b9;
b4 = text(\` -\`);
if (ctx['elem_first']) {
b5 = text(\` first\`);
@@ -144,6 +256,34 @@ exports[`t-foreach iterate, position 1`] = `
}"
`;
exports[`t-foreach iterate, string param 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { prepareList, withKey } = helpers;
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList('abc');;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`item\`] = k_block1[i1];
ctx[\`item_index\`] = i1;
ctx[\`item_value\`] = v_block1[i1];
const key1 = ctx['item_index'];
const b3 = text(\` [\`);
const b4 = text(ctx['item_index']);
const b5 = text(\`: \`);
const b6 = text(ctx['item']);
const b7 = text(\` \`);
const b8 = text(ctx['item_value']);
const b9 = text(\`] \`);
c_block1[i1] = withKey(multi([b3, b4, b5, b6, b7, b8, b9]), key1);
}
return list(c_block1);
}
}"
`;
exports[`t-foreach simple iteration (in a node) 1`] = `
"function anonymous(app, bdom, helpers
) {
@@ -156,7 +296,7 @@ exports[`t-foreach simple iteration (in a node) 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList([3,2,1]);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`item\`] = v_block2[i1];
ctx[\`item\`] = k_block2[i1];
const key1 = ctx['item'];
c_block2[i1] = withKey(text(ctx['item']), key1);
}
@@ -176,7 +316,7 @@ exports[`t-foreach simple iteration 1`] = `
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList([3,2,1]);;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`item\`] = v_block1[i1];
ctx[\`item\`] = k_block1[i1];
const key1 = ctx['item'];
c_block1[i1] = withKey(text(ctx['item']), key1);
}
@@ -198,7 +338,7 @@ exports[`t-foreach simple iteration with two nodes inside 1`] = `
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList([3,2,1]);;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`item\`] = v_block1[i1];
ctx[\`item\`] = k_block1[i1];
const key1 = ctx['item'];
let txt1 = ctx['item'];
const b3 = block3([txt1]);
@@ -227,20 +367,20 @@ exports[`t-foreach t-call with body in t-foreach in t-foreach 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['numbers']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`a\`] = v_block2[i1];
ctx[\`a\`] = k_block2[i1];
ctx[\`a_first\`] = i1 === 0;
ctx[\`a_last\`] = i1 === v_block2.length - 1;
ctx[\`a_last\`] = i1 === k_block2.length - 1;
ctx[\`a_index\`] = i1;
ctx[\`a_value\`] = k_block2[i1];
ctx[\`a_value\`] = v_block2[i1];
const key1 = ctx['a'];
ctx = Object.create(ctx);
const [k_block4, v_block4, l_block4, c_block4] = prepareList(ctx['letters']);;
for (let i2 = 0; i2 < l_block4; i2++) {
ctx[\`b\`] = v_block4[i2];
ctx[\`b\`] = k_block4[i2];
ctx[\`b_first\`] = i2 === 0;
ctx[\`b_last\`] = i2 === v_block4.length - 1;
ctx[\`b_last\`] = i2 === k_block4.length - 1;
ctx[\`b_index\`] = i2;
ctx[\`b_value\`] = k_block4[i2];
ctx[\`b_value\`] = v_block4[i2];
const key2 = ctx['b'];
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
@@ -296,20 +436,20 @@ exports[`t-foreach t-call without body in t-foreach in t-foreach 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['numbers']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`a\`] = v_block2[i1];
ctx[\`a\`] = k_block2[i1];
ctx[\`a_first\`] = i1 === 0;
ctx[\`a_last\`] = i1 === v_block2.length - 1;
ctx[\`a_last\`] = i1 === k_block2.length - 1;
ctx[\`a_index\`] = i1;
ctx[\`a_value\`] = k_block2[i1];
ctx[\`a_value\`] = v_block2[i1];
const key1 = ctx['a'];
ctx = Object.create(ctx);
const [k_block4, v_block4, l_block4, c_block4] = prepareList(ctx['letters']);;
for (let i2 = 0; i2 < l_block4; i2++) {
ctx[\`b\`] = v_block4[i2];
ctx[\`b\`] = k_block4[i2];
ctx[\`b_first\`] = i2 === 0;
ctx[\`b_last\`] = i2 === v_block4.length - 1;
ctx[\`b_last\`] = i2 === k_block4.length - 1;
ctx[\`b_index\`] = i2;
ctx[\`b_value\`] = k_block4[i2];
ctx[\`b_value\`] = v_block4[i2];
const key2 = ctx['b'];
c_block4[i2] = withKey(callTemplate_1.call(this, ctx, node, key + \`__1__\${key1}__\${key2}\`), key2);
}
@@ -363,12 +503,12 @@ exports[`t-foreach t-foreach in t-foreach 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['numbers']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`number\`] = v_block2[i1];
ctx[\`number\`] = k_block2[i1];
const key1 = ctx['number'];
ctx = Object.create(ctx);
const [k_block3, v_block3, l_block3, c_block3] = prepareList(ctx['letters']);;
for (let i2 = 0; i2 < l_block3; i2++) {
ctx[\`letter\`] = v_block3[i2];
ctx[\`letter\`] = k_block3[i2];
const key2 = ctx['letter'];
const b5 = text(\` [\`);
const b6 = text(ctx['number']);
@@ -397,7 +537,7 @@ exports[`t-foreach t-foreach with t-if inside (no external node) 1`] = `
ctx = Object.create(ctx);
const [k_block1, v_block1, l_block1, c_block1] = prepareList(ctx['elems']);;
for (let i1 = 0; i1 < l_block1; i1++) {
ctx[\`elem\`] = v_block1[i1];
ctx[\`elem\`] = k_block1[i1];
const key1 = ctx['elem'].id;
let b3;
if (ctx['elem'].id<3) {
@@ -424,7 +564,7 @@ exports[`t-foreach t-foreach with t-if inside 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['elems']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`elem\`] = v_block2[i1];
ctx[\`elem\`] = k_block2[i1];
const key1 = ctx['elem'].id;
let b4;
if (ctx['elem'].id<3) {
@@ -452,7 +592,7 @@ exports[`t-foreach t-key on t-foreach 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['things']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`thing\`] = v_block2[i1];
ctx[\`thing\`] = k_block2[i1];
const key1 = ctx['thing'];
c_block2[i1] = withKey(block3(), key1);
}
@@ -475,7 +615,7 @@ exports[`t-foreach throws error if invalid loop expression 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['abc']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`item\`] = v_block2[i1];
ctx[\`item\`] = k_block2[i1];
ctx[\`item_index\`] = i1;
const key1 = ctx['item'];
const tKey_1 = ctx['item_index'];
@@ -502,7 +642,7 @@ exports[`t-foreach with t-memo 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['items']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`item\`] = v_block2[i1];
ctx[\`item\`] = k_block2[i1];
const key1 = ctx['item'].id;
const memo1 = [ctx['item'].x];
const vnode1 = cache[key1];;
+16 -16
View File
@@ -8,7 +8,7 @@ exports[`t-if a t-if next to a div 1`] = `
let block2 = createBlock(\`<div>foo</div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
b2 = block2();
if (ctx['cond']) {
b3 = text(\`1\`);
@@ -44,7 +44,7 @@ exports[`t-if boolean value condition elif (no outside node) 1`] = `
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
let b2,b3,b4,b5;
let b2, b3, b4, b5;
if (ctx['color']=='black') {
b2 = text(\`black pearl\`);
} else if (ctx['color']=='yellow') {
@@ -67,7 +67,7 @@ exports[`t-if boolean value condition elif 1`] = `
let block1 = createBlock(\`<div><block-child-0/><block-child-1/><block-child-2/><block-child-3/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3,b4,b5;
let b2, b3, b4, b5;
if (ctx['color']=='black') {
b2 = text(\`black pearl\`);
} else if (ctx['color']=='yellow') {
@@ -90,7 +90,7 @@ exports[`t-if boolean value condition else 1`] = `
let block1 = createBlock(\`<div><span>begin</span><block-child-0/><block-child-1/><span>end</span></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['condition']) {
b2 = text(\`ok\`);
} else {
@@ -109,7 +109,7 @@ exports[`t-if boolean value condition false else 1`] = `
let block1 = createBlock(\`<div><span>begin</span><block-child-0/><block-child-1/><span>end</span></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['condition']) {
b2 = text(\`fail\`);
} else {
@@ -145,7 +145,7 @@ exports[`t-if can use some boolean operators in expressions 1`] = `
let block1 = createBlock(\`<div><block-child-0/><block-child-1/><block-child-2/><block-child-3/><block-child-4/><block-child-5/><block-child-6/><block-child-7/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3,b4,b5,b6,b7,b8,b9;
let b2, b3, b4, b5, b6, b7, b8, b9;
if (ctx['cond1']&&ctx['cond2']) {
b2 = text(\`and\`);
}
@@ -239,7 +239,7 @@ exports[`t-if simple t-if/t-else 1`] = `
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['condition']) {
b2 = text(\`1\`);
} else {
@@ -258,7 +258,7 @@ exports[`t-if simple t-if/t-else in a div 1`] = `
let block1 = createBlock(\`<div><block-child-0/><block-child-1/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['condition']) {
b2 = text(\`1\`);
} else {
@@ -277,7 +277,7 @@ exports[`t-if t-esc with t-elif 1`] = `
let block1 = createBlock(\`<div><block-child-0/><block-child-1/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (false) {
b2 = text(\`abc\`);
} else {
@@ -314,7 +314,7 @@ exports[`t-if t-if and t-else with two nodes 1`] = `
let block5 = createBlock(\`<span>b</span>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['condition']) {
b2 = text(\`1\`);
} else {
@@ -372,7 +372,7 @@ exports[`t-if t-if with empty content 1`] = `
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
b2 = text(\`hello\`);
if (ctx['condition']) {
b3 = text(\`\`);
@@ -388,7 +388,7 @@ exports[`t-if t-if/t-else with more content 1`] = `
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['condition']) {
if (ctx['condition']) {
b2 = text(\`asf\`);
@@ -458,7 +458,7 @@ exports[`t-if t-set, then t-if, part 3 1`] = `
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1
let b2,b3;
let b2, b3;
setContextValue(ctx, \\"y\\", false);
setContextValue(ctx, \\"x\\", ctx['y']);
if (ctx['x']) {
@@ -477,7 +477,7 @@ exports[`t-if two consecutive t-if 1`] = `
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['cond1']) {
b2 = text(\`1\`);
}
@@ -497,7 +497,7 @@ exports[`t-if two consecutive t-if in a div 1`] = `
let block1 = createBlock(\`<div><block-child-0/><block-child-1/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['cond1']) {
b2 = text(\`1\`);
}
@@ -520,7 +520,7 @@ exports[`t-if two t-ifs next to each other 1`] = `
let block5 = createBlock(\`<p>2</p>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['condition']) {
let txt1 = ctx['text'];
b2 = block2([txt1]);
@@ -58,7 +58,7 @@ exports[`t-key t-key directive in a list 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['beers']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`beer\`] = v_block2[i1];
ctx[\`beer\`] = k_block2[i1];
const key1 = ctx['beer'].id;
let txt1 = ctx['beer'].name;
c_block2[i1] = withKey(block3([txt1]), key1);
@@ -79,7 +79,7 @@ exports[`t-key t-key on sub dom node pushes a child block in its parent 1`] = `
let block3 = createBlock(\`<div><h1/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['hasSpan']) {
b2 = block2();
}
@@ -103,3 +103,18 @@ exports[`t-key t-key on sub dom node pushes a child block in its parent 2`] = `
}
}"
`;
exports[`t-key t-key: interaction with t-esc 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<p><block-text-0/></p>\`);
return function template(ctx, node, key = \\"\\") {
const tKey_1 = ctx['key'];
let txt1 = ctx['text'];
return toggler(tKey_1, block1([txt1]));
}
}"
`;
+11 -11
View File
@@ -35,15 +35,15 @@ exports[`t-out multiple calls to t-out 1`] = `
const callTemplate_1 = app.getTemplate(\`sub\`);
let block1 = createBlock(\`<div><block-child-0/></div>\`);
let block2 = createBlock(\`<span>coucou</span>\`);
let block3 = createBlock(\`<span>coucou</span>\`);
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
const b2 = block2();
ctx[zero] = b2;
const b3 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
return block1([], [b3]);
const b3 = block3();
ctx[zero] = b3;
const b2 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
return block1([], [b2]);
}
}"
`;
@@ -102,15 +102,15 @@ exports[`t-out t-out 0 1`] = `
const callTemplate_1 = app.getTemplate(\`_basic-callee\`);
let block1 = createBlock(\`<div><block-child-0/></div>\`);
let block2 = createBlock(\`<div>zero</div>\`);
let block3 = createBlock(\`<div>zero</div>\`);
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1;
const b2 = block2();
ctx[zero] = b2;
const b3 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
return block1([], [b3]);
const b3 = block3();
ctx[zero] = b3;
const b2 = callTemplate_1.call(this, ctx, node, key + \`__1\`);
return block1([], [b2]);
}
}"
`;
@@ -309,7 +309,7 @@ exports[`t-out t-out switch markup on bdom 1`] = `
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1
let b3,b5;
let b3, b5;
ctx[\`bdom\`] = new LazyValue(value1, ctx, this, node, key);
if (ctx['hasBdom']) {
const b4 = safeOutput(ctx['bdom']);
@@ -105,7 +105,7 @@ exports[`t-ref refs in a loop 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['items']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`item\`] = v_block2[i1];
ctx[\`item\`] = k_block2[i1];
const key1 = ctx['item'];
const tKey_1 = ctx['item'];
const v1 = ctx['item'];
@@ -1,5 +1,50 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`t-set body with backslash at top level 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { isBoundary, withDefault, setContextValue } = helpers;
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1
setContextValue(ctx, \\"value\\", \`\\\\\\\\\`);
return text(ctx['value']);
}
}"
`;
exports[`t-set body with backtick at top-level 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { isBoundary, withDefault, setContextValue } = helpers;
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1
setContextValue(ctx, \\"value\\", \`\\\\\`\`);
return text(ctx['value']);
}
}"
`;
exports[`t-set body with interpolation sigil at top level 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { isBoundary, withDefault, setContextValue } = helpers;
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1
setContextValue(ctx, \\"value\\", \`\\\\\${very cool}\`);
return text(ctx['value']);
}
}"
`;
exports[`t-set evaluate value expression 1`] = `
"function anonymous(app, bdom, helpers
) {
@@ -94,7 +139,7 @@ exports[`t-set set from body literal (with t-if/t-else 1`] = `
let { isBoundary, withDefault, LazyValue } = helpers;
function value1(ctx, node, key = \\"\\") {
let b2,b3;
let b2, b3;
if (ctx['condition']) {
b2 = text(\`true\`);
} else {
@@ -351,7 +396,7 @@ exports[`t-set t-set outside modified in t-foreach 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(['a','b']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`val\`] = v_block2[i1];
ctx[\`val\`] = k_block2[i1];
const key1 = ctx['val'];
let txt1 = ctx['iter'];
c_block2[i1] = withKey(block3([txt1]), key1);
@@ -381,7 +426,7 @@ exports[`t-set t-set outside modified in t-foreach increment-after operator 1`]
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(['a','b']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`val\`] = v_block2[i1];
ctx[\`val\`] = k_block2[i1];
const key1 = ctx['val'];
let txt1 = ctx['iter'];
c_block2[i1] = withKey(block3([txt1]), key1);
@@ -411,7 +456,7 @@ exports[`t-set t-set outside modified in t-foreach increment-before operator 1`]
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(['a','b']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`val\`] = v_block2[i1];
ctx[\`val\`] = k_block2[i1];
const key1 = ctx['val'];
let txt1 = ctx['iter'];
c_block2[i1] = withKey(block3([txt1]), key1);
@@ -441,7 +486,7 @@ exports[`t-set t-set should reuse variable if possible 1`] = `
ctx = Object.create(ctx);
const [k_block2, v_block2, l_block2, c_block2] = prepareList(ctx['list']);;
for (let i1 = 0; i1 < l_block2; i1++) {
ctx[\`elem\`] = v_block2[i1];
ctx[\`elem\`] = k_block2[i1];
ctx[\`elem_index\`] = i1;
const key1 = ctx['elem_index'];
let txt1 = ctx['v'];
@@ -0,0 +1,13 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`t-slot compile t-props correctly multiple time 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { callSlot } = helpers;
return function template(ctx, node, key = \\"\\") {
return callSlot(ctx, node, key, 'default', false, Object.assign({}, {a:1}));
}
}"
`;
@@ -101,3 +101,55 @@ exports[`loading templates can load a few templates from an XMLDocument 2`] = `
}
}"
`;
exports[`loading templates getTemplate: element returned (2) 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div>Hello World!</div>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
exports[`loading templates getTemplate: element returned 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div>Hello World!</div>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
exports[`loading templates getTemplate: template string returned 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div>Hello World!</div>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
exports[`loading templates getTemplate: undefined returned 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div>Hello World!</div>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
@@ -1,5 +1,233 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`translation context body of t-sets are translated in context 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { isBoundary, withDefault, setContextValue } = helpers;
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1
setContextValue(ctx, \\"label\\", \`traduit\`);
return text(ctx['label']);
}
}"
`;
exports[`translation context default slot params and content translated in context 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { callSlot } = helpers;
let block1 = createBlock(\`<div><block-child-0/></div>\`);
function defaultContent1(ctx, node, key = \\"\\") {
return text(\` foo \`);
}
return function template(ctx, node, key = \\"\\") {
const b3 = callSlot(ctx, node, key, 'default', false, {param: \`param\`,title: \`título\`}, defaultContent1.bind(this));
return block1([], [b3]);
}
}"
`;
exports[`translation context props with modifier .translate are translated in context 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
const comp1 = app.createComponent(\`ChildComponent\`, true, false, false, []);
return function template(ctx, node, key = \\"\\") {
return comp1({text: \`jeu\`}, key + \`__1\`, node, this, null);
}
}"
`;
exports[`translation context props with modifier .translate are translated in context 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<span><block-text-0/></span>\`);
return function template(ctx, node, key = \\"\\") {
let txt1 = ctx['props'].text;
return block1([txt1]);
}
}"
`;
exports[`translation context slot attrs and text contents are translated in context 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { capture, markRaw } = helpers;
const comp1 = app.createComponent(\`ChildComponent\`, true, true, false, []);
function slot1(ctx, node, key = \\"\\") {
return text(\`jeu\`);
}
return function template(ctx, node, key = \\"\\") {
const ctx1 = capture(ctx);
return comp1({slots: markRaw({'a': {__render: slot1.bind(this), __ctx: ctx1, title: \`título\`}})}, key + \`__1\`, node, this, null);
}
}"
`;
exports[`translation context slot attrs and text contents are translated in context 2`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { callSlot } = helpers;
let block1 = createBlock(\`<div><block-child-0/></div>\`);
return function template(ctx, node, key = \\"\\") {
const b2 = callSlot(ctx, node, key, 'a', false, {});
return block1([], [b2]);
}
}"
`;
exports[`translation context t-translation-context with several children 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div><div/><div/><block-child-0/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2;
if (true) {
b2 = text(\`\`);
}
return block1([], [b2]);
}
}"
`;
exports[`translation context translation of attributes in context 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div title=\\"titre\\" label=\\"game\\"/>\`);
return function template(ctx, node, key = \\"\\") {
return block1();
}
}"
`;
exports[`translation context translation of text in context 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block2 = createBlock(\`<div>word</div>\`);
let block3 = createBlock(\`<div>mot</div>\`);
return function template(ctx, node, key = \\"\\") {
const b2 = block2();
const b3 = block3();
return multi([b2, b3]);
}
}"
`;
exports[`translation support body of t-sets are translated 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { isBoundary, withDefault, setContextValue } = helpers;
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1
setContextValue(ctx, \\"label\\", \`translated\`);
return text(ctx['label']);
}
}"
`;
exports[`translation support body of t-sets inside translation=off are not translated 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { isBoundary, withDefault, setContextValue } = helpers;
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1
setContextValue(ctx, \\"label\\", \`untranslated\`);
return text(ctx['label']);
}
}"
`;
exports[`translation support body of t-sets inside translation=off are not translated 2 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { isBoundary, withDefault, setContextValue } = helpers;
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1
setContextValue(ctx, \\"label\\", \`untranslated\`);
return text(ctx['label']);
}
}"
`;
exports[`translation support body of t-sets with html content are translated 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { isBoundary, withDefault, LazyValue, safeOutput } = helpers;
let block1 = createBlock(\`<div>translated</div>\`);
function value1(ctx, node, key = \\"\\") {
return block1();
}
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1
ctx[\`label\`] = new LazyValue(value1, ctx, this, node, key);
return safeOutput(ctx['label']);
}
}"
`;
exports[`translation support body of t-sets with text and html content are translated 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { isBoundary, withDefault, LazyValue, safeOutput } = helpers;
let block3 = createBlock(\`<div>translated</div>\`);
function value1(ctx, node, key = \\"\\") {
const b2 = text(\` translated \`);
const b3 = block3();
return multi([b2, b3]);
}
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1
ctx[\`label\`] = new LazyValue(value1, ctx, this, node, key);
return safeOutput(ctx['label']);
}
}"
`;
exports[`translation support can set and remove translatable attributes 1`] = `
"function anonymous(app, bdom, helpers
) {
@@ -52,6 +280,38 @@ exports[`translation support some attributes are translated 1`] = `
}"
`;
exports[`translation support t-set and falsy t-value: t-body are translated 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let { isBoundary, withDefault, setContextValue } = helpers;
return function template(ctx, node, key = \\"\\") {
ctx = Object.create(ctx);
ctx[isBoundary] = 1
setContextValue(ctx, \\"label\\", withDefault(false, \`translated\`));
return text(ctx['label']);
}
}"
`;
exports[`translation support t-translation with several children 1`] = `
"function anonymous(app, bdom, helpers
) {
let { text, createBlock, list, multi, html, toggler, comment } = bdom;
let block1 = createBlock(\`<div><div/><div/><block-child-0/></div>\`);
return function template(ctx, node, key = \\"\\") {
let b2;
if (true) {
b2 = text(\`\`);
}
return block1([], [b2]);
}
}"
`;
exports[`translation support translation is done on the trimmed text, with extra spaces readded after 1`] = `
"function anonymous(app, bdom, helpers
) {
+29
View File
@@ -371,4 +371,33 @@ describe("attributes", () => {
// not sure about this. maybe we want to remove the attribute?
expect(fixture.innerHTML).toBe('<div class="hoy a b"></div>');
});
test("various combinations of class, t-att-class, and t-att", () => {
const template1 = `<div t-att="{ class: 'a' }" class="c">content</div>`;
expect(renderToString(template1)).toBe('<div class="c a">content</div>');
const template2 = `<div t-att="{ class: 'a' }" t-att-class="{'b': true}" class="c">content</div>`;
expect(renderToString(template2)).toBe('<div class="c a b">content</div>');
const template3 = `<div t-att="{ class: 'a' }" class="c" t-att-class="{'b': true}">content</div>`;
expect(renderToString(template3)).toBe('<div class="c a b">content</div>');
const template4 = `<div class="c" t-att="{ class: 'a' }" t-att-class="{'b': true}">content</div>`;
expect(renderToString(template4)).toBe('<div class="c a b">content</div>');
const template5 = `<div class="c" t-att-class="{'b': true}" t-att="{ class: 'a' }">content</div>`;
expect(renderToString(template5)).toBe('<div class="c b a">content</div>');
const template6 = `<div class="c" t-att-class="{'b': true}">content</div>`;
expect(renderToString(template6)).toBe('<div class="c b">content</div>');
const template7 = `<div class="c" t-attf-class="{{'b'}}">content</div>`;
expect(renderToString(template7)).toBe('<div class="c b">content</div>');
const template8 = `<div t-att="{ class: 'a' }" class="c" t-att-class="{'b': true}">content</div>`;
expect(renderToString(template8)).toBe('<div class="c a b">content</div>');
const template9 = `<div t-att="{ class: 'a' }" t-att-class="{'b': true}">content</div>`;
expect(renderToString(template9)).toBe('<div class="a b">content</div>');
});
});
+15
View File
@@ -26,4 +26,19 @@ describe("comments", () => {
</div>`;
expect(renderToString(template)).toBe("<div><span>true</span></div>");
});
test("comment node with backslash at top level", () => {
const template = "<!-- \\ -->";
expect(renderToString(template)).toBe("<!-- \\ -->");
});
test("comment node with backtick at top-level", () => {
const template = "<!-- ` -->";
expect(renderToString(template)).toBe("<!-- ` -->");
});
test("comment node with interpolation sigil at top level", () => {
const template = "<!-- ${very cool} -->";
expect(renderToString(template)).toBe("<!-- ${very cool} -->");
});
});
@@ -174,6 +174,9 @@ describe("expression evaluation", () => {
expect(compileExpr("list.data.map((data) => data)")).toBe(
"ctx['list'].data.map((_data)=>_data)"
);
expect(compileExpr("(ev) => { myFunc(v1, v2, ev.target.value); }")).toBe(
"(_ev)=>{ctx['myFunc'](ctx['v1'],ctx['v2'],_ev.target.value);}"
);
});
test.skip("arrow functions: not yet supported", () => {
// e is added to localvars in inline_expression but not removed after the arrow func body
File diff suppressed because it is too large Load Diff
+15
View File
@@ -154,4 +154,19 @@ describe("simple templates, mostly static", () => {
</div>`;
expect(renderToString(template, { a: "a", b: "b", c: "c" })).toBe("<div>abLoadingc</div>");
});
test("text node with backslash at top level", () => {
const template = "\\";
expect(renderToString(template)).toBe("\\");
});
test("text node with backtick at top-level", () => {
const template = "`";
expect(renderToString(template)).toBe("`");
});
test("text node with interpolation sigil at top level", () => {
const template = "${very cool}";
expect(renderToString(template)).toBe("${very cool}");
});
});
+10 -5
View File
@@ -9,20 +9,20 @@ describe("properly support svg", () => {
test("add proper namespace to svg", () => {
const template = `<svg width="100px" height="90px"><circle cx="50" cy="50" r="4" stroke="green" stroke-width="1" fill="yellow"/> </svg>`;
expect(renderToString(template)).toBe(
`<svg width=\"100px\" height=\"90px\"><circle cx=\"50\" cy=\"50\" r=\"4\" stroke=\"green\" stroke-width=\"1\" fill=\"yellow\"></circle> </svg>`
`<svg xmlns="http://www.w3.org/2000/svg" width="100px" height="90px"><circle cx="50" cy="50" r="4" stroke="green" stroke-width="1" fill="yellow"></circle> </svg>`
);
});
test("add proper namespace to g tags", () => {
const template = `<g><circle cx="50" cy="50" r="4" stroke="green" stroke-width="1" fill="yellow"/> </g>`;
expect(renderToString(template)).toBe(
`<g><circle cx=\"50\" cy=\"50\" r=\"4\" stroke=\"green\" stroke-width=\"1\" fill=\"yellow\"></circle> </g>`
`<g xmlns="http://www.w3.org/2000/svg"><circle cx="50" cy="50" r="4" stroke="green" stroke-width="1" fill="yellow"></circle> </g>`
);
});
test("namespace to g tags not added if already in svg namespace", () => {
const template = `<svg><g/></svg>`;
expect(renderToString(template)).toBe(`<svg><g></g></svg>`);
expect(renderToString(template)).toBe(`<svg xmlns="http://www.w3.org/2000/svg"><g></g></svg>`);
});
test("namespace to svg tags added even if already in svg namespace", () => {
@@ -41,8 +41,13 @@ describe("properly support svg", () => {
test("svg namespace added to sub-blocks", () => {
const template = `<svg><path t-if="path"/></svg>`;
expect(renderToString(template, { path: false })).toBe(`<svg></svg>`);
expect(renderToString(template, { path: true })).toBe(`<svg><path></path></svg>`);
expect(renderToString(template, { path: false })).toBe(
`<svg xmlns="http://www.w3.org/2000/svg"></svg>`
);
// Because the path is its own block, it has its own xmlns attribute
expect(renderToString(template, { path: true })).toBe(
`<svg xmlns="http://www.w3.org/2000/svg"><path xmlns="http://www.w3.org/2000/svg"></path></svg>`
);
const bdom = renderToBdom(template, { path: true });
const fixture = makeTestFixture();

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