microsoft-graph-toolkit icon indicating copy to clipboard operation
microsoft-graph-toolkit copied to clipboard

[BUG] Multiple Web Parts with Sharepoint Provider in the same page error

Open RagasaSP opened this issue 6 years ago • 47 comments

Describe the bug If I add 2 or more web parts with mgt on the same page, the first web part is loaded correctly but the second and so on get an error: "Failed to execute 'define' on 'CustomElementRegistry': the name "mgt-person" has already been used with this registry".

Already tried: gulp clean delete node_modules and then npm i import {Providers, SharePointProvider} from '@microsoft/mgt/dist/commonjs';

To Reproduce Add 2 web parts in the same page with mgt and both with: import {Providers, SharePointProvider} from '@microsoft/mgt'; onInit() protected async onInit(){ Providers.globalProvider = new SharePointProvider(this.context); }

render() public render(): void { this.domElement.innerHTML = ' <mgt-agenda group-by-day days="7"></mgt-agenda> '; }

Screenshots image

Environment (please complete the following information):

  • Browser: Chrome
  • Framework: No javascript web framework
  • Context: Sharepoint
  • Version: npm 1.1.0-preview.2

RagasaSP avatar Dec 04 '19 18:12 RagasaSP

This is a good scenario we haven't considered, thanks for reporting this. I'll investigate this.

Initial thoughts - we need to find a way to prevent the same component being defined twice. lit-element is doing the element registration right now - wondering if there is something we can do on our end to not load the component if it's already defined. CustomElementRegistry.get() looks promising

nmetulev avatar Dec 04 '19 19:12 nmetulev

The issue is that lit-element does not check if the custom element is defined with customElements.get before calling customElements.define.

One workaround is to wrap the lit-element @customElement decorator with the check, like so:

// tslint:disable: completed-docs
import * as litElement from 'lit-element';
import { Constructor } from 'lit-element';

// From the TC39 Decorators proposal
interface ClassDescriptor {
  kind: 'class';
  elements: ClassElement[];
  finisher?: <T>(clazz: Constructor<T>) => undefined | Constructor<T>;
}

// From the TC39 Decorators proposal
interface ClassElement {
  kind: 'field' | 'method';
  key: PropertyKey;
  placement: 'static' | 'prototype' | 'own';
  initializer?: () => void;
  extras?: ClassElement[];
  finisher?: <T>(clazz: Constructor<T>) => undefined | Constructor<T>;
  descriptor?: PropertyDescriptor;
}

export const customElement = (tagName: string) => (classOrDescriptor: Constructor<HTMLElement> | ClassDescriptor) => {
  if (!customElements.get(tagName)) {
    litElement.customElement(tagName);
  }
};

Then import customElement from the new decorators.ts wrapper, instead of lit-element:

import { html, LitElement, property, PropertyValues } from 'lit-element';
import { classMap } from 'lit-html/directives/class-map';
import { customElement } from '../../../decorators';
import { styles } from './mgt-flyout-css';

/**
 * A component to create flyout anchored to an element
 *
 * @export
 * @class MgtFlyout
 * @extends {LitElement}
 */
@customElement('mgt-flyout')
export class MgtFlyout extends LitElement { ...

Thoughts?

shweaver-MSFT avatar Feb 05 '20 23:02 shweaver-MSFT

The alternative would be to add the customElements.get check to the beginning of every component file.

shweaver-MSFT avatar Feb 05 '20 23:02 shweaver-MSFT

Thinking about this, I'm now understanding this is a bigger issue than just avoiding double registration

For example, assume

