Giter VIP home page Giter VIP logo

iron-location's Introduction

Published on NPM Build status Published on webcomponents.org

iron-location

The iron-location elements manage bindings to and from the current URL and query parameters. See: Documentation, iron-location demo, iron-query-params demo.

<iron-location>

The iron-location element manages binding to and from the current URL.

<iron-query-params>

The iron-query-params element manages serialization and parsing of query parameter strings.

Usage

Installation

npm install --save @polymer/iron-location

In an html file

<iron-location>
<html>
  <head>
    <script type="module">
      import '@polymer/iron-location/iron-location.js';
    </script>
  </head>
  <body>
    <iron-location
        path="/social/profiles"
        hash="profilePicture"
        query="userId=polymer&display=dark"
        dwell-time="1000">
    </iron-location>
  </body>
</html>

<iron-query-params>

<html>
  <head>
    <script type="module">
      import '@polymer/polymer/lib/elements/dom-bind.js';
      import '@polymer/iron-location/iron-location.js';
      import '@polymer/iron-location/iron-query-params.js';
    </script>
  </head>
  <body>
    <dom-bind>
      <template>
        <iron-location
            path="/social/profiles"
            hash="profilePicture"
            query="{{paramsString}}"
            dwell-time="1000">
        </iron-location>
        <iron-query-params
            id="queryParams"
            params-string='{{paramsString}}'
            params-object='{"userId": "polymer", "display": "dark"}'>
        </iron-query-params>
      </template>
    </dom-bind>
  </body>
</html>

In a Polymer 3 element

<iron-location>
import {PolymerElement, html} from '@polymer/polymer';
import '@polymer/iron-location/iron-location.js';

class SampleElement extends PolymerElement {
  static get template() {
    return html`
      <iron-location
          path="/social/profiles"
          hash="profilePicture"
          query="userId=polymer&display=dark"
          dwell-time="1000">
      </iron-location>
    `;
  }
}
customElements.define('sample-element', SampleElement);

<iron-query-params>

import {PolymerElement, html} from '@polymer/polymer';
import '@polymer/iron-location/iron-location.js';
import '@polymer/iron-location/iron-query-params.js';

class SampleElement extends PolymerElement {
  static get template() {
    return html`
      <iron-location
          path="/social/profiles"
          hash="profilePicture"
          query="{{paramsString}}"
          dwell-time="1000">
      </iron-location>
      <iron-query-params
          id="queryParams"
          params-string='{{paramString}}'
          params-object='{"userId": "polymer", "display": "dark"}'>
      </iron-query-params>
    `;
  }
}
customElements.define('sample-element', SampleElement);

Contributing

If you want to send a PR to this element, here are the instructions for running the tests and demo locally:

Installation

git clone https://github.com/PolymerElements/iron-location
cd iron-location
npm install
npm install -g polymer-cli

Running the demo locally

polymer serve --npm
open http://127.0.0.1:<port>/demo/

Running the tests

polymer test --npm

iron-location's People

Contributors

alirni avatar aomarks avatar arantius avatar bicknellr avatar brianmanden avatar cdata avatar dependabot[bot] avatar dfreedm avatar e111077 avatar holgerengels avatar karolchmist avatar keanulee avatar mgibas avatar mgiuffrida avatar notwaldorf avatar palli avatar rictic avatar tedium-bot avatar valdrinkoshi avatar zboralski avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

iron-location's Issues

Use URLSearchParams for paramsObject

Currently, the paramsObject in iron-query-params.html is a native JS object. The most noticeable limitation of this approach is that every key can have at most one value. It is impossible to have the following paramsObject:

{
  "key": "value",
  "key": "otherValue"
}

The ability to have multiple values for one key is a fairly common need, especially in faceted searching.

The WHATWG spec defines a URLSearchParams class for interacting with query parameters of a URL. Web developers will be able to use a standard for interacting with query parameters of the URL instead of the custom implementation noted above.

This is a breaking change, but I feel there is great value in using a native class for query parameters. It will make the use and interaction with query parameters much more rich, as well as providing support for otherwise unattainable use cases.

Query Parameters which have zero as value are being ignored

Description

The query parameters which have zero as value are being ignored in iron-query-params

var params = {
  status : 0,
  s: 'term'
}

Expected outcome

url?status=0&s="term"

Actual outcome

url?s="term"

Browsers Affected

  • [x ] Chrome
  • [ x] Firefox
  • [ x] Safari 9
  • [ x] Safari 8
  • [ x] Safari 7
  • [ x] Edge
  • [ x] IE 11

Default dwellTime is too long

Gotcha!

I just got caught out by the default dwellTime, which is a whopping 2000ms! This is more than long enough for a user to click through to a different route, in fairly normal use cases.

Unless there is good reason, please reduce this to something more suitable like 100ms, or less. This is just way too big a gotcha at present...

Cheers,

Steve

IE11 support for "new URL()" is gone...

Description

It looks like support for new URL() is gone from IE11

https://developer.mozilla.org/en/docs/Web/API/URL#Browser_compatibility

Expected outcome

Navigation from anchor tags to not reload the entire page.

Actual outcome

Navigation is causing the entire page to reload.

Live Demo

Steps to reproduce

polymer init a PSK 2.0 and run it in ie 11
click navigation links on the left

Dev Note :)

It's in the _getSameOriginLinkHref function.

Browsers Affected

  • IE 11
  • Chrome
  • Firefox
  • Safari 9
  • Safari 8
  • Safari 7
  • Edge
  • IE 10

Handling blob url

Description

iron-location swallow url like: href="blob:https://..." and make link download not working.

seems like not working with data-property of app-route

Description

We used iron-location to get query parameters from url. If we also change the data property of app-route, the url will not be changed in address bar. For example:

<iron-location path="{{path}}" query="{{query}}" use-hash-as-path></iron-location>
<iron-query-params
  params-string="{{query}}"
  params-object="{{queryParams}}">
</iron-query-params>
<app-route-converter
  path="{{path}}"
  query-params="{{queryParams}}"
  route="{{route}}">
</app-route-converter>

<app-route route="{{route}}"
           pattern="/:view"
           data="{{routeData}}"></app-route>

...
this.set('routeData.view', 'GNAAA');

Expected outcome

http://someurl/index.html#/GNAAA

Actual outcome

http://someurl/index.html#/

If we remove the iron-location from our code, all works as expected.

Browsers Affected

  • Chrome
  • Firefox
  • Safari 9
  • Safari 8
  • Safari 7
  • Edge
  • IE 11
  • IE 10

urls starting with double / causes iron-location to "forget" hostname when generating urls

Description

when the url starts with a double slash (or more), iron-location generates an incorrect url (hostname is left out). When trying to set this invalid url through the history api, a DOMException is raised ( DOMException: Failed to execute 'pushState' on 'History')

Expected outcome

The host should still be included in the generated url, and the history push state should work as expected

Actual outcome

unhandled DOMException, breaking all following script execution

Hostname property for SEO URL conversions?

I'm actually not sure if this is correct practice but for SEO purposes it's considered best practice to define absolute paths vs relative paths. This could be easily solved by data-binding to a hostname property in the iron-page-url element. Though I'm not sure if Google's crawler or crawlers in general can pick up that hostname defined this way. Either way, a hostname property might make sense?

location-changed event not fired in case of file:// protocol for mobile hybrid app.

Description

To check whether the href origin and current origin is same or not, URL constructor is being used.

URL constructor is behaving correctly for http:, but not for file: protocol

var url = new URL("http://google.com")
url.origin will be http://google.com

However when index.html is loaded from cordova hybrid app for following href
"file:///Users/kpraveen/Library/Developer/CoreSimulator/Devices/8336AC80-5CE3-4E95-BEDE-34667F0F845D/data/Containers/Bundle/Application/AA8F812B-2B08-41D9-A11C-F0E82B3B6193/HelloWorld.app/www/elements/abcd"
url.origin will be "null"

Due to this, when following check is performed
origin will be "file://", and url.origin will be "null"
if (url.origin !== origin) {
return null;
}
it will be treated as different origin, although origin is same.
This causes app-location, app-route to fail.
Tested in ios simulator on mac.

Expected outcome

if current and linked url both are from file:// it should be treated as same origin always and location-changed event must be fired.

Actual outcome

if current and linked url both are from file:// it is treated as cross origin so location-changed event is not fired.

Feature request : encode spaces as pluses (+)

Description

Currently the spaces in the URL are encoded as %20. It would be useful to be able to replace them with pluses (+). Many services do it as it's more pleasant to read (Google included).

To maintain current functionality, it would be optional and enabled with an attribute.

PR will follow.

Expected outcome

{'foo': 'value with spaces'} =>   '?foo=value+with+spaces'

Actual outcome

{'foo': 'value with spaces'} =>   '?foo=value%20with%20spaces'

iron-location shouldn't decode window.location.search

Decoding the entire query component at once (at least with decodeURIComponent, perhaps we should use decodeURI instead?) is an error because it is impossible to distinguish the urls:

/?foo=bar&baz -- two query parameters
/?foo=bar%26baz -- one query parameter

Better handle unusual characters

iron-location breaks in a variety of ways when given paths with # or ?, or queries with #. Any fix should also include unit tests for a variety of unexpected characters in each of the fields.

Anyway to allow multiple query parameters with same key ?

Description

Many backend frameworks allow multiple query parameters with the same key. For example ?sort=a,desc&sort=b,desc

Expected outcome

queryObject shoud be like this : { sort: ['a,desc', 'b,desc'] }

Actual outcome

Only one key is handled : { sort: 'a,desc' }

Proposition

I propose the following PR : #80.
Is that acceptable?

hashchange event is inconsistent on IE11

Description

iron-location's handling of history api seems to be causing IE11 to not fire hashchange events in some edge-case scenarios. I'm able to reproduce whenever the site uses anchor tags for some navigation and javascript for some other navigation.

Expected outcome

browser fires hashchange event

Actual outcome

browser doesn't fire hashchange event

Live Demo

http://codepen.io/robrez/pen/zKNGmK

Steps to reproduce

The issue seems to occur iff you navigate using an anchor, then navigate using javascript, then navigate using the anchor that was previously used. In otherwords, given two routes A and B, if you navigate like this: A->B->A->B and A uses an anchor, but B uses javascript, hashchange events cease to fire.

If A and B both use anchors or A and B both use javascript, the issue does not seem to occur.

In the live demo provided, you can see the breakdown by clicking bravo->charlie->bravo->charlie
Note that iron-location incorrectly reports a hash of "bravo". Proceeding to a different route, eg delta, "fixes" the problem

I only speculate that this relates to iron-location because I have a separate demo that doesn't use iron-location. In that demo, hashchange events continue firing in every situation I've tested

Browsers Affected

  • Chrome
  • Firefox
  • Safari 9
  • Safari 8
  • Safari 7
  • Edge
  • IE 11
  • IE 10

iron-location's this.hash is encoded and decoded using different funcitons

Description

this.hash should use the same encoding and decoding functions. encodeURI and encodeURIComponent have subtle differences.

https://github.com/PolymerElements/iron-location/blob/master/iron-location.js#L88
window.decodeURIComponent(window.location.hash.slice(1));

https://github.com/PolymerElements/iron-location/blob/master/iron-location.js#L210
partiallyEncodedHash = '#' + window.encodeURI(this.hash);

encodeURI and encodeURIComponent maybe the wrong function to encode/decode the hash, but i am just advocating for using the same function... not necessarily the correct one.

Document the location-changed event

There isn't a standard event that's fired when someone uses pushState/replaceState so we're listening for and firing the location-changed event. We should document this more clearly.

`iron-query-params` does not correctly decode + in query string values.

Seems like internally iron-query-params uses decodeUriComponent to decode query string into a dictionary.

encodeUri and decodeUri expect spaces to be encoded as %20, however when it comes to query string values (not the url part of the uri), then encoding spaces as + is also valid, but decodeUriComponent does not take this into account, despite this being a common encoding way in many libraries.

Google closure libraries work around this by explicitly doing a .replace() in addition to calling decodeUriComponent. See http://www.hobsonassoc.com/scripts/closure/goog/docs/closure_goog_string_string.js.source.html#line425 for example.

