Created
March 13, 2019 20:20
-
-
Save jasonmit/13bb7641310bf8217d1e5f8be22081e6 to your computer and use it in GitHub Desktop.
Persisting query params
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { run } from '@ember/runloop'; | |
import { action } from '@ember-decorators/object'; | |
import storageFor from 'os-workflows/utils/storage-for-decorator'; | |
const { assign } = Object; | |
export function withQueryParamMemory(Klass) { | |
return class WithQueryParams extends Klass { | |
@storageFor('route-memory') | |
_memory; | |
// NOTE: paramsFor is re-implemented to provide the model hooks with the appropriate | |
// dynamic segments and query parameters (mimicking the default behavior) | |
paramsFor(routeName) { | |
const params = super.paramsFor(...arguments); | |
const restoredQueryParams = this._findStoredQueryParams( | |
routeName, | |
this._router._routerMicrolib.activeTransition | |
); | |
const mergedParams = { | |
...params, | |
...restoredQueryParams | |
}; | |
return mergedParams; | |
} | |
setupController(controller, model, transition) { | |
super.setupController(...arguments); | |
const restoredQueryParams = this._findStoredQueryParams( | |
this.routeName, | |
transition | |
); | |
run.schedule('afterRender', () => { | |
controller.setProperties(restoredQueryParams); | |
// Since we are deferring setting the query parameters (primarily so that they appear in the URL) | |
// we much notify the controller once it's ready. Logic that was previously done | |
// inside of the setupController hook will need to be moved into some listener for this | |
// event name. | |
controller.trigger('readyState'); | |
}); | |
} | |
_findStoredQueryParams(routeName /*, transition */) { | |
// TODO: any qps in the transition object should cause the | |
// restoration to bail out (return `null`) | |
const manifest = this._memory.get('queryParams'); | |
if (routeName in manifest) { | |
return manifest[routeName]; | |
} | |
return null; | |
} | |
@action | |
queryParamsDidChange(changed, preset, removed) { | |
const { controller, routeName } = this; | |
this._memory.set('queryParams', { | |
...this._memory.get('queryParams'), | |
[this.routeName]: { ...preset } | |
}); | |
this._recordQps(preset); | |
this._scheduleParachuteChangeEvent( | |
routeName, | |
controller, | |
assign({}, changed, removed) | |
); | |
return this._super(...arguments); | |
} | |
_recordQps(queryParams) { | |
this._memory.set('queryParams', { | |
...this._memory.get('queryParams'), | |
[this.routeName]: { ...queryParams } | |
}); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment