diff --git a/addons/core/addon/decorators/resource-filter-param.js b/addons/core/addon/decorators/resource-filter-param.js deleted file mode 100644 index b8395a20f..000000000 --- a/addons/core/addon/decorators/resource-filter-param.js +++ /dev/null @@ -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 }); - }, - }; - }; -} diff --git a/addons/core/addon/decorators/resource-filter.js b/addons/core/addon/decorators/resource-filter.js new file mode 100644 index 000000000..df84cb09a --- /dev/null +++ b/addons/core/addon/decorators/resource-filter.js @@ -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; + }, + }; + }; +} diff --git a/addons/core/addon/helpers/has-resource-filter-param-selections.js b/addons/core/addon/helpers/has-resource-filter-selections.js similarity index 84% rename from addons/core/addon/helpers/has-resource-filter-param-selections.js rename to addons/core/addon/helpers/has-resource-filter-selections.js index 6f6015078..3a026c5aa 100644 --- a/addons/core/addon/helpers/has-resource-filter-param-selections.js +++ b/addons/core/addon/helpers/has-resource-filter-selections.js @@ -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, diff --git a/addons/core/addon/helpers/resource-filter-param.js b/addons/core/addon/helpers/resource-filter.js similarity index 75% rename from addons/core/addon/helpers/resource-filter-param.js rename to addons/core/addon/helpers/resource-filter.js index e78ac20a7..1872a1d5d 100644 --- a/addons/core/addon/helpers/resource-filter-param.js +++ b/addons/core/addon/helpers/resource-filter.js @@ -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 }; } diff --git a/addons/core/app/decorators/resource-filter-param.js b/addons/core/app/decorators/resource-filter-param.js deleted file mode 100644 index 4e5cebc3c..000000000 --- a/addons/core/app/decorators/resource-filter-param.js +++ /dev/null @@ -1 +0,0 @@ -export { default } from 'core/decorators/resource-filter-param'; diff --git a/addons/core/app/decorators/resource-filter.js b/addons/core/app/decorators/resource-filter.js new file mode 100644 index 000000000..48ab848b6 --- /dev/null +++ b/addons/core/app/decorators/resource-filter.js @@ -0,0 +1 @@ +export { default } from 'core/decorators/resource-filter'; diff --git a/addons/core/app/helpers/has-resource-filter-param-selections.js b/addons/core/app/helpers/has-resource-filter-param-selections.js deleted file mode 100644 index b6ab1bc86..000000000 --- a/addons/core/app/helpers/has-resource-filter-param-selections.js +++ /dev/null @@ -1 +0,0 @@ -export { default } from 'core/helpers/has-resource-filter-param-selections'; diff --git a/addons/core/app/helpers/has-resource-filter-selections.js b/addons/core/app/helpers/has-resource-filter-selections.js new file mode 100644 index 000000000..26765e488 --- /dev/null +++ b/addons/core/app/helpers/has-resource-filter-selections.js @@ -0,0 +1 @@ +export { default } from 'core/helpers/has-resource-filter-selections'; diff --git a/addons/core/app/helpers/resource-filter-param.js b/addons/core/app/helpers/resource-filter-param.js deleted file mode 100644 index 8977c55f0..000000000 --- a/addons/core/app/helpers/resource-filter-param.js +++ /dev/null @@ -1 +0,0 @@ -export { default } from 'core/helpers/resource-filter-param'; diff --git a/addons/core/app/helpers/resource-filter.js b/addons/core/app/helpers/resource-filter.js new file mode 100644 index 000000000..573aa1050 --- /dev/null +++ b/addons/core/app/helpers/resource-filter.js @@ -0,0 +1 @@ +export { default } from 'core/helpers/resource-filter'; diff --git a/ui/admin/app/routes/scopes/scope/auth-methods.js b/ui/admin/app/routes/scopes/scope/auth-methods.js index e83a95911..491cdd44d 100644 --- a/ui/admin/app/routes/scopes/scope/auth-methods.js +++ b/ui/admin/app/routes/scopes/scope/auth-methods.js @@ -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 diff --git a/ui/admin/app/routes/scopes/scope/sessions.js b/ui/admin/app/routes/scopes/scope/sessions.js index 525cfdf1d..29a0d87a5 100644 --- a/ui/admin/app/routes/scopes/scope/sessions.js +++ b/ui/admin/app/routes/scopes/scope/sessions.js @@ -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. */ diff --git a/ui/admin/app/templates/scopes/scope/auth-methods/index.hbs b/ui/admin/app/templates/scopes/scope/auth-methods/index.hbs index d6075980e..ea12808c3 100644 --- a/ui/admin/app/templates/scopes/scope/auth-methods/index.hbs +++ b/ui/admin/app/templates/scopes/scope/auth-methods/index.hbs @@ -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') ) }} {{#with - (resource-filter-param 'scopes.scope.auth-methods' 'type') + (resource-filter 'scopes.scope.auth-methods' 'type') as |filter| }} - {{else if (has-resource-filter-param-selections - 'scopes.scope.auth-methods' + {{else if (has-resource-filter-selections + 'scopes.scope.auth-methods' 'type' )}} diff --git a/ui/admin/app/templates/scopes/scope/sessions/index.hbs b/ui/admin/app/templates/scopes/scope/sessions/index.hbs index d5052b1ee..ec412bb5e 100644 --- a/ui/admin/app/templates/scopes/scope/sessions/index.hbs +++ b/ui/admin/app/templates/scopes/scope/sessions/index.hbs @@ -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') ) }} {{#with - (resource-filter-param 'scopes.scope.sessions' 'status') + (resource-filter 'scopes.scope.sessions' 'status') as |filter| }} - {{else if (has-resource-filter-param-selections 'scopes.scope.sessions')}} + {{else if (has-resource-filter-selections 'scopes.scope.sessions' 'type')}} diff --git a/ui/desktop/app/routes/scopes/scope/projects/sessions.js b/ui/desktop/app/routes/scopes/scope/projects/sessions.js index f190e1b75..12618d741 100644 --- a/ui/desktop/app/routes/scopes/scope/projects/sessions.js +++ b/ui/desktop/app/routes/scopes/scope/projects/sessions.js @@ -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. */ diff --git a/ui/desktop/app/templates/scopes/scope/projects/sessions/index.hbs b/ui/desktop/app/templates/scopes/scope/projects/sessions/index.hbs index 2ebe5491b..798489e7e 100644 --- a/ui/desktop/app/templates/scopes/scope/projects/sessions/index.hbs +++ b/ui/desktop/app/templates/scopes/scope/projects/sessions/index.hbs @@ -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' ) ) }} {{#with - (resource-filter-param 'scopes.scope.projects.sessions' 'status') + (resource-filter 'scopes.scope.projects.sessions' 'status') as |filter| }} - {{else if (has-resource-filter-param-selections - 'scopes.scope.projects.sessions' + {{else if (has-resource-filter-selections + 'scopes.scope.projects.sessions' 'type' )}}