WICG / webcomponents

Web Components specifications
Other
4.36k stars 370 forks source link

Scoped Custom Element Registries #716

Open justinfagnani opened 6 years ago

justinfagnani commented 6 years ago

Since #488 is closed, I thought I'd open up a new issue to discuss a relatively specific proposal I have for Scoped Custom Element Registries.

Scoped Custom Element Definitions

Overview

Scoped Custom Element definitions is an oft-requested feature of Web Components. The global registry is a possible source of name collisions that may arise from coincidence, or from an app trying to define multiple versions of the same element, or from more advanced scenarios like registering mocks during tests, or a component explicitly replacing an element definition for its scope.

Since the key DOM creation APIs are global, scoping definitions is tricky because we'd need a mechanism to determine which scope to use. But if we offer scoped versions of these APIs the problem is tractable. This requires that DOM creation code is upgraded to use the new scoped APIs, something that hopefully could be done in template libraries and frameworks.

This proposal adds the ability to construct CustomElementRegistrys and chain them in order to inherit custom element definitions. It uses ShadowRoot as a scope for definitions. ShadowRoot can be associated with a CustomElementRegistry when created and gains element creation methods, like createElement. When new elements are created within a ShadowRoot, that ShadowRoot's registry is used to Custom Element upgrades.

API Changes

CustomElementRegistry

ShadowRoot

ShadowRoots are already the scoping boundary for DOM and CSS, so it's natural to be the scope for custom elements. ShadowRoot needs a CustomElementRegistry and the DOM creation APIs that current exist on document.

Element

New properties:

With a scope, DOM creation APIs like innerHTML and insertAdjacentHTML will use the element's scope's registry to construct new custom elements. Appending or inserting an existing element doesn't use the scope, nor does it change the scope of the appended element. Scopes are completely defined when an element is created.

Example

// x-foo.js is an existing custom element module that registers a class
// as 'x-foo' in the global registry.
import {XFoo} from './x-foo.js';

// Create a new registry that inherits from the global registry
const myRegistry = new CustomElementRegistry(window.customElements);

// Define a trivial subclass of XFoo so that we can register it ourselves
class MyFoo extends XFoo {}

// Register it as `my-foo` locally.
myRegistry.define('my-foo', MyFoo);

class MyElement extends HTMLElement {
  constructor() {
    super();
    // Use the local registry when creating the ShadowRoot
    this.attachShadow({mode: 'open', customElements: myRegistry});

    // Use the scoped element creation APIs to create elements:
    const myFoo = this.shadowRoot.createElement('my-foo');
    this.shadowRoot.appendChild(myFoo);

    // myFoo is now associated with the scope of `this.shadowRoot`, and registy
    // of `myRegistry`. When it creates new DOM, is uses `myRegistry`:
    myFoo.innerHTML = `<my-bar></my-bar>`;
  }
}

Open Issues

Questions

This section is not current. See the open issues list

/cc @domenic @rniwa @hayatoito @TakayoshiKochi

caridy commented 6 years ago

Questions:

Missing features

Recommendation

Based on those two possible missing features, and extensibility point of view, it is probably easier to find an API that delegates part of the resolution to user-land, and let users to implement the hierarchical/resolution algo. e.g.:

class MyFoo extends HTMLElement {}

// lookup must return a registry
function lookup(registry, name) {
    if (name === 'my-bar') {
        return customElements; // delegate the lookup to another known registry (in this case the global registry)
    }
    if (name === 'my-baz') {
        registry.define('my-baz', class extends HTMLElement {}); // define inline
    } else {
        // import `name` component, and define it in `register` when it is ready...
    }
    return registry;
}
const myRegistry = new CustomElementRegistry(lookup);
myRegistry.define('my-foo', MyFoo); // you can still prime the registry

This will require effectible a new constructor with a single argument, nothing else. Or could potentially be fold into ShadowRoot constructor as well.

Wish List

caridy commented 6 years ago

hey @justinfagnani, this is the comment that I've mentioned today, let's chat about this tomorrow, I can explain more.

trusktr commented 6 years ago

What happens in my-foo from the above example is removed then appended into another tree unrelated to the scope? Does it just continue to work? Or is an error thrown?

fully composable registry graph where the resolution of a name can be delegated to any registry where the logic can be customized in user-land.

This seems like it could be useful for some sort of framework, but would definitely be nice to have a default (that just looks in the parent scope) so that the end user can just do something perhaps as easy as

const myRegistry = new CustomElementRegistry()
myRegistry.define('my-foo', MyFoo);
this.root = this.attachShadow({mode: 'open', registry: myRegistry})

which causes lookup to look in the parent scope (parent shadow root) when the element name is not found in the current registry.

Just tossing in a syntax idea:

this.root = this.attachShadow({mode: 'open', registry: true})
this.root.define('my-foo', MyFoo);

or maybe just simply:

this.root = this.attachShadow({mode: 'open'})
this.root.define('my-foo', MyFoo); // creates a registry internally on first use

And for advanced use (f.e. defining lookup):

this.root = this.attachShadow({mode: 'open'})

console.log(this.root.registry) // null

this.root.define('my-foo', MyFoo); // creates a registry on first use

console.log(this.root.registry) // CustomElementsRegistry

// ... and for advanced users:
this.root.registry.defineLookup(function() { ... })

// also use the registry directly:
this.root.registry.define('other-foo', OtherFoo)

This way it's easier, yet still configurable for advanced cases.

trusktr commented 6 years ago

Oh! This is also a great opportunity to not require hyphens in element names of scoped registries! Maybe it's possible?

Jamesernator commented 6 years ago

@trusktr Although I really like the idea of hyphen-less names what would happen if you happen to upgrade an existing name?

e.g. What on earth would happen in this situation:

<link rel="stylesheet" src=".." />

<script>
    class MyLink extends HTMLElement {
        constructor() {
            // Would this still be a proper link element?

            // If so this clearly wouldn't work as HTMLLinkElement
            // doesn't support attachShadow 
            this.attachShadow({ mode: 'open' })
        }
    }

    window.customElements.define('link', MyLink)
</script>

Now I think this could actually be resolvable by having a special element that must be included in head (similar to <base>/<meta>) that declares all names that will be overridden so that the browser knows ahead of time not to assign any builtin behavior to those elements.

For example it might look something like this:

<head>
    <override element="link">
    <override element="input">
    <!-- Or maybe <override elements="link input">
</head>
<body>
    <!-- link no longer works as a link tag but is just a plain html tag -->
    <link rel="stylesheet" />

    <!-- Neither does input -->
    <input type="date">

    <script>
        ...
        customElements.define('input', MyCustomInput)
    </script>
</body> 

Of course this doesn't explain what'd happen if override itself is overriden (not allowed? namespaces (<html:override element="link">)?) or any other tag like meta. Perhaps metadata tags would need to be strictly reserved by html (which would prevent future metadata tags being added but maybe the existing metadata tags (particularly <meta>) are already sufficiently flexible for all such purposes?).

I think it's simpler to keep this and #658 separate given that I don't think it's worth blocking scoped registries on a topic that I personally think is much more complicated than scoped registries.

trusktr commented 6 years ago

What on earth would happen in this situation:

Just like with variable shadowing in practically any programming language, then in that case that <link> is no longer the sort of <link> from the outer scope, and it will not pull in the stylesheet, unless the Custom Element implements that.

const foo = "foo"

~function() {
  const foo = "bar"

  console.log(foo)
  // is "foo" here the same "foo" as outside? Nope, not any more, we're in a new scope!
}()

Same thing for elements! If you override a "variable" (in this case an element name) in the inner scope, then it is no longer what it was in the outer scope.

<override element="input">

But, that's in global scope. Overriding should only be possible in non-global scope. Maybe, <override element="XXX"> is something that could work, as it can signal the parser not to do certain things if xxx is tr, for example.

But then again, I don't like redundancy, I like things DRY.

Imagine if this was required in JavaScript:

const foo = "foo"

~function() {
  override foo;
  const foo = "bar"
  console.log(foo)
}()