  • webpart A is using component A version 1.0
  • webpart B is using component A version 2.0.

In this case, with the proposed solution, the webpart that loads second will use the wrong version of component A.

I think this is well explained in this proposed solution and this experimental feature from open-wc.

@shweaver-MSFT, your solution above will fix this if the webparts are using the same version of the component. However I can see multiple webpart using the same component, but not necessarily the same version.

Couple options that come to mind (but I'm not super happy with either one):

  1. Version components: Append the version of the component in the tag - mgt-person-110
  2. Ask developers to register components with their own name:
    customElements.define('my-person', class extends MgtPerson)
    

Additionally, we should also consider doing custom versioned implementation of subcomponents used within top level components and use your solution.

nmetulev avatar Feb 06 '20 00:02 nmetulev

I don't think we are going to be able to explicitly version components. LitElement definitely makes it difficult anyway.

We traditionally decorate classes with @customElement('mgt-foo'). Unfortunately, LitElement won't let us do this because it attempts to reuse the same constructor to define a new element, which causes an error.

DOESN'T WORK 😢

@customElement('mgt-person')
@customElement(`mgt-person-${COMPONENT_VERSION}`)
export class MgtPerson...

My next thought was to do something like this:

class MgtPersonVersioned extends MgtPerson {}
window.customElements.define(`mgt-person-${COMPONENT_VERSION}`, MgtPersonVersioned);

Unfortunately, this creates components that we can't actually reference from Lit html templates:

DOESN'T WORK 😢

protected renderFlyoutContent(
    personDetails: IDynamicPerson,
    image: string,
    presence: MicrosoftGraphBeta.Presence
  ): TemplateResult {
    return (
      this.renderTemplate('person-card', { person: personDetails, personImage: image }) ||
      html`
        <mgt-person-card-${COMPONENT_VERSION}
          .personDetails=${personDetails}
          .personImage=${image}
          .personPresence=${presence}
          .showPresence=${this.showPresence}
        ></mgt-person-card-${COMPONENT_VERSION}>
      `
    );
  }

WORKS 🤔

<mgt-person-card-130` ...></mgt-person-card-130>

If we can't use dynamic syntax to name elements we would have to hardcode the version all over the project to get components to work. Which I'm not a fan of.

I'm going to start looking into https://open-wc.org/scoped-elements/ next. Looks promising. More to come...

shweaver-MSFT avatar Jun 26 '20 19:06 shweaver-MSFT

I think I have a good solution based on https://open-wc.org/scoped-elements/ See #543

shweaver-MSFT avatar Jul 08 '20 22:07 shweaver-MSFT

We need your help

This is a tough one. After much discussion on the team, we aren't sure exactly the correct approach to solve this issue. A PR is available with my attempt at a solution, but it isn't perfect (#543).

The attempt is built on the assumption that all MGT instances would be used in an iframe, but to my chagrin this isn't always the case. In addition, support for scoped element registries is not yet adopted by the W3C, so I had to work with a polyfill. Some good discussion on the topic can be found here.

If there are any particularly savvy developers out there, we welcome your expertise 😊

shweaver-MSFT avatar Jul 24 '20 20:07 shweaver-MSFT

There is no easy solution to this while we are waiting for scoped elements to make it into the w3c spec. But I'm wondering if there is something that can be done with SPFx library types as a workaround for webparts? If I'm understanding it correctly, it sounds like the library type can be used to package a library to be reused across web parts? If that's the case, could we ship an SPFx npm package for this use case? There seems to be some prototyping needed here if we think this could be viable.

  • @waldekmastykarz, @rabwill

nmetulev avatar Dec 04 '20 05:12 nmetulev

Good idea! Let's check with ODSP if there are no limitations that would prevent us from doing it.

waldekmastykarz avatar Dec 04 '20 08:12 waldekmastykarz

After chatting with @waldekmastykarz, in addition to investigating whether an SPFx library type would work, he suggested we change the error that happens when trying to register the same component type with a warning. The idea is to log a warning in the console if a component is already registered to let the developer know that someone else might already have imported a different version of the toolkit and is using it. Even though it does not solve the issue here, it will at least give more insight to the developer. A warning such as should work:

Warning: component mgt-bla was already registered. This is usually because multiple versions of the Microsoft Graph Toolkit mgt-bla component might be used on this page. All instances of mgt-bla on this page will be using the first registration of the component, version 1.3.6. See issue [this] for more details

Created #810 to track this work

nmetulev avatar Dec 07 '20 03:12 nmetulev

As for prototyping with the SPFx library types, that seems like a good solution for SPFx developers. This is how I see it working from a high level:

  • Create a new npm package for SPFx. Could be called @microsoft/mgt-spfx. Open to other name ideas of course
  • The package should only take dependency on the @microsoft/mgt-components and @microsoft/mgt-sharepoint-provider packages as those are the only ones needed. It can then re-export them back from it's index.ts
  • If the package needs to expose a bundle (not sure if that is a requirement for library types), we could reuse the rollup configuration we have for mgt.dev as that packages up everything in a single es module.

Thoughts?

nmetulev avatar Dec 07 '20 04:12 nmetulev

Awesome idea!

  • Many folks on SPFx use React but definitely not everyone. Shall we consider @microsoft/mgt-spfx and @microsoft/mgt-spfx-react or could you use both @microsoft/mgt and @microsoft/mgt-react with @microsoft/@spfx?
  • The requirement of being able to support multiple things loading MGT on one page is typical for any system that supports building widgets that aren't isolated in iframes, rather than being specific to SPFx. That said, for the simplicity I'd suggest using @microsoft/mgt-spfx for now and renaming should there be a need in the future
  • Library packages do indeed have a bundle. Typically, you put in there something you'd use in other solutions, like a logging service, data service, etc. Not sure if that's necessary, since after deploying the library component, it's automatically loaded on the page. Let's have a look at what we need to get it to work

waldekmastykarz avatar Dec 07 '20 11:12 waldekmastykarz

Many folks on SPFx use React but definitely not everyone. Shall we consider @microsoft/mgt-spfx and @microsoft/mgt-spfx-react or could you use both @microsoft/mgt and @microsoft/mgt-react with @microsoft/@spfx?

Great point. @microsoft/mgt-react should just work on top of @microsoft/mgt-spfx since mgt-react just uses the components, it doesn't need to register them. If that's not the case, then we should make sure it works that way - I can help with this.

The requirement of being able to support multiple things loading MGT on one page is typical for any system that supports building widgets that aren't isolated in iframes, rather than being specific to SPFx. That said, for the simplicity I'd suggest using @microsoft/mgt-spfx for now and renaming should there be a need in the future

Makes sense, @microsoft/mgt-spfx it is :)

Library packages do indeed have a bundle. Typically, you put in there something you'd use in other solutions, like a logging service, data service, etc. Not sure if that's necessary, since after deploying the library component, it's automatically loaded on the page. Let's have a look at what we need to get it to work

Awesome. Either way, we can make it work

nmetulev avatar Dec 07 '20 16:12 nmetulev

This is great new @nmetulev 😍 a package for SPFx would be perfect. I am happy to work with you to test out and provide feedback. Thanks also to @waldekmastykarz 💪🏾

rabwill avatar Dec 07 '20 23:12 rabwill

Hey @nmetulev, just to check if I get the spec correctly:

  • we create a new SPFx package with a library component
  • the library component references @microsoft/mgt-components and @microsoft/mgt-sharepoint-provider but doesn't need to do anything else beyond that
  • with the SPFx library component on the page you should be able to use multiple instances of mgt (react) on the page without any additional changes in MGT, correct?

waldekmastykarz avatar Dec 09 '20 12:12 waldekmastykarz

Btw, I'll created a repo that we can use to test the setup: https://github.com/waldekmastykarz/mgt-spfx

waldekmastykarz avatar Dec 09 '20 13:12 waldekmastykarz

@nmetulev when trying to install the MGT dependencies, I'm getting the following error:

$ npm i @microsoft/mgt-components @microsoft/mgt-sharepoint-provider
npm ERR! code ETARGET
npm ERR! notarget No matching version found for @microsoft/[email protected].
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.
npm ERR! notarget
npm ERR! notarget It was specified as a dependency of '@microsoft/mgt-components'
npm ERR! notarget

waldekmastykarz avatar Dec 09 '20 13:12 waldekmastykarz

@waldekmastykarz @nmetulev react components don't seem to work on top of just mgt-components so may be mgt-react should also be exported? I also had to add mgt-elements into the library for below

Providers.globalProvider

And with provider only initiated on one webpart the other webpart can co-exist. image

rabwill avatar Dec 10 '20 02:12 rabwill

This is so cool!

I just created a PR to change the dependency of mgt-react to just mgt-components (#839), that should help to keep the dependency light.

I also had to add mgt-elements into the library for below

mgt-element makes sense, that's where all the provider glue lives. We could re-export mgt-element from mgt-react, but not sure if that makes a ton of sense.

And with provider only initiated on one webpart the other webpart can co-exist.

This also makes sense, since the components now live globaly on the page, they only need one provider. Is that a concern?

nmetulev avatar Dec 10 '20 05:12 nmetulev

This also makes sense, since the components now live globaly on the page, they only need one provider. Is that a concern?

Nope, that makes perfect sense. If you use MGT across multiple web parts/extensions, you shouldn't need to load the init code multiple times.

waldekmastykarz avatar Dec 10 '20 08:12 waldekmastykarz