Skip to content

Error On Any Inheritance #1060

Closed
Closed

Description

@lupiter

Stencil version:

I'm submitting a:

[X] bug report

The change in 0.12 to introduce a compiler error when a Stencil component inherits from any class is causing us a lot of problems. Most of our components inherit from non-Stencil base classes that define common properties (not @props) and methods.

While I can understand that supporting inheritance between components is hard, blocking all inheritance seems like a poor solution. Can the error be changed to stop you inheriting only from other classes that are also annotated with @component and leave open the option of inheriting from non-component classes? At the very least can we get some kind of flag or option to disable this check? As it stands we can't move to 0.12.

Activity

  1. jthoms1 commented on Sep 6, 2018

    @jthoms1
    Contributor

    Currently we do not allow for any inheritance of Stencil Components. We have talked about possibly allowing for mixins in the future. But this will need to be outlined in our future roadmap.

    I am tagging this as a feature request. Thanks!

  2. kael commented on Sep 6, 2018

    @kael

    The lack of inheritance is a bit problematic from a productivity point of view.

    Copying and pasting the same set of code, for example for click events, to different components, and then readjusting when necessary is time consuming, and then you have to keep track of changes and modify all components after one modification.

    But well, there seems to be strong reasons against it.

    Perhaps there could be more patterns examples for composition (until with get some cool stuff) ?

  3. lupiter commented on Sep 6, 2018

    @lupiter
    Author

    I'm not sure this is a feature request? Maybe I didn't explain what I meant properly. I understand that the following doesn't work:

    @Component(...)
    class Animal {}
    
    @Component(...)
    class Dog extends Animal {}
    

    but we have

    class Animal {}
    
    @Component(...)
    class Dog extends Animal {}
    

    Our base class then handles our generic service interactions (in our case with the redux store).

    This did work prior to 0.12, when the compiler error was introduced.

  4. self-assigned this
    on Sep 10, 2018
  5. jthoms1 commented on Sep 10, 2018

    @jthoms1
    Contributor

    @lupiter I think your use case is valid and we should allow for it.

  6. jthoms1 commented on Sep 13, 2018

    @jthoms1
    Contributor

    @lupiter could you provide the base class that you wanted to extend. We are trying to identify solutions to the problem. I just want to have better insight. Thank you!

  7. lupiter commented on Sep 13, 2018

    @lupiter
    Author

    @jthoms1

    Here you go. It should remind you of stencil-redux but because we don't have a root component (we're making a component collection) we setup the redux store with a special <sw-store> component. getSubscription is related to configuring a redux middleware.

    import { ActionType, AppState, Store, StoreStates, Subscription } from 'global/state';
    import { extractFromGlobal } from 'global/store';
    
    export abstract class SWComponent {
      public abstract store: Store;
      public abstract storeManager: any;
      public abstract applyState(state: AppState): object;
      public abstract storeState: StoreStates;
      protected subscriptionId: string;
    
      public linkStore(): void {
        if (!this.store) {
          this.store = extractFromGlobal();
        }
        this.store.mapStateToProps(this, (state: AppState) => this.applyState(state));
        if (!this.subscriptionId) {
          this.subscriptionId = this.store.getId();
        }
        this.store.dispatch({ type: ActionType.UPSERT, payload: [this.getSubscription()] });
        this.store.mapDispatchToProps(this, this.getSavingProperties());
      }
    
      protected getSavingProperties(): object {
        return {};
      }
    
      protected getSubscription(): Subscription {
        return new Subscription(this.subscriptionId, []);
      }
    
      public willLoad(): void {
        if (this.storeManager && this.storeManager.componentOnReady) {
          this.storeManager
            .componentOnReady()
            .then(() => {
              this.linkStore();
            })
            .catch((reason: string) => {
              console.error(reason);
              if (window.name !== 'nodejs') {
                throw new Error('Couldn\'t find a <sw-store> element, May be misconfigured.');
              }
              this.linkStore();
            });
        } else if (window.name !== 'nodejs') {
          throw new Error('Couldn\'t find a <sw-store> element, May be misconfigured.');
        }
      }
    }
  8. dgibson666 commented on Oct 2, 2018

    @dgibson666

    I've just updated to .13* and it's broken what was previous working in a basic extends case. Not doing anything fancy - just trying to provide a handful of utility methods in a parent class so I'm not repeating code and creating a maintenance nightmare. Please allow this once again. Thanks.

  9. safebyte commented on Oct 3, 2018

    @safebyte

    @lupiter I think your use case is valid and we should allow for it.

    I do not understand why inheriting from an imported class is considered valid, but the inheritance of a component isn't. IMHO this should be exactly the other way around. Handling dependencies on a component basis seems to be much more convenient than including / shipping global dependencies from external files.

    Although there had been plenty of feature requests for component inheritance, there hasn't been a clear statement. The most promissing issue has been closed due to inactivity while waiting for an answer from @jthoms1 , others just refer to the closed one.

    The ability to inherit from a component is a key feature to me and it seems like others base their decision of working with stenciljs on this aswell. Will stenciljs ever support inheritance of components? If so, does a roadmap exist?

    My use case is a "window" component that comes in different variations: <win-alert/>, <win-confirm/>, <win-prompt/>... they all have to inherit the base functionality from <win-base/> which comes with the window container, a title bar, close / minimize / maximize buttons and some global APIs for handling events, a taskbar etc.

    Thanks.

  10. peterpeterparker commented on Oct 31, 2018

    @peterpeterparker
    Contributor

    @jthoms1 are you still looking for practical examples where inheritance would be a good solution/welcomed?

    if so, I could provide one soonish, I'm duplicating code in 3-4 components of the same project right now and I miss having the ability of having an abstract class ;)

  11. 15 remaining items

  12. FRSgit commented on Apr 25, 2019

    @FRSgit

    Okay, the only @peterpeterparker ah, sorry, didn't saw that on readme page, my bad.
    @manucorporat That's a pity, but understandable. Are there any plans on supporting extending native elements though? Im' talking about components defined like here.

    Supporting this approach would give a possibility to write better (semantic-wise) html code, so as a result also a real boost for all SEO-connected usecases.

  13. menosprezzi commented on Aug 17, 2019

    @menosprezzi

    Hi Guys!
    I'm was working on a large scale internal Design System and developed a pattern for creating components that extend functionality. It is based on Polymer's behavior mixin pattern, but it's cleaner.

    Suggestions please!

    https://gist.github.com/menosprezzi/9d4de98960d343a4283e268073402b6c

    In this example we have a layout component that controls a navdrawer that closes if focus change.

    I'll revise this pattern and write an Medium article soon as possible explaining the concept

    thanks!

  14. Danetag commented on Oct 16, 2019

    @Danetag

    @manucorporat Hi! Do you have more information about how to share code between Stencil components? Thanks!

  15. supproduction commented on Oct 29, 2019

    @supproduction

    I found workaround to share code between Stencil components. But in any case it inconvenient.
    You can use use decorator from typescript-mix library and also duplicate all props and state to the new component.

    import { use } from 'typescript-mix';
    import { Component, Prop, State } from '@stencil/core';
    import { ComponentToOverride } from '../path';
    
    export interface OverrideComponent extends ComponentToOverride {}
     
    @Component({
        tag: 'override-component',
        styleUrl: 'style.scss',
        shadow: true,
    })
    export class OverrideComponent {
        @use(ComponentToOverride) this: ComponentToOverride;
    
        @State() stateValue: string;
    
        @Prop() name: string;
    }
    

    And also you should avoid arrow functions in the component

  16. META-DREAMER commented on Nov 28, 2019

    @META-DREAMER

    @manucorporat
    Any update yet on how to achieve code sharing between components? This is a huge non-starter for our team, and IMO an essential feature for something like Stencil aiming to be the best way to build design systems. Simply not scalable without it.

    @adamdbradley You mentioned using utility functions in this issue, is there any examples or docs on how this can be accomplished? #936

  17. dgesteves commented on Jan 21, 2020

    @dgesteves

    I have a question regarding this subject.
    I want that all my library components have a theme property or for example RTL support or something that will be present in all components.
    How can i use inheritance like class CarCompoent extends VehicleComponent?
    I sow @jthoms1 saying that we should use composition but how can i do that?
    using a component and then a to be able to put other components inside?
    But in this case i can't style the slot deeply.

    Can someone help me with this issue?

  18. chiqui3d commented on Jan 25, 2020

    @chiqui3d

    So what's the solution for reusable code if we can't use inheritance?

  19. chiqui3d commented on Jan 25, 2020

    @chiqui3d

    Just because Adam Abramov doesn't like the inheritance, doesn't mean we all have to follow the same pattern, if in the end we're going to follow the same React pattern, can you tell me what I want to use Stencil for? --> Nextj.js

  20. META-DREAMER commented on Feb 4, 2020

    @META-DREAMER

    Composition alone isn't enough when you want to be able to share / pass through a common set of props without having to duplicate those props for every single component. I use composition to build my design systems with styled-system, its definitely the way to go, but its not feasible if I have to repeat the same set of 20-30 common styling props on every component (color, margin, padding, etc)

  21. OddDev commented on Oct 26, 2020

    @OddDev

    Would be cool to have inheritance implemented. I have a certain use-case where the code would be so much cleaner and easier to maintain.

  22. FirstVertex commented on Feb 14, 2023

    @FirstVertex

    Some have asked how to implement the composition solution that was mentioned. Here is what I have done.

    Consider a set of date-picking controls. One is DatePicker and a similar one is DayOfYearPicker, and we have DateRangePicker. They have similar needs from a UI standpoint, much can be shared as far as presenting a date, opening a dropdown, navigating a calendar, representing selection, etc.

    I made a contract which the Stencil Date Components must fulfill:

    export interface IDateComponent<TValue> {
        value?: TValue;
        valueChange?: EventEmitter<TValue>;
    }
    

    Now I made this Stencil component for the DatePicker, it implements this IDateComponent interface. I wrote the date component entire logic here. And then I transferred it to a separate class which is not a Stencil component. I left only the Stencil decorators and lifecycle hooks in the Stencil component. Everything else I call into this new "base class". In Stencil component ctor I instantiate base class. So I called it "base class" this is just a name. It is not inherited but it treats it the same way you would "super". This is what we mean by "composition", the base is just a class composed with the component.

    @Component({
        tag: 'ace-date-picker',
        shadow: true
    })
    export class AceDatePicker implements IDateComponent {
        @Prop({ mutable: true }) value?: IAceDate;
        private _base: DateComponent;
    
        constructor() {
            this._base = new DateComponent(this);
        }
    
        componentWillLoad() {
            this._base.componentWillLoad();
        }
    
        componentDidLoad() {
            this._base.componentDidLoad();
        }
    
        componentWillRender() {
            this._base.componentWillRender();
        }
    
        render() {
            return this._base.render();
        }
    }
    

    You see this is just a flyweight wrapper now, a facade around the real class, where I do not have Stencil's inheritance limitations.

    DateComponent, now is just what used to be in the AceDateComponent. But from there once again I moved all of that logic to a DateComponentBase, an abstract class. This is where all of the display logic ended up. Just put it in a new .tsx file, you can import anything you want here and e.g. render jsx markup, it's not going to bother inheritance.

    abstract class DateComponentBase<TValue = IAceDate> {
        constructor(public component: IDateComponent<TValue>) { }
    
        componentWillLoad() { }
    
        componentDidLoad() { }
    
        componentWillRender() { }
    
        render() { }
    }
    

    Now in my base component I can touch the Stencil component using the injected this.component. It has a contract that I can use to get the value, or emit an event, or e.g. touch a prop decorated with @State to force a rerender.

    protected _setValue(date: TValue) {
        this.component.value = date;
        this.component.valueChange.emit(date);
    }
    

    Just write "this.component" instead of "this."

    And I have a few classes who extend that. These are the ones the components are composed with:

    export class DateComponent extends DateComponentBase<IAceDate> {
    }
    
    export class DayOfYearComponent extends DateComponentBase<IAceDayOfYear> {
    }
    
    export class DateRangeComponent extends DateComponentBase<IAceDateRange> {
    }
    

    Now I make regular Stencil component for AceDayOfYearPicker and AceDateRangePicker. They have a duplicate of the wrapper above I made for AceDatePicker. This is where we're forced to duplicate some code, but that has been minimized to only the props, and lifecycle hooks, anything that needs a Stencil decorator, needs a stub here, which will always be 1 line that calls into the composed "base" class. The only difference is which base do they new in their ctor. AceDayOfYearPicker is composed with a "base" of DayOfYearComponent, and AceDateRangePicker is composed with DateRangeComponent, and these bases inherit from the abstract DateComponentBase.

    Hope this can help. ✌️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions