Merge pull request #877 from hashicorp/refactor-resource-filters

Refactor resource filters
This commit is contained in:
Randall Morey authored and GitHub committed 2021-12-08 17:09:32 -05:00
commit a7c5332a99
16 files changed
+295 -134

No files matched your search

@@ -1,92 +0,0 @@
/**
* A resource filter param is a concise way to express a route query parameter.
* Resource filter params abstract away a route's query parameter
* interface, treating a query param as a simple attribute on a route instance.
* Getting the attribute value is equivalent to looking up the associated query
* parameter. Setting the attribute is equivalent to transitioning to the route
* and passing the associated query parameter value.
*
* Additionally, resource filter params may declare `allowedValues`, an array
* containing the set of values the parameter may take. While unenforced,
* `allowedValues` are useful metadata about a resource filter and may be fetch
* via `ResourceFilterParamHelper`. An optional default value may be specified
* via `defaultValue` passed to the decorator.
*
* @see ResourceFilterParamHelper
*
* @example
*
* export default class MyRoute extends Route {
*
* @resourceFilterParam(['active', 'pending'], ['active'])
* status;
*
* @action
* changeStatus(status) {
* // Sets query param `filter-status` on the current route, which occurs
* // via a route transition.
* this.status = status;
* // Log the value of query param `filter-status`.
* log(this.status);
* }
* }
*
*/
export function resourceFilterParam(allowedValues, defaultValue) {
/**
* @param {object} target
* @param {string} name
* @param {object} descriptor
* @return {object{get, set}}
*/
return function (target, name /*, descriptor*/) {
const filterKey = `filter-${name}`;
const filterAllowedValuesKey = `filter-allowed-values-${name}`;
// If the route has no query params specified yet, declare them.
if (!Object.keys(target.queryParams).length) target.queryParams = {};
// If the route has no resource filters list specified yet, create one.
if (!target.resourceFilterParams) target.resourceFilterParams = [];
// Add the resource filter query parameter to the route. Resource filter
// param changes refresh the model but do not contribute to browser history.
// See https://guides.emberjs.com/release/routing/query-params/
target.queryParams[filterKey] = {
refreshModel: true,
replace: true,
};
// Note the name of this filter param.
target.resourceFilterParams.push(name);
// Store the allowed values for future lookup
// (via `ResourceFilterParamHelper`).
target[filterAllowedValuesKey] = allowedValues;
// Override the decorated attribute with a getter and setter.
return {
/**
* Returns the JSON-parsed query parameter value OR defaultValue.
*/
get() {
const value =
this.paramsFor(this.routeName)[filterKey] ||
JSON.stringify(defaultValue);
return value ? JSON.parse(value) : null;
},
/**
* Sets the resource filter param to the stringified representation
* of `value`. NOTE: this is equivalent to transitioning into the
* current route, changing the associated query param.
* @param value
*/
set(value) {
const queryParams = {};
queryParams[filterKey] = JSON.stringify(value);
this.transitionTo({ queryParams });
},
};
};
}
@@ -0,0 +1,251 @@
import EmberObject from '@ember/object';
import { getOwner } from '@ember/application';
import { typeOf } from '@ember/utils';
/**
* @param value
* @return {boolean} true if `value` is a function
*/
const isFunction = (value) => typeOf(value) === 'function';
/**
* Represents a filter on a specific route and maintains filter state.
* @class
*/
class RouteResourceFilter extends EmberObject {
// =attributes
route;
name;
defaultValue;
allowed;
serialize;
findBySerialized;
// =computed
/**
* Query parameter name where the selected value(s) for this filter are
* stored in the URL.
* @type {string}
*/
get filterKey() {
return `filter-${this.name}`;
}
/**
* The allowed values for this filter. See `allowed`.
* @type {?array}
*/
get allowedValues() {
if (isFunction(this.allowed)) {
return this.allowed(this.route);
}
return this.allowed;
}
/**
* Currently selected value(s) for this filter, deserialized from the value of
* the associated route query parameter.
* @type {?array}
*/
get value() {
const decodedValue =
this.route.paramsFor(this.route.routeName)[this.filterKey] ||
JSON.stringify(this.defaultValue);
const value = decodedValue ? JSON.parse(decodedValue) : null;
const deserializedValue = value
? value.map((serializedValue) =>
this.allowedValues.find((item) =>
this.deserializeValue(item, serializedValue)
)
)
: null;
return deserializedValue;
}
set value(value) {
const queryParams = {};
const serialized = value.map((value) => this.serializeValue(value));
queryParams[this.filterKey] = JSON.stringify(serialized);
this.route.transitionTo({ queryParams });
}
// =methods
/**
* Calls `serialize` (if set) on the passed value. Otherwise returns the
* value unaltered.
*/
serializeValue(value) {
if (this.serialize) {
return this.serialize(...arguments);
}
return value;
}
/**
* Tests if `item` is represented by `serializedValue` when deserializing
* items from the query string. If `findBySerialized` is unspecified,
* a simple equality test is used.
* @param item
* @param {string} serializedValue
* @return {boolean} item is represented by `serializedValue`
*/
deserializeValue(item, serializedValue) {
if (this.findBySerialized) {
return this.findBySerialized(...arguments);
}
return item === serializedValue;
}
// =static methods
/**
* Configures the specified route with a query parameter of `name` that, when
* changed, refreshes the route model and replaces history (rather than
* advancing history).
* @static
* @param {Route} routeClass
* @param {string} name
*/
static setupRouteQueryParams(routeClass, name) {
const filterKey = `filter-${name}`;
// If the route has no query params specified yet, declare them.
if (!Object.keys(routeClass.queryParams).length)
routeClass.queryParams = {};
// If the route has no resource filters list specified yet, create one.
if (!routeClass.resourceFilterParams) routeClass.resourceFilterParams = [];
// Add the resource filter query parameter to the route. Resource filter
// param changes refresh the model but do not contribute to browser history.
// See https://guides.emberjs.com/release/routing/query-params/
routeClass.queryParams[filterKey] = {
refreshModel: true,
replace: true,
};
}
/**
* Factory method to instantiate an instance of this class.
* @static
* @param {Route} routeInstance
* @param {string} name
* @param {array|function} allowed
* @param {?array} defaultValue
* @param {?function} serialize
* @param {?function} findBySerialized
* @return {RouteResourceFilter}
*/
static getOrCreateRouteResourceFilter(
routeInstance,
name,
allowed,
defaultValue,
serialize,
findBySerialized
) {
const owner = getOwner(routeInstance);
const containerKey = `resource-filter:${name}@${routeInstance.routeName}`;
const factory = owner.factoryFor(containerKey);
if (!factory) {
// create factory
class AppliedRouteResourceFilter extends this {
route = routeInstance;
name = name;
allowed = allowed;
defaultValue = defaultValue;
serialize = serialize;
findBySerialized = findBySerialized;
}
owner.register(containerKey, AppliedRouteResourceFilter);
}
const instance = owner.lookup(containerKey);
return instance;
}
}
/**
* This decorator provides a concise way to express a route resource filter.
* Resource filter params abstract away a route's query parameter
* interface, treating a query param as just an attribute on a route instance.
* Getting the attribute value is equivalent to looking up the associated query
* parameter. Setting the attribute is equivalent to transitioning to the route
* and passing the associated query parameter value.
*
* Additionally, resource filter params may declare `allowed`, an array
* (or function returning an array) containing the set of values the parameter
* may take. While unenforced, `allowed` are useful metadata about a resource
* filter and may be fetch via `ResourceFilterParamHelper`. An optional default
* value may be specified via `defaultValue` passed to the decorator.
*
* @see ResourceFilterParamHelper
*
* @example
*
* export default class MyRoute extends Route {
*
* @resourceFilter({
* allowed: ['active', 'pending'],
* defaultvalue: ['active'], // optional
* })
* status;
*
* @action
* changeStatus(status) {
* // Sets query param `filter-status` on the current route, which occurs
* // via a route transition.
* this.status = status;
* // Log the value of query param `filter-status`.
* log(this.status);
* }
* }
*
*/
export function resourceFilter({
allowed,
defaultValue,
serialize,
findBySerialized,
}) {
/**
* @param {object} target
* @param {string} name
* @param {object} descriptor
* @return {object{get, set}}
*/
return function (target, name /*, descriptor*/) {
RouteResourceFilter.setupRouteQueryParams(target, name);
let instance;
// Override the decorated attribute with a getter and setter.
return {
/**
* Returns the current value of the resource filter.
*/
get() {
instance = RouteResourceFilter.getOrCreateRouteResourceFilter(
this,
name,
allowed,
defaultValue,
serialize,
findBySerialized
);
return instance.value;
},
/**
* Sets the resource filter param to the stringified representation
* of `value`. NOTE: this is equivalent to transitioning into the
* current route, changing the associated query param.
* @param value
*/
set(value) {
instance.value = value;
},
};
};
}
@@ -11,11 +11,11 @@ import { action } from '@ember/object';
*
* @example
*
* {{#if (has-resource-filter-param-selections 'route.name' 'field')}}
* {{#if (has-resource-filter-selections 'route.name' 'field')}}
* Field has filter selections.
* {{/if}}
*/
export default class HasResourceFilterParamSelectionsHelper extends Helper {
export default class HasRouteResourceFilterSelectionsHelper extends Helper {
// =services
@service router;
@@ -44,14 +44,14 @@ export default class HasResourceFilterParamSelectionsHelper extends Helper {
/**
* Returns true if the specified route has a value set for
* any resource filter.
* any resource filter passed into the helper.
* @param {string} routeName
* @param {string[]} names - names of resource filter fields
* @return {boolean}
*/
compute([routeName]) {
compute([routeName, ...names]) {
const owner = getOwner(this);
const route = owner.lookup(`route:${routeName}`);
const names = route.resourceFilterParams;
const selectedValues = names.map((name) => route[name] || null).flat();
const anyTruthy = selectedValues.reduce(
(previousValue, currentValue) => previousValue || currentValue,
@@ -7,15 +7,15 @@ import { action } from '@ember/object';
* Use this helper to fetch the current value of a resource filter param,
* as well as its allowedValues.
*
* @see resourceFilterParam (decorator)
* @see resourceFilter (decorator)
*
* @example
*
* {{#with resource-filter-param 'status' as |param|}}
* {{#with resource-filter 'status' as |param|}}
* {{param.name}} / {{param.value}} / {{param.selectedValue}}
* {{/with}}
*/
export default class ResourceFilterParamHelper extends Helper {
export default class ResourceFilterHelper extends Helper {
// =services
@service router;
@@ -50,13 +50,9 @@ export default class ResourceFilterParamHelper extends Helper {
*/
compute([routeName, name]) {
const owner = getOwner(this);
// Filter options
const route = owner.lookup(`route:${routeName}`);
const filterAllowedValuesKey = `filter-allowed-values-${name}`;
const allowedValues = route[filterAllowedValuesKey];
// Selected filters
const rawValue = route[name];
const selectedValue = rawValue || null;
const containerKey = `resource-filter:${name}@${routeName}`;
const resourceFilter = owner.lookup(containerKey);
const { allowedValues, value: selectedValue } = resourceFilter;
return { name, allowedValues, selectedValue };
}
@@ -1 +0,0 @@
export { default } from 'core/decorators/resource-filter-param';
@@ -0,0 +1 @@
export { default } from 'core/decorators/resource-filter';
@@ -1 +0,0 @@
export { default } from 'core/helpers/has-resource-filter-param-selections';
@@ -0,0 +1 @@
export { default } from 'core/helpers/has-resource-filter-selections';
@@ -1 +0,0 @@
export { default } from 'core/helpers/resource-filter-param';
@@ -0,0 +1 @@
export { default } from 'core/helpers/resource-filter';
@@ -4,7 +4,7 @@ import { action } from '@ember/object';
import loading from 'ember-loading/decorator';
import { confirm } from 'core/decorators/confirm';
import { notifySuccess, notifyError } from 'core/decorators/notify';
import { resourceFilterParam } from 'core/decorators/resource-filter-param';
import { resourceFilter } from 'core/decorators/resource-filter';
export default class ScopesScopeAuthMethodsRoute extends Route {
// =services
@@ -17,7 +17,7 @@ export default class ScopesScopeAuthMethodsRoute extends Route {
// =attributes
@resourceFilterParam(['password', 'oidc']) type;
@resourceFilter({ allowed: ['password', 'oidc'] }) type;
// =methods
+6 -3
View File
@@ -6,7 +6,7 @@ import { task, timeout } from 'ember-concurrency';
import { A } from '@ember/array';
import { notifySuccess, notifyError } from 'core/decorators/notify';
import config from '../../../config/environment';
import { resourceFilterParam } from 'core/decorators/resource-filter-param';
import { resourceFilter } from 'core/decorators/resource-filter';
const POLL_TIMEOUT_SECONDS = config.sessionPollingTimeoutSeconds;
@@ -21,7 +21,10 @@ export default class ScopesScopeSessionsRoute extends Route {
// =attributes
@resourceFilterParam(['active', 'pending', 'canceling', 'terminated'], ['active','pending', 'canceling']) status;
@resourceFilter({
allowed: ['active', 'pending', 'canceling', 'terminated'],
defaultValue: ['active','pending', 'canceling']
}) status;
/**
* A simple Ember Concurrency-based polling task that refreshes the route
@@ -128,7 +131,7 @@ export default class ScopesScopeSessionsRoute extends Route {
filterBy(field, value) {
this[field] = value;
}
/**
* Clears and filter selections.
*/
@@ -39,13 +39,13 @@
{{#if
(or
@model
(has-resource-filter-param-selections 'scopes.scope.auth-methods')
(has-resource-filter-selections 'scopes.scope.auth-methods' 'type')
)
}}
<Rose::Toolbar>
<Rose::Form as |form|>
{{#with
(resource-filter-param 'scopes.scope.auth-methods' 'type')
(resource-filter 'scopes.scope.auth-methods' 'type')
as |filter|
}}
<Rose::Dropdown
@@ -74,7 +74,7 @@
{{/with}}
{{#if
(has-resource-filter-param-selections 'scopes.scope.auth-methods')
(has-resource-filter-selections 'scopes.scope.auth-methods' 'type')
}}
<Rose::Button
@style='inline-link-action'
@@ -207,8 +207,8 @@
</table.body>
</Rose::Table>
{{else if (has-resource-filter-param-selections
'scopes.scope.auth-methods'
{{else if (has-resource-filter-selections
'scopes.scope.auth-methods' 'type'
)}}
<Rose::Layout::Centered>
@@ -16,13 +16,13 @@
{{#if (feature-flag 'filter')}}
{{#if
(or
@model (has-resource-filter-param-selections 'scopes.scope.sessions')
@model (has-resource-filter-selections 'scopes.scope.sessions' 'type')
)
}}
<Rose::Toolbar>
<Rose::Form as |form|>
{{#with
(resource-filter-param 'scopes.scope.sessions' 'status')
(resource-filter 'scopes.scope.sessions' 'status')
as |filter|
}}
<Rose::Dropdown
@@ -51,7 +51,7 @@
{{/with}}
{{#if
(has-resource-filter-param-selections 'scopes.scope.sessions')
(has-resource-filter-selections 'scopes.scope.sessions' 'type')
}}
<Rose::Button
@style='inline-link-action'
@@ -136,7 +136,7 @@
</table.body>
</Rose::Table>
{{else if (has-resource-filter-param-selections 'scopes.scope.sessions')}}
{{else if (has-resource-filter-selections 'scopes.scope.sessions' 'type')}}
<Rose::Layout::Centered>
<Rose::Message @title={{t 'titles.no-results'}} as |message|>
<message.description>
@@ -4,7 +4,7 @@ import { task, timeout } from 'ember-concurrency';
import config from '../../../../config/environment';
import { action } from '@ember/object';
import { notifySuccess, notifyError } from 'core/decorators/notify';
import { resourceFilterParam } from 'core/decorators/resource-filter-param';
import { resourceFilter } from 'core/decorators/resource-filter';
const POLL_TIMEOUT_SECONDS = config.sessionPollingTimeoutSeconds;
@@ -18,7 +18,10 @@ export default class ScopesScopeProjectsSessionsRoute extends Route {
// =attributes
@resourceFilterParam(['active', 'pending', 'canceling', 'terminated'], ['active','pending', 'canceling']) status;
@resourceFilter({
allowed: ['active', 'pending', 'canceling', 'terminated'],
defaultValue: ['active','pending', 'canceling']
}) status;
/**
* A simple Ember Concurrency-based polling task that refreshes the route
@@ -100,7 +103,7 @@ export default class ScopesScopeProjectsSessionsRoute extends Route {
filterBy(field, value) {
this[field] = value;
}
/**
* Clears and filter selections.
*/
@@ -13,15 +13,15 @@
{{#if
(or
@model
(has-resource-filter-param-selections
'scopes.scope.projects.sessions'
(has-resource-filter-selections
'scopes.scope.projects.sessions' 'type'
)
)
}}
<Rose::Toolbar>
<Rose::Form as |form|>
{{#with
(resource-filter-param 'scopes.scope.projects.sessions' 'status')
(resource-filter 'scopes.scope.projects.sessions' 'status')
as |filter|
}}
<Rose::Dropdown
@@ -50,8 +50,8 @@
{{/with}}
{{#if
(has-resource-filter-param-selections
'scopes.scope.projects.sessions'
(has-resource-filter-selections
'scopes.scope.projects.sessions' 'type'
)
}}
<Rose::Button
@@ -142,8 +142,8 @@
{{/each}}
</table.body>
</Rose::Table>
{{else if (has-resource-filter-param-selections
'scopes.scope.projects.sessions'
{{else if (has-resource-filter-selections
'scopes.scope.projects.sessions' 'type'
)}}
<Rose::Layout::Centered>
<Rose::Message @title={{t 'titles.no-results'}} as |message|>