I would not prefer a similar thing for HTML name scope. But, what if an HTML/CSS no-JS person looks at the markup? They might get confused? True! I would probably not want to do that, just like I don't override globals in JS. What it would really be useful for is, for example, coming up with new element names that don't already exist (like <node3d> or <magic>), and then if the browser by chance introduces one of those names, oh well, then the component will just work, and everyone can be happy. If a component wasn't using a yet-to-exist <magic> element before, but rather a custom element called <magic>, then, who cares if the browser introduces a new <magic> element later, as long as that component continues to work. Some other component can decide to use the builtin <magic> element by not overriding it.

I find myself in situation where I'm forced to think of another word to add to a single-word component, just to appease the hyphen rule. Sometimes I do something dumb like <stu-pid> just to get around the limitation and keep the single <wo-rd> element, which is awkward.

So my specific argument isn't leaning towards overriding certain builtins, though I can imagine that if someone wanted to implement a "super <link>" that worked the same, plus did much more, while making it easy to adopt by simple override, then why not?

Personally, I just want to use single words when I want to.

trusktr commented 6 years ago

I don't think it's worth blocking scoped registries on a topic that I personally think is much more complicated than scoped registries.

Good point. That'd be great regardless of hyphen-or-not!

TakayoshiKochi commented 6 years ago

Scopes are completely defined when an element is created.

This sounds the most important principle in the proposal, to understand the behaviors. It's a new ownerDocument, so to say.

comments

tomalec commented 6 years ago

I'd like to ask, what is the desired approach of providing definitions of scoped custom elements? In the example above I can see it's done imperatively by someone who attaches the shadow root. That is not necessarily the same person or entity who created the shadow tree.

I have a number of use cases where shadow root is created, therefore scoped custom elements registry could be used, not for custom elements. Even for custom elements, it does not have to be exactly the same for every instance. In those cases, shadow dom is created by a separate entity and just employed by the host.

I'd like to ask about a more declarative approach and defining elements closer to the markup that uses them, like:

<template is="declarative-shadow-root"> to be stamped in different places.
  <link rel="import" href="/path/to/my-element/definition.html">
  or
  <script src="/path/to/my-element/definition.js"></script>
  or
  <script type="module" src="/path/to/my-element/definition.html"></script>
  or
  <script type="module">
    import {MyElement} from '/path/to/my-element/definition.js';
    import.meta.scriptElement.getRootNode().customElements.define('my-element',MyElement);
  </script>

   <p>Shadow dom that's encapsulated, independent, and works exactly the same anywhere it's attached</p>
   <my-element>scoped custom element, working in a scoped tree</my-element>  
</template>

The person who creates the markup for shadow dom is the one who knows best what elements need to be used.

I believe, above approach would be intuitive, and should play well with declarative Shadow DOM.

For the document tree, you can provide custom elements and scripts that work in its scope. I don't have to provide them by the entity who stamps the document - like browser or HTTP. It would be useful to be able to provide element definitions from within the shadow tree scope, that would be scoped to this tree and do not pollute the document.

However, given the HTML Imports are dead, classic <script>s have no access to currentScript, currentRoot, the only chance to achieve that is to give HTML Modules an access to current root https://github.com/w3c/webcomponents/issues/645, https://github.com/whatwg/html/issues/1013

justinfagnani commented 6 years ago

@tomalec one of the use cases we're trying to address is a large application that may not be able to guarantee that each tag name is used only once, whether because there are version conflicts, or because portions of the app are built and distributed separately. We see this with decentralized teams, or with applications with plug-in systems like IDEs.

The pattern that would need to develop is that elements would be distributed without self-registering:

export class MyElement extends HTMLElement {}
// no customElements.define() call

The user of the element imports and defines the element in the registry it's using:

import {MyElement} from './my-element.js';
const localRegistry = new CustomElementRegistry();
localRegistry.define('my-element', class extends MyElement {});

class MyContainer extends HTMLElement {
  constructor() {
    this.attachShadow({mode: 'open', customElements: localRegistry});
  }
}

This scopes the definition so it doesn't conflict with any other registration is the entire page.

I prefer the imperative API as a start because it's an incremental change from current patterns and doesn't tie this proposal with with another. Tying the scope to the ShadowRoot is mainly because ShadowRoot is the one scoping mechanism we have in the DOM, and it makes sense that a scope will work for a number of things like CSS, element definitions, and DOM.

If there's a situation where the shadow root creator and the registry owner are different, I suspect there will usually be a way to route the registry to or from the ShadowRoot creator to be able to get the registry to the right place.