Expected

  '?foo=value+with+spaces' => {'foo': 'value with spaces'}

Actual outcome

  '?foo=value+with+spaces' => {'foo': 'value+with+spaces'}

Browsers Affected

At least chrome. Probably all.

could not change property and url

Description

Expected outcome

Actual outcome

Live Demo

Steps to reproduce

Browsers Affected

  • Chrome
  • Firefox
  • Safari 9
  • Safari 8
  • Safari 7
  • Edge
  • IE 11
  • IE 10

<dom-module id="app-shell">
  <style>

  </style>
  <template>
    <iron-location path="{{path}}" query="{{query}}" hash="{{hash}}"> </iron-location>
<some query="{{query}}" > <some>
  </template>
</dom-module>

<script>
  Polymer({
    is: 'app-shell',
    properties: {
      query: {
        type: String,
        notify: true,
      },
      path: String,
    },

    ready: function () {
      this.query="fsdf=fasd";
      this.async(function () {
              this.set('query', "?");
      this.query = this.query + "aaa";
      this.set('path', this.path + '?' + 'aa');
      });
    },

  });

</script>

Instant redirects when the element wakes up shouldn't flood history

As a user of a site built with iron-location,
when the site redirects automatically and immediately
after I initially navigate to it,
I don't want any extra entries in my history,
and I definitely want the back button to take me to the
previous site I was on, rather than taking me back to
a page that will then instantly navigate me forward again.

We should be able to do this pretty simply by just giving _lastChangedAt a better initial value, such that any navigations in the first 200ms or so will call replaceState rather than pushState.

[IE] ES5-compiled iron-location with Polymer 2 does not intercept <a> link clicks

Description

When a ES5-compiled project is served from a remote web server (i.e. "github.io", not "localhost:8081"), iron-location doesn't intercept clicks on anchor tags and, as a result, navigation causes full-page reload.

Note that this issue does not occur when served locally. That is, if you clone the below repo and locally serve the docs/ directory (via python -m SimpleHTTPServer or something).

Expected outcome

Clicking on the link updates the URL (via pushstate) and the browser does not navigate.

Actual outcome

The browser navigates (to a non-existent URL)

Live Demo

https://keanulee.github.io/iron-location-ie-test/
(Code: https://github.com/keanulee/iron-location-ie-test)

Steps to reproduce

See above

Browsers Affected

IE only

Not in the catalog?

Since it is not in PolymerLabs, one would expect this one to appear in the catalog?

More samples

Hi, can you point me to more samples of using I can't seem to get it to work but I suspect I am doing it wrong. If there was a working example somewhere I could figure it out.

Thanks

about the listener in the document.body

Hi, this is more a question that an issue, I think. Why is there a listener to all clicks in the document.body?

this.unlisten(/** @type {!HTMLBodyElement} */(document.body), 'click', '_globalOnClick');

I have an small router component that wraps a router library. This library fires some events and when I add the iron-page-url to show and debug some information in my demo, the router stops working due to the event.preventDefault().

My demo has some links and one iron-pages component to show how the element changes when the user clicks in the links.

Regards.

<iron-location> should not disassemble the url

Hi,

I propose to let <iron-location> just sync to the url bar, not split the url string. The splitting should be done by another element.

<iron-location url="{{url}}"></iron-location>
<iron-url-splitter url="{{url}}"
                   use-hash-routing
                   path="{{path}}"
                   query="{{query}}"></iron-url-splitter>
<iron-query-params params-string="{{query}}"
                   params-object="{{queryParams}}">

Note: <iron-url-splitter> is ATM purely fictional. I just use it to show how it would look like.

PROs:

  • Separation of concerns: <iron-location> is responsible for syncing to the url bar only
  • Atomic updates: Just one string parameter for everything
  • The disassembly for hash routing could be done properly. The element that does the splitting (here my fictional <iron-url-splitter>) should care about hash routing vs path routing.
    • Currently it ends up like this: ?key=value#/my/path (Note the reverse order)
    • It should look like this: #/my/path?key=value

'use strict' failing closure compile

Description

The 'use strict' line at the top of all iron-location elements is causing closure compile failure. This can be fixed by wrapping the entire script so it looks like

(function() {
'use strict'
....
}());

Steps to reproduce

When attempting to add iron-location to a Chromium closure build (e.g chrome/browser/resources/md_history/compiled_resources2.gyp), the closure build fails with

## ERROR - Suspicious code. Is there a missing '+' on the previous line?
## 'use strict';
## ^

Full page refresh when clicking on a link to the same page

Description

Ref Polymer/shop#51

When clicking on a link to the URL you're already on (e.g. link in the tabs to http://localhost:8080/list/ladies_outerwear while on the same page), a full page refresh is triggered instead of silently doing nothing. Seems to be because of this code: https://github.com/PolymerElements/iron-location/blob/master/iron-location.html#L321

Expected outcome

After a normal click (e.g. no modifier keys), the page should not refresh.

Actual outcome

After a normal click, the page refreshes.

Live Demo

(Not on shop.polymer-project.org which uses an older version of iron-location, but occurs with fresh bower install

Steps to reproduce

Run shop, click a category, click on the same category.

Browsers Affected

  • Chrome
  • Firefox
  • Safari 9
  • Safari 8
  • Safari 7
  • Edge
  • IE 11
  • IE 10

Before-location-changed event

I've been finding it rather difficult to prevent a user from leaving a page if they have unsaved changes since onbeforeunload is never called. I'd like to display a confirmation "Are you sure you want to leave? Unsaved changes will be lost" before letting them leave.

One solution could be to add a before-location-changed event that is cancelable in the _updateUrl and _globalOnClick methods just before a state is pushed/replaced.

if (this.fire("before-location-changed",{},{cancelable:true}).defaultPrevented){
   return
}

This wouldn't work for back/forward browser navigation and you would still have to fire that event yourself if you wanted to imperatively change the url in the format that is suggested in the docs. If you change the path, query, or hash directly, the event would be called in the _updateUrl, we would just also have to reset those variables if defaultPrevented was true.

Open to other solutions, just figure this is a common issue.

Iron-location prevents native hash navigation

Description

Hashes can be used to point to a section with the corresponding id. E.g. if you go to mydomain.com#foo and there is a <section id="foo"> then the browser automatically scrolls to that section.

Adding app-location (and consecutively iron-location) prevents this navigation from happening.

Expected outcome

Changes to only the hash should not be intercepted.

Actual outcome

Changing the hash does not let the browser scroll to the corresponding section

Live Demo

https://jsbin.com/savejohumi/1/edit?html,console,output

Steps to reproduce

  1. Click on the link Go to Foo4
  2. Observe that the scrollbar is not altered
  3. Comment out the declaration of <iron-location>
  4. Refresh the jsbin
  5. Click on the link Go to Foo4
  6. Observe that the scrollbar is altered to the correct section

Browsers Affected

Probably all, but could verify in these browsers

  • Chrome
  • Firefox
  • Safari 9
  • Safari 8
  • Safari 7
  • Edge
  • IE 11
  • IE 10

Bower invalid-meta when installing iron-location

Description

Installing iron-location causes bower to message an invalid-meta for the field main.

Expected outcome

No error is shown

Actual outcome

bower new           version for git://github.com/polymerelements/iron-location.git#^0.8.1
bower resolve       git://github.com/polymerelements/iron-location.git#^0.8.1
bower download      https://github.com/polymerelements/iron-location/archive/v0.8.2.tar.gz
bower extract       iron-location#^0.8.1 archive.tar.gz
bower invalid-meta  The "main" field has to contain only 1 file per filetype; found multiple .html files: ["iron-location.html","iron-query-params.html"]

Steps to reproduce

  1. bower install --save polymerelements/iron-location

Browsers Affected

N/A

  • Chrome
  • Firefox
  • Safari 9
  • Safari 8
  • Safari 7
  • Edge
  • IE 11
  • IE 10

Is Still Maintained ?

It this element still maintained??
there are numbers of critical issues and PRS waiting for a response since months?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.