open-consul/ui/packages/consul-ui/app/locations/fsm-with-optional.js

321 lines
9.1 KiB
JavaScript
Raw Normal View History

import { env } from 'consul-ui/env';
const OPTIONAL = {};
ui: Adds Partitions to the HTTP layer (#10447) This PR mainly adds partition to our HTTP adapter. Additionally and perhaps most importantly, we've also taken the opportunity to move our 'conditional namespaces' deeper into the app. The reason for doing this was, we like that namespaces should be thought of as required instead of conditional, 'special' things and would like the same thinking to be applied to partitions. Now, instead of using code throughout the app throughout the adapters to add/remove namespaces or partitions depending on whether they are enabled or not. As a UI engineer you just pretend that namespaces and partitions are always enabled, and we remove them for you deeper in the app, out of the way of you forgetting to treat these properties as a special case. Notes: Added a PartitionAbility while we were there (not used as yet) Started to remove the CONSTANT variables we had just for property names. I prefer that our adapters are as readable and straightforwards as possible, it just looks like HTTP. We'll probably remove our formatDatacenter method we use also at some point, it was mainly too make it look the same as our previous formatNspace, but now we don't have that, it instead now looks different! We enable parsing of partition in the UIs URL, but this is feature flagged so still does nothing just yet. All of the test changes were related to the fact that we were treating client.url as a function rather than a method, and now that we reference this in client.url (etc) it needs binding to client.
2021-09-15 17:09:55 +00:00
if (env('CONSUL_PARTITIONS_ENABLED')) {
OPTIONAL.partition = /^-([a-zA-Z0-9]([a-zA-Z0-9-]{0,62}[a-zA-Z0-9])?)$/;
}
if (env('CONSUL_NSPACES_ENABLED')) {
OPTIONAL.nspace = /^~([a-zA-Z0-9]([a-zA-Z0-9-]{0,62}[a-zA-Z0-9])?)$/;
}
const trailingSlashRe = /\/$/;
// see below re: ember double slashes
// const moreThan1SlashRe = /\/{2,}/g;
const _uuid = function() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
const r = (Math.random() * 16) | 0;
return (c === 'x' ? r : (r & 3) | 8).toString(16);
});
};
// let popstateFired = false;
/**
* Register a callback to be invoked whenever the browser history changes,
* including using forward and back buttons.
*/
const route = function(e) {
const path = e.state.path;
const url = this.getURLForTransition(path);
// Ignore initial page load popstate event in Chrome
// if (!popstateFired) {
// popstateFired = true;
// if (url === this._previousURL) {
// return;
// }
// }
if (url === this._previousURL) {
if (path === this._previousPath) {
return;
}
this._previousPath = e.state.path;
// async
this.container.lookup('route:application').refresh();
}
if (typeof this.callback === 'function') {
// TODO: Can we use `settled` or similar to make this `route` method async?
// not async
this.callback(url);
}
// used for webkit workaround
this._previousURL = url;
this._previousPath = e.state.path;
};
export default class FSMWithOptionalLocation {
// extend FSMLocation
implementation = 'fsm-with-optional';
baseURL = '';
/**
* Set from router:main._setupLocation (-internals/routing/lib/system/router)
* Will be pre-pended to path upon state change
*/
rootURL = '/';
/**
* Path is the 'application path' i.e. the path/URL with no root/base URLs
* but potentially with optional parameters (these are remove when getURL is called)
*/
path = '/';
/**
* Sneaky undocumented property used in ember's main router used to skip any
* setup of location from the main router. We currently don't need this but
* document it here incase we ever do.
*/
cancelRouterSetup = false;
/**
* Used to store our 'optional' segments should we have any
*/
optional = {};
static create() {
return new this(...arguments);
}
constructor(owner, doc, env) {
this.container = Object.entries(owner)[0][1];
// add the route/state change handler
this.route = route.bind(this);
this.doc = typeof doc === 'undefined' ? this.container.lookup('service:-document') : doc;
this.env = typeof env === 'undefined' ? this.container.lookup('service:env') : env;
const base = this.doc.querySelector('base[href]');
if (base !== null) {
this.baseURL = base.getAttribute('href');
}
}
/**
* @internal
* Called from router:main._setupLocation (-internals/routing/lib/system/router)
* Used to set state on first call to setURL
*/
initState() {
this.location = this.location || this.doc.defaultView.location;
this.machine = this.machine || this.doc.defaultView.history;
this.doc.defaultView.addEventListener('popstate', this.route);
const state = this.machine.state;
const url = this.getURL();
const href = this.formatURL(url);
if (state && state.path === href) {
// preserve existing state
// used for webkit workaround, since there will be no initial popstate event
this._previousPath = href;
this._previousURL = url;
} else {
this.dispatch('replace', href);
}
}
getURLFrom(url) {
// remove trailing slashes if they exist
url = url || this.location.pathname;
this.rootURL = this.rootURL.replace(trailingSlashRe, '');
this.baseURL = this.baseURL.replace(trailingSlashRe, '');
// remove baseURL and rootURL from start of path
return url
.replace(new RegExp(`^${this.baseURL}(?=/|$)`), '')
.replace(new RegExp(`^${this.rootURL}(?=/|$)`), '');
// ember default locations remove double slashes here e.g. '//'
// .replace(moreThan1SlashRe, '/'); // remove extra slashes
}
getURLForTransition(url) {
this.optional = {};
url = this.getURLFrom(url)
.split('/')
.filter((item, i) => {
if (i < 3) {
let found = false;
Object.entries(OPTIONAL).reduce((prev, [key, re]) => {
const res = re.exec(item);
if (res !== null) {
prev[key] = {
value: item,
match: res[1],
};
found = true;
}
return prev;
}, this.optional);
return !found;
}
return true;
})
.join('/');
return url;
}
optionalParams() {
let optional = this.optional || {};
ui: Partitions Application Layer (#11017) * Add Partition to all our models * Add partitions into our serializers/fingerprinting * Make some amends to a few adapters ready for partitions * Amend blueprints to avoid linting error * Update all our repositories to include partitions, also Remove enabled/disable nspace repo and just use a nspace with conditionals * Ensure nspace and parition parameters always return '' no matter what * Ensure data-sink finds the model properly This will later be replaced by a @dataSink decorator but we are find kicking that can down the road a little more * Add all the new partition data layer * Add a way to set the title of the page from inside the route and make it accessibile via a route announcer * Make the Consul Route the default/basic one * Tweak nspace and partition abilities not to check the length * Thread partition through all the components that need it * Some ACL tweaks * Move the entire app to use partitions * Delete all the tests we no longer need * Update some Unit tests to use partition * Fix up KV title tests * Fix up a few more acceptance tests * Fixup and temporarily ignore some acceptance tests * Stop using ember-cli-page-objects fillable as it doesn't seem to work * Fix lint error * Remove old ACL related test * Add a tick after filling out forms * Fix token warning modal * Found some more places where we need a partition var * Fixup some more acceptance tests * Tokens still needs a repo service for CRUD * Remove acceptance tests we no longer need * Fixup and "FIXME ignore" a few tests * Remove an s * Disable blocking queries for KV to revert to previous release for now * Fixup adapter tests to follow async/function resolving interface * Fixup all the serializer integration tests * Fixup service/repo integration tests * Fixup deleting acceptance test * Fixup some ent tests * Make sure nspaces passes the dc through for when thats important * ...aaaand acceptance nspaces with the extra dc param
2021-09-15 18:50:11 +00:00
return ['partition', 'nspace'].reduce((prev, item) => {
let value = '';
if (typeof optional[item] !== 'undefined') {
value = optional[item].match;
}
prev[item] = value;
return prev;
}, {});
}
// public entrypoints for app hrefs/URLs
// visit and transitionTo can't be async/await as they return promise-like
// non-promises that get re-wrapped by the addition of async/await
visit() {
return this.transitionTo(...arguments);
}
/**
* Turns a routeName into a full URL string for anchor hrefs etc.
*/
hrefTo(routeName, params, hash) {
if (typeof hash.dc !== 'undefined') {
delete hash.dc;
}
if (typeof hash.nspace !== 'undefined') {
hash.nspace = `~${hash.nspace}`;
}
ui: Adds Partitions to the HTTP layer (#10447) This PR mainly adds partition to our HTTP adapter. Additionally and perhaps most importantly, we've also taken the opportunity to move our 'conditional namespaces' deeper into the app. The reason for doing this was, we like that namespaces should be thought of as required instead of conditional, 'special' things and would like the same thinking to be applied to partitions. Now, instead of using code throughout the app throughout the adapters to add/remove namespaces or partitions depending on whether they are enabled or not. As a UI engineer you just pretend that namespaces and partitions are always enabled, and we remove them for you deeper in the app, out of the way of you forgetting to treat these properties as a special case. Notes: Added a PartitionAbility while we were there (not used as yet) Started to remove the CONSTANT variables we had just for property names. I prefer that our adapters are as readable and straightforwards as possible, it just looks like HTTP. We'll probably remove our formatDatacenter method we use also at some point, it was mainly too make it look the same as our previous formatNspace, but now we don't have that, it instead now looks different! We enable parsing of partition in the UIs URL, but this is feature flagged so still does nothing just yet. All of the test changes were related to the fact that we were treating client.url as a function rather than a method, and now that we reference this in client.url (etc) it needs binding to client.
2021-09-15 17:09:55 +00:00
if (typeof hash.partition !== 'undefined') {
hash.partition = `-${hash.partition}`;
}
if (typeof this.router === 'undefined') {
this.router = this.container.lookup('router:main');
}
const router = this.router._routerMicrolib;
const url = router.generate(routeName, ...params, {
queryParams: {},
});
let withOptional = true;
switch (true) {
case routeName === 'settings':
case routeName.startsWith('docs.'):
withOptional = false;
}
return this.formatURL(url, hash, withOptional);
}
/**
* Takes a full browser URL including rootURL and optional (a full href) and
* performs an ember transition/refresh and browser location update using that
*/
transitionTo(url) {
const transitionURL = this.getURLForTransition(url);
if (this._previousURL === transitionURL) {
// probably an optional parameter change
this.dispatch('push', url);
return Promise.resolve();
// this.setURL(url);
} else {
// use ember to transition, which will eventually come around to use location.setURL
return this.container.lookup('router:main').transitionTo(transitionURL);
}
}
//
// Ember location interface
/**
* Returns the current `location.pathname` without `rootURL` or `baseURL`
*/
getURL() {
const search = this.location.search || '';
let hash = '';
if (typeof this.location.hash !== 'undefined') {
hash = this.location.hash.substr(0);
}
const url = this.getURLForTransition(this.location.pathname);
return `${url}${search}${hash}`;
}
formatURL(url, optional, withOptional = true) {
if (url !== '') {
// remove trailing slashes if they exists
this.rootURL = this.rootURL.replace(trailingSlashRe, '');
this.baseURL = this.baseURL.replace(trailingSlashRe, '');
} else if (this.baseURL[0] === '/' && this.rootURL[0] === '/') {
// if baseURL and rootURL both start with a slash
// ... remove trailing slash from baseURL if it exists
this.baseURL = this.baseURL.replace(trailingSlashRe, '');
}
if (withOptional) {
const temp = url.split('/');
if (Object.keys(optional || {}).length === 0) {
optional = undefined;
}
optional = Object.values(optional || this.optional || {});
ui: Partitions Application Layer (#11017) * Add Partition to all our models * Add partitions into our serializers/fingerprinting * Make some amends to a few adapters ready for partitions * Amend blueprints to avoid linting error * Update all our repositories to include partitions, also Remove enabled/disable nspace repo and just use a nspace with conditionals * Ensure nspace and parition parameters always return '' no matter what * Ensure data-sink finds the model properly This will later be replaced by a @dataSink decorator but we are find kicking that can down the road a little more * Add all the new partition data layer * Add a way to set the title of the page from inside the route and make it accessibile via a route announcer * Make the Consul Route the default/basic one * Tweak nspace and partition abilities not to check the length * Thread partition through all the components that need it * Some ACL tweaks * Move the entire app to use partitions * Delete all the tests we no longer need * Update some Unit tests to use partition * Fix up KV title tests * Fix up a few more acceptance tests * Fixup and temporarily ignore some acceptance tests * Stop using ember-cli-page-objects fillable as it doesn't seem to work * Fix lint error * Remove old ACL related test * Add a tick after filling out forms * Fix token warning modal * Found some more places where we need a partition var * Fixup some more acceptance tests * Tokens still needs a repo service for CRUD * Remove acceptance tests we no longer need * Fixup and "FIXME ignore" a few tests * Remove an s * Disable blocking queries for KV to revert to previous release for now * Fixup adapter tests to follow async/function resolving interface * Fixup all the serializer integration tests * Fixup service/repo integration tests * Fixup deleting acceptance test * Fixup some ent tests * Make sure nspaces passes the dc through for when thats important * ...aaaand acceptance nspaces with the extra dc param
2021-09-15 18:50:11 +00:00
optional = optional.filter(item => Boolean(item)).map(item => item.value || item, []);
temp.splice(...[1, 0].concat(optional));
url = temp.join('/');
}
return `${this.baseURL}${this.rootURL}${url}`;
}
/**
* Change URL takes an ember application URL
*/
changeURL(type, path) {
this.path = path;
const state = this.machine.state;
path = this.formatURL(path);
if (!state || state.path !== path) {
this.dispatch(type, path);
}
}
setURL(path) {
// this.optional = {};
this.changeURL('push', path);
}
replaceURL(path) {
this.changeURL('replace', path);
}
onUpdateURL(callback) {
this.callback = callback;
}
//
/**
* Dispatch takes a full actual browser URL with all the rootURL and optional
* params if they exist
*/
dispatch(event, path) {
const state = {
path: path,
uuid: _uuid(),
};
this.machine[`${event}State`](state, null, path);
// popstate listeners only run from a browser action not when a state change
// is called directly, so manually call the popstate listener.
// https://developer.mozilla.org/en-US/docs/Web/API/Window/popstate_event#the_history_stack
this.route({ state: state });
}
willDestroy() {
this.doc.defaultView.removeEventListener('popstate', this.route);
}
}