For any declarative feature we do have a problem of referencing values in JS. The current solution is exactly CustomElementRegistry: a global keyed object that's specced to be used as a lookup from a DOM value. In general I don't think we've identified a slam-dunk pattern for referencing non-global objects from markup. This came up in the Template Instantiation discussion too, for choosing template processors from markup. Once we solve that we should be able to tell a declarative shadow root which registry to use. Speculatively (and probably a poor choice of syntax, tbh) it could be something like this:

<template is="declarative-shadow-root" registry="registry from ./registry.js">
  ...
</template>

Where registry from ./registry.js is like a JS import.

I think this is a separable concern though

justinfagnani commented 6 years ago

I think a common pattern that might emerge is sharing a registry across a whole package rather than per-module. Since in npm generally a package can only resolve a dependency to a single version, it'll be relatively safe to have a package-wide registry that handles the element subclassing automatically and is tolerant of re-registrations:

registry.js

export class AutoScopingCustomElementRegistry extends CustomElementRegistry {
  constructor() {
    this.bases = new Map();
  }

  define(name, constructor, options) {
    if (this.bases.has(tagname)) {
      const base = defined.get(tagname);
      if (base !== constructor) {
        throw new Error('Tried to redefine a tagname with a different class');
      }
      return; // already defined
    }
    super.define(name, class extends constructor {}, options);
  }
}
export const registry = new AutoScopingCustomElementRegistry();

Now one module can define the element without making a trivial subclass:

container-a.js

import {registry} from './registry.js';
import {ChildElement) from './child-element.js';
registry.define('child-element', ChildElement);

And another module too, but it's safe and shares the definition:

container-b.js

import {registry} from './registry.js';
import {ChildElement) from './child-element.js';
registry.define('child-element', ChildElement);

It's possible this is useful enough that it should make it into the proposal.

caridy commented 6 years ago

Not all APIs can be high-level, just like not all APIs can be low-level, but no API should be mid-level :). I truly believe that scope registry should be a low-level API, imperative, following the principles of EWM. It should be something that libraries, transpilers and framework authors can rely on. Most likely tools that can do the static analysis to either bundle things together, or create the corresponding registries. I don't think we should create an API for this and expect that citizen developers will use it on the daily basics.

justinfagnani commented 6 years ago

@caridy I don't think this proposal is at different of a level than the current CustomElementRegistry, and I don't think it would be only for tools. In fact a major reason for proposing this is to get closer to the scoping and workflow that pure-JS component solution enjoy.

Consider the following React-ish example:

import {ChildComponent} from './child-component.js';

export class ParentComponent extends Component {
  render() {
    return <ChildComponent>Hello</ChildComponent>;
  }
}

This has no problem with several components being named ChildComponent, supports renaming, and multiple versions in the same program.

I think we can get very close to this with custom elements (this example using LitElement for conciseness, it just creates a shadow root automatically):

import {ChildElement} from './child-element.js';
import {registry} from './registry.js';
registry.define('child-element', ChildElement);

