UNPKG

cheetah-framework

Version:

Cheetah Framework JS used in all our applications

87 lines (68 loc) 2.21 kB
/* param */ const baseOptions = { strictMode: true, key: ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'], q: { parser: /(?:^|&)([^&=]*)=?([^&]*)/g }, parser: { strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ } } class ParsedUri { constructor (str, customOptions) { const options = _.extend({}, baseOptions, customOptions) var m = options.parser[options.strictMode ? 'strict' : 'loose'].exec(str) var i = 14 while (i--) this[options.key[i]] = m[i] || '' this.queryKey = {} this[options.key[12]].replace(options.q.parser, ($0, $1, $2) => { if ($1) this.queryKey[$1] = $2 }) } toUrl () { return [ ...(this.protocol && this.host ? `${this.protocol}://${this.host}` : ''), ...(!this.protocol && this.host ? `//${this.host}` : ''), ...(this.port ? `:${this.port}` : ''), `${this.path}${this.queryString}${this.hash}`, ].join('') } mergeParams (params) { _.merge(this.queryKey, params) return this } addParam (key, value) { _.set(this.queryKey, key, value) return this } removeParam (name) { delete this.queryKey[name] return this } getParam (name) { return _.get(this.queryKey, name) } get queryString () { return _.isEmpty(this.queryKey) ? '' : `?${param(this.queryKey)}` } get hash () { return this.anchor ? `#${this.anchor}` : '' } toString () { return this.toUrl() } } class Uri { static parse (str = null, options = {}) { return new ParsedUri(str || window.location.href, options) } static replace (url) { window.history.replaceState(null, null, url instanceof ParsedUri ? url.toString() : url) } static addParams (url, params) { return Uri.parse(url).mergeParams(params).toUrl() } } export default Uri