Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨ [amp-render] implement xssi-prefix, sub-object and refresh support #33894

Merged
merged 24 commits into from
Apr 21, 2021
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 23 additions & 5 deletions extensions/amp-render/1.0/amp-render.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
*/

import {BaseElement} from './base-element';
import {FetchOptionsDef, batchFetchJsonFor} from '../../../src/batched-json';
import {Services} from '../../../src/services';
import {batchFetchJsonFor} from '../../../src/batched-json';
import {dev, user, userAssert} from '../../../src/log';
import {dict} from '../../../src/core/types/object';
import {isAmpScriptUri} from '../../../src/url';
Expand Down Expand Up @@ -67,14 +67,27 @@ const getAmpStateJson = (element, src) => {
});
};

/**
* @param {!AmpElement} element
* @param {boolean} shouldRefresh true to force refresh of browser cache.
* @return {!FetchOptionsDef} options object to pass to `batchFetchJsonFor` method.
*/
function buildOptionsObject(element, shouldRefresh = false) {
return {
xssiPrefix: element.getAttribute('xssi-prefix'),
expr: element.getAttribute('key') ?? '.',
refresh: shouldRefresh,
};
}

/**
* Returns a function to fetch json from remote url, amp-state or
* amp-script.
*
* @param {!AmpElement} element
* @return {Function}
*/
export const getJsonFn = (element) => {
export function getJsonFn(element) {
const src = element.getAttribute('src');
if (!src) {
// TODO(dmanek): assert that src is provided instead of silently failing below.
Expand All @@ -90,8 +103,13 @@ export const getJsonFn = (element) => {
return ampScriptService.fetch(src);
});
}
return () => batchFetchJsonFor(element.getAmpDoc(), element);
};
return (unusedSrc, shouldRefresh = false) =>
batchFetchJsonFor(
element.getAmpDoc(),
element,
buildOptionsObject(element, shouldRefresh)
);
}

export class AmpRender extends BaseElement {
/** @param {!AmpElement} element */
Expand Down Expand Up @@ -122,7 +140,7 @@ export class AmpRender extends BaseElement {
// variable `canRefresh`. See https://github.com/ampproject/amphtml/pull/33776#discussion_r614087734
// for more context. This approach may be better if src does not mutate often. But the alternative might
// be better if src mutatates often and component user does not use `refresh` action.
if (!src?.length || isAmpStateSrc(src) || isAmpScriptUri(src)) {
if (!src || isAmpStateSrc(src) || isAmpScriptUri(src)) {
return;
}
api.refresh();
Expand Down
2 changes: 1 addition & 1 deletion extensions/amp-render/1.0/component.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export function RenderWithRef(
}, [src, getJson]);

const refresh = useCallback(() => {
getJson(src).then((data) => {
getJson(src, /* shouldRefresh */ true).then((data) => {
setData(data);
});
}, [getJson, src]);
Expand Down
53 changes: 53 additions & 0 deletions extensions/amp-render/1.0/test/test-amp-render.js
Original file line number Diff line number Diff line change
Expand Up @@ -208,10 +208,20 @@ describes.realWin(
doc.body.appendChild(element);

await getRenderedData();
let options = fetchJsonStub.getCall(0).args[2];
// verify initial call to `batchFetchJsonFor`
expect(options.refresh).to.be.false;
expect(options.xssiPrefix).to.be.null;
expect(options.expr).to.be.equal('.');

element.enqueAction(invocation('refresh'));
await getRenderedData();
expect(fetchJsonStub).to.have.been.calledTwice;
options = fetchJsonStub.getCall(1).args[2];
// verify subsequent call to `batchFetchJsonFor`
expect(options.refresh).to.be.true;
expect(options.xssiPrefix).to.be.null;
expect(options.expr).to.be.equal('.');
});

it('should not re-fetch when src=amp-state', async () => {
Expand Down Expand Up @@ -305,5 +315,48 @@ describes.realWin(
expect(ampScript.getImpl).to.have.been.calledOnce;
expect(fetchJsonStub).not.to.have.been.called;
});

it('should use the specified xssi-prefix and key attributes', async () => {
const json = {
fullName: {
firstName: 'Joe',
lastName: 'Biden',
},
};

const fetchJsonStub = env.sandbox
.stub(BatchedJsonModule, 'batchFetchJsonFor')
.callThrough();

env.sandbox.stub(Services, 'batchedXhrFor').returns({
fetchJson: () => Promise.resolve(json),
});

env.sandbox.stub(Services, 'xhrFor').returns({
fetch: () => Promise.resolve(json),
xssiJson: () => Promise.resolve(json),
});

element = html`
<amp-render
xssi-prefix=")]}"
key="fullName"
src="https://example.com/data.json"
width="auto"
height="140"
layout="fixed-height"
>
<template type="amp-mustache">{{lastName}}, {{firstName}}</template>
</amp-render>
`;
doc.body.appendChild(element);

const text = await getRenderedData();
expect(text).to.equal('Biden, Joe');
const options = fetchJsonStub.getCall(0).args[2];
expect(options.xssiPrefix).to.equal(')]}');
expect(options.expr).to.equal('fullName');
expect(options.refresh).to.be.false;
});
}
);
26 changes: 18 additions & 8 deletions src/batched-json.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,23 @@ import {assertHttpsUrl} from './url';
import {getValueForExpr} from './json';
import {user} from './log';

/**
* Detail of each `options` property:
* expr - Dot-syntax reference to subdata of JSON result to return. If not specified,
* entire JSON result is returned.
* urlReplacement - If ALL, replaces all URL vars. If OPT_IN, replaces allowlisted
* URL vars. Otherwise, don't expand.
* refresh - Forces refresh of browser cache.
* xssiPrefix - Prefix to optionally strip from the response before calling parseJson.
*
* @typedef {{
* expr:(string|undefined),
* urlReplacement: (UrlReplacementPolicy|undefined),
* refresh: (boolean|undefined),
* xssiPrefix: (string|undefined)}}
*/
export let FetchOptionsDef;

/**
* @enum {number}
*/
Expand All @@ -35,14 +52,7 @@ export const UrlReplacementPolicy = {
*
* @param {!./service/ampdoc-impl.AmpDoc} ampdoc
* @param {!Element} element
* @param {!Object} options options bag for modifying the request.
* @param {string|undefined} options.expr Dot-syntax reference to subdata of JSON result.
* to return. If not specified, entire JSON result is returned.
* @param {UrlReplacementPolicy|undefined} options.urlReplacement If ALL, replaces all URL
* vars. If OPT_IN, replaces allowlisted URL vars. Otherwise, don't expand.
* @param {boolean|undefined} options.refresh Forces refresh of browser cache.
* @param {string|undefined} options.xssiPrefix Prefix to optionally
* strip from the response before calling parseJson.
* @param {!FetchOptionsDef} options options bag for modifying the request.
* @return {!Promise<!JsonObject|!Array<JsonObject>>} Resolved with JSON
* result or rejected if response is invalid.
*/
Expand Down