export class ParentElement extends LitElement {
  render() {
    return html`<child-element>Hello</child-element>;
  }
}

This has no problem with several components being named child-element, supports renaming, and multiple versions in the same program, with only a slightly addition in LoC for making sure the element is registered. I see this as very hand-writable.

caridy commented 6 years ago

In the example above (using LitElement), how does the ParentElement connects to the register implemented in ./registry.js? Is this the global registry or a registry that is somehow connected to a container element's shadow?

justinfagnani commented 6 years ago

In this example I'm showing the shared registry per package pattern I described above. I did forget to give the element the registry though.

We need to add:

export class ParentElement extends LitElement {
  static get registry { return registry; }
}

or:

ParentElement.registry = registry;

And have LitElement use that in it's attachShadow() call.

trusktr commented 6 years ago

And then it'd be possible for SkateJS, StencilJS, PolymerJS, etc, to abstract away the boilerplate. :)

caridy commented 6 years ago

@justinfagnani the point I was trying to make is that providing a very low level API for the registry allows to implement something like what you have described, and many other cases (like those that we have discussed in our meeting last week), library authors will create abstractions on top of that like the one you just described in Lit, and I believe that will be the primary way devs will consume this API, via abstraction.

In your example above, you're adding the sugar layer via a) the import for the local registry and b) the static registry reference. And that is totally fine! What is not fine is to force framework, tool and library authors to have to do gymnastics to accomplish some scoping mechanism, and that's why I'm favoring a very low level API here.

matthewp commented 6 years ago

As far as I can tell, no one has yet explained how this will work:

class MyElement extends HTMLElement {}

customRegistry.define('my-element', MyElement);

new MyElement();

Does this?

If the answer is the latter, meaning it is allowed, what happens when you then do:

class MyElement extends HTMLElement {}

customRegistry.define('my-element', MyElement);

let el = new MyElement();
document.body.appendChild(el);

Note that this is appending to the document body, which is not part of the customRegistry. What happens at this point? Is this treated as an HTMLUnknownElement?

caridy commented 6 years ago

@matthewp those are very good questions that need concrete answers.

The second example could be simplified to just asking what happen when you insert an already upgraded element into a different shadow or global? IMO, since the shadow dom is not really a security mechanism, it will work just fine. Meaning that the scoped registry is about facilitating the upgrading process rather than a security boundary.

Update: Thinking more about this, I believe the registry (custom or not) is just a mechanism to determine how to upgrade the elements, and not about where the element is used or not.

justinfagnani commented 6 years ago

@matthewp While this proposal removes the 1-1 relationship between a tagname and a constructor, it preserves a 1-1 relationship between a constructor and a registration, so for any given constructor call we know what tagname to create, and what registry to associate with the instance. This doesn't require putting constructors into a global set.

In other words:

class MyElement extends HTMLElement {}
customRegistry.define('my-element', MyElement);
const el = new MyElement();

would just work. And further:

el.innerHTML = '<my-element></my-element>';

would also create a MyElement instance.

For the second question: once upgraded, an element is never downgraded or re-upgraded. Creating an element in one scope and moving it to another should neither change it's prototype, nor the scope associated with the element.

This could conceivably lead to some weird situations where after moving elements around, two elements in the same container produce different results (different prototypes) when setting their innerHTML to the same text. I think this is a very edge case, so it'll be really rare (how often are elements initially appended to ShadowRoot, then moved outside that root?) and at least this behavior is consistent.

justinfagnani commented 6 years ago

Summary of the discussion in Tokyo:

Registry Inheritance & Scope Lookup

There were some suggestions (with possibly mild agreement?) to make registry inheritance and scope lookup dynamic based on tree location. =

That is, the CustomElementRegistry constructor would no longer take a parent argument, but look up a parent via the tree. This ensures that the structure of the registry tree agrees with the structure of the DOM tree.

Likewise, looking up the registry to use for element-creation operations like innerHTML= would be done via the tree, so that an element doesn't need to remember it's scope.

The performance concerns I had seem to not be a concern for implementers, who say they can optimize this.

Constructors & Registrations

There were few questions about how constructors would they behave. Would they only work if registered in the global registry? Could a constructor be registered with multiple registries, or would it requires trivial subclasses be registered in each? There was a desire to match iframe behavior, since it defines another registry scope already, so match what happens if you register a constructor in a frame then send the constructor to another frame.

Some discussion also about how this relates to being able to lookup a tagname by constructor. If you allow a constructor to be registered multiple times, it doesn't have a single tag name. The v0 registerElement() API actually returned the class the browser created, maybe there's something similar as in the AutoScopingCustomElementRegistry example above.

Element Creation APIs

There was a suggestion to put scoped element creation APIs on CustomElementRegistry, not ShadowRoot.

Lazy Registration

This was talked about briefly for the use case of supporting a potentially very, very large number of tag names, by being notified the first time a tag name is used allowing the registry an opportunity to fetch the definition. This feature seems separable from scopes.

diervo commented 6 years ago

For solving the lazy registration problem, after talking to @rniwa there might be some appetite to expose a low level API to observe when a unknown-element its being inserted. I will file a separate issue for that.

snuggs commented 6 years ago

And further: el.innerHTML = '<my-element></my-element>'; @justinfagnani

If el.outerHTML = '<my-element></my-element>; Would not el.innerHTML = '<my-element></my-element>'; thus create

<my-element>
  <my-element></my-element>
</my-element>

?

Or were those merely adjacent thoughts?

Jamesernator commented 6 years ago

If trivial subclassing is necessary for scoped registries to work that would be fine in my opinion.

But if this path is taken I think it would preferable for all registries except the global one to perform this trivial subclassing automatically (by default at least) so that developers don't accidentally write components that explode when put in a page together.

lacolaco commented 6 years ago

I think scoped root EventTarget also will be needed. Separated elements can only communicate each other via its outer event bus, window. Events are identified by its name as well as elements. So, as the same idea, I guess something like EventTargetRegistry will be important.

hayatoito commented 6 years ago

@lacolaco Could you kindly give us an example how scoped root EventTarget works? Pseudo-code snippet might be helpful to understand the basic idea.

I think I can understand what problem you are trying to solve, but it is unclear to me how EventTargetRegistry works.

lacolaco commented 6 years ago

@hayatoito Just an idea, for example, I think CustomEelementRegistry can be an EventTarget.

const xRegistry = new CustomElementRegistry();

class XFoo extends HTMLElement {
  constructor() {
    super();
    this.addEventListener('click', () => {
      // dispatch a scoped event
      xRegistry.dispatchEvent(new CustomEvent('xEvent'))
    });
  }
}
class XBar extends HTMLElement {
  constructor() {
    super();
    // subscribe scoped events
    xRegistry.addEventListener('xEvent', () => {
      // ...
    });
  }
}

xRegistry.define('x-foo', XFoo);
xRegistry.define('x-bar', XBar);

image

hayatoito commented 6 years ago

Thanks. Yup, I think letting CustomElementRegistry (or something which is not in a node tree) inherit EventTarget would be good enough. We wouldn't need an EventTargetRegistry.

lacolaco commented 6 years ago

I agree. I think so, too. EventTargetRegistry is my initial thought but it was difficult to imagine the detail.

hayatoito commented 6 years ago

Thanks. Just in case, EventTarget is now constructible. Users can create their own EventTarget and use it for any purpose.

lacolaco commented 6 years ago

Wow, I didn't know that! Thank you for the information!

justinfagnani commented 6 years ago

@lacolaco I don't quite understand the need here, at least as it related to custom elements. Why would you want to dispatch an event on the registry? Most elements will not know the registry they are registered against, only the registry they define their dependencies in.

I think you may see a similar problem with even names as tag names - that because they're not namespaced, there can be collisions. But this is separate from custom elements - any two uncoordinated pieces of code may fire unrelated events that happen to have the same name.

lacolaco commented 6 years ago

@justinfagnani IMHO, A set of custom elements created as a micro application may need its own closed event system because event names can conflict as you said. And I think that system's scope is the same to its registry level.

Most elements will not know the registry they are registered against, only the registry they define their dependencies in.

For example, if elements have this.registry field which allows the element to access its own registry, it may be worth more. Each element doesn't know other elements and they are created in independent js modules without including xRegistry reference as a closure, but they can fire closed events without name collision.

bicknellr commented 6 years ago

Or, we could allow symbols to be used as event types and not change anything with events here. :)

namannehra commented 5 years ago

Has there been any updates on this?

rniwa commented 5 years ago

I've added this as a potential topic for the F2F meeting at TPAC.

annevk commented 5 years ago

F2F update: situation hasn't changed. Google will work an update, but hasn't gotten around to it.

marcoscaceres commented 5 years ago

Can we formally assign someone?

justinfagnani commented 5 years ago

I haven't had time to work on a concrete proposal, and I probably won't until January at the earliest. We're in the midst of planning at Google that might free up someone. @hayatoito might have some insight there.

I don't think there are that many more open questions after the Tokyo meeting. We just need to write it all down in one place. The polyfill could probably be updated very easily too.

adrianhelvik commented 5 years ago

I have thought some about this. If we want to be able to override elements without a hyphen, two things stand out to me:

So I propose two APIs (that work together) to do this.

In an option when creating a shadow root

This will allow for optimizations, be pleasant to use and ensure that builtin elements are never rendered before elements are upgraded. I'm not against having this be the only way to override builtin elements.

(This part of the proposal could be added as a follow-up proposal.)

const shadow = element.attachShadow({
  mode: 'open',
  customElements: {
    'ul': MyUl,
    'li': MyLi,
    'my-element': MyElement
  }
})

ShadowRoot instances should each have a customElements registry

We can use ShadowRoot#customElements in the exact same way as window.customElements.

shadow.customElements.define(
  'another-element',
  class extends HTMLElement { ... }
)

Registries should not bleed through slots and shadow roots

It would be very confusing to have <ul></ul> not be the builtin element unless explicitly specified. It could also affect the performance of deeply nested shadow roots.

adrianhelvik commented 5 years ago

A nice addon proposal for perf and for property/attribute heuristics would be CustomElementRegistry.prototype.createElement.

stramel commented 5 years ago

Perhaps this would better fit a different discussion but it would be nice to be able to use the Class name as the tag name.

class MyElement extends HTMLElement {}
customElements.define(MyElement) // equivalent to `customElements.define('my-element', MyElement)`

this would be nice to fit into the above example like so:

const shadow = element.attachShadow({
  mode: 'open',
  customElements: {
    'ul': MyUl,
    'li': MyLi,
    MyElement
  }
})
namannehra commented 5 years ago

Any update on this or any other solutions that would prevent conflicts in names of custom elements?

rniwa commented 5 years ago

Someone has to design an API, write a spec PR, and tests.

justinfagnani commented 5 years ago

A little update here: Since the Toronto web components face-to-face, @bicknellr has been taking some of the feedback from this issue and lazy definitions and experimenting with adding APIs to the webcomponentsjs custom elements polyfill. This is highlighting a number of choices we'll have to make, and we'll be able to come back with a much more concrete proposal for them both very soon I think.

From that, neither @bicknellr or I have experience writing spec PRs, but would be willing to try or find someone who can.

rniwa commented 5 years ago

For the purpose of making a progress faster on this issue, it would be ideal if you split the work for lazy definitions & custom element registries when it comes to making a proposal or a spec PR, not that you can't think about both issues at once while you're working on it.

askbeka commented 5 years ago

any progress?

jarrodek commented 4 years ago

I'd like to join the discussion with additional use case for scoping but in a different context. I am not sure if that is actually related to this but please, let me know if that would require a new feature request.

I have a problem with very complex SPA applications and custom elements. In my organization we (so far) have a one application that is completely build with WC and the rest is React.

In the platform we have several different applications developed by different teams. The applications work under single SPA. The shell app just requires new sources to be downloaded when switching between apps. There is no actual page reload.

This one WC based application is used in multiple other applications (4 so far). If we would like to incorporate the components into the build process of each application this would inevitably lead to name collision and component registration errors when another application sources are requested. Because of that currently we are bundling this single WC based application into own package and it is included by a script from our CDN. Because all apps uses the same script (from the same URL) the import occurs only once. So far it works fine. But then if we would like to introduce a new application that re-use some of the components used in the first application that would lead to name collision again. We would have to come up with a very clever build system that can work across multiple applications and scripts that imports WC bundles depending on current context without causing names collisions. I am not sure if we would be able to do this to be honest. Alternative would be not to bundle WC at all and host separate components on CDN. However, even after minification, this would take ages to download the application (the WC based app I mentioned before has over 120 components in the dependencies tree). More applications like that just add to that. What I was thinking is a way to somehow scope web components bundle so there are no registry collisions. However doing this on the component level would defeat the purpose because the scope is defined at the moment of bundling specific application. Do you guys have similar use case already? Do you think we could make it easier for complex systems to work with WC?

markcellus commented 4 years ago

Yeah, we had a similar setup at my previous company. To get around this, we prefixed each custom element name with an identifier that is scoped to the app or package. In other words, we just created our own custom namespace pattern. But doing so takes a great deal of cooperation and coordination, which can get messy 😬

frank-dspeed commented 4 years ago

to have a easy implamentation of this we would need

document.createElement('p',class extends ParagraphHTMLElement {})
document.createElement('my-element',class extends HTMLElement {})

note that we don't need to supply extends since we don't hornor the is attribute when we create the element our self its not the ui thats upgrading the element .

Alternativ we could expose upgrade api.

customElements.upgrade(el,class extends ParagraphHTMLElement {})