dart-lang / sdk

The Dart SDK, including the VM, JS and Wasm compilers, analysis, core libraries, and more.
https://dart.dev
BSD 3-Clause "New" or "Revised" License
10.21k stars 1.57k forks source link

Make dart class extend JS classes when implementing a JS class #48261

Open jodinathan opened 2 years ago

jodinathan commented 2 years ago

Today it seems to not be trivial to use webcomponents and Dart. And the reason is that a Dart class can't extend a JS class/HTMLElement.

I think that not extend a JS class is ok, however, to be able to use a Dart class as a WebComponent we could make that the resulting JS class actually extend the desired Element/class when implementing.

Example:

the js-interop file

@JS()
@staticInterop
class HTMLElement {}

extension ExtHTMLElement on HTMLElement {
  ShadowRoot attachShadow(ShadowRootInit init) =>
      js_util.callMethod(this, 'attachShadow', [init]);
}

the dart class

class Foo implements HTMLElement {
  Foo() {
    final pElem = document.createElement('p');
    final shadowRoot = attachShadow(ShadowRootInit(mode: 'open'));

    shadowRoot.appendChild(pElem);
  }
}

now as Foo implements a JS interoped class, the resulting js could be:

class Foo extends HTMLElement {
    constructor() {
        super();

       final pElem = document.createElement('p');
       final shadowRoot = attachShadow({mode: 'open'});

       shadowRoot.appendChild(pElem);
    }
}

With this we still make sure that a Dart class doesn't mix up with JS classes directly, but still allow it to be used as a webcomponent

Tusharkhati commented 2 years ago

Hello. I'm interested in contributing to the Dart community. I'm a beginner at dart language since I have already made some Android/ iOS applications in flutter using dart language. I know how we can use APIssince I have made my mini project on it. I'm a quick learner and It will be really helpful to me if you can guide me on this, I've already cloned the project on my machine but I'm a little confused there are so many different files. Thanks.