youtube / spfjs

A lightweight JS framework for fast navigation and page updates from YouTube
https://youtube.github.io/spfjs/
MIT License
2.23k stars 147 forks source link

Custom URL endpoint w/ SPF #432

Open mAAdhaTTah opened 7 years ago

mAAdhaTTah commented 7 years ago

I'm considering using spfjs for a WordPress theme, but I'd like to use the WP-API to return the JSON response, rather than adding custom behavior to the standard URLs, which would mean a completely different URL structure than what spfjs expects by default. Is there a config item or hook I can use to modify this?

RoneyThomas commented 7 years ago

No. spfjs sends query string ?spf=navigate so that in the back end it can decide whether to send the full page or JSON.

DavidCPhillips commented 7 years ago

Well it depends on exactly how different. The SPF identifying (?spf=navigate) is configurable by setting the url-identifier field in the global configuration:

https://github.com/youtube/spfjs/blob/master/src/client/config.js#L44

Since the default identifier starts with the parameters, that can be replaced by any valid suffix. For example, the demo uses '.spf.json' to reference static files:

https://github.com/youtube/spfjs/blob/master/web/assets/scripts/main.js#L142

mAAdhaTTah commented 7 years ago

No, I'm looking at trying to implement it against a completely different URL endpoint. e.g. navigate to /my-post/ hits endpoint @ /wp-json/theme/spf?slug=my-post or something of that nature.

nicksay commented 7 years ago

For link clicks, the only currently supported base value is an href on the target element or an ancestor: https://github.com/youtube/spfjs/blob/988b652f6f979d7445f3160a40e29094030d1be5/src/client/nav/nav.js#L176-L182

However, I think it would be a reasonable extension to allow a data attribute on an element to specify a custom URL, perhaps either data-spf-url or data-spf-href? It would look something like:

<a href="/page-url" data-spf-url="/custom-spf-url">...</a>

@DavidCPhillips Any objections? This would break the tight coupling between content served for static/dynamic navigation, but as long as it's not the default behavior, I think it would be okay.

mAAdhaTTah commented 7 years ago

For my purposes, I'd prefer being able to handle this on the Javascript side, supplying a function that takes the destination URL and returns the API endpoint URL.

DavidCPhillips commented 7 years ago

I'd be open to a custom data attribute. For the JS side, we could potentially make the spfrequest event have a more complex configurable response. That would address issue #427 as well.

rviscomi commented 7 years ago

If you've got a service worker, it could intercept /foo?spf=navigate requests and fulfill them with responses from /some/other/handler?page=foo&spf=navigate. Not saying it's any better than customizing SPF URL request templates, but it's an interesting solution.