Skip to content

Improving runtime services API #16322

@dreamofabear

Description

@dreamofabear

Background

Status quo API is highly error prone for PWA and FIEs:

// Case 1: Returns service scoped to parent document.
Services.fooForDoc(element.getAmpdoc());

// Case 2: Returns service scoped to FIE.
Services.fooForDoc(element);

// Case 2A: Implicit FIE service sharing (fallback) case.
Services.fooForDoc(element);

// Case 3: Does not work in PWA.
Services.fooForDoc(element.ownerDocument);

// Proposal: Return the correctly-scoped service given an element. 
// If element is in FIE, will _not_ return parent service unless explicitly asked.
Services.fooForElement(element, opt_useParentService);

FIE

requiem/doc/postmortem112504, #19295

PWA

#16043

The root problem is that getServiceForDoc(window.document) doesn't work in PWAs. This is because it relies on AmpDocService#getAmpDoc(node) which traverses up node's parents to find the service holder. However, in shadow AMP services live on the shadow root, which is a child of the document. So traversing up the document will fail to find the shadow root.

Instead, non-window service getters should always be passed the AMP element itself (or a nearby node), e.g. getServiceForDoc(myAmpElement). We have a long-standing initiative to refactor and improve this but it hasn't been prioritized yet (go/amp-roots).

Context: #16233 (comment)

Proposal

Only allow passing !Element|!ShadowRoot to service getters for current FIE-supported services (actions, bind, url, urlReplacements).

This has the nice benefit that extensions will automatically do the right thing in FIE context if A4A decides to support them (e.g. amp-gwd-animation recently was whitelisted and needed refactoring for proper support). By contrast, if we decided to continue using AmpDoc for FIE, we'd need to worry if callers are passing the wrong AmpDoc instance.

/cc @dvoytenko @lannka

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions