@coolon/angular-ui-powerups 14.27.0 → 14.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/esm2020/lib/components/tables/abstract-table.component.mjs +2 -4
  2. package/esm2020/lib/place/components/abstract-place-navigation.component.mjs +14 -15
  3. package/esm2020/lib/place/components/place-outlet/place-outlet.component.mjs +27 -26
  4. package/esm2020/lib/place/exports.mjs +3 -2
  5. package/esm2020/lib/place/guards/place.guard.mjs +49 -30
  6. package/esm2020/lib/place/navigation/session/interactions/navigating-during-interaction.mjs +2 -2
  7. package/esm2020/lib/place/navigation/session/navigating.mjs +7 -3
  8. package/esm2020/lib/place/navigation/session/navigation-context.mjs +1 -1
  9. package/esm2020/lib/place/navigation/session/navigation-session.mjs +22 -9
  10. package/esm2020/lib/place/navigation/session/pop-state-navigation.mjs +2 -2
  11. package/esm2020/lib/place/place-component.mjs +2 -2
  12. package/esm2020/lib/place/place-definition.mjs +62 -3
  13. package/esm2020/lib/place/place-history.mjs +24 -17
  14. package/esm2020/lib/place/place-router.mjs +48 -60
  15. package/esm2020/lib/place/route/parameter-definition.mjs +2 -2
  16. package/esm2020/lib/place/route/parameter-sanitiser.mjs +1 -1
  17. package/esm2020/lib/place/route/visit-segment-sanitiser.mjs +41 -0
  18. package/esm2020/lib/place/url-service.mjs +3 -3
  19. package/esm2020/lib/place/url-snapshot.mjs +26 -23
  20. package/esm2020/lib/place/visit-segment.mjs +86 -0
  21. package/esm2020/lib/place/visit.mjs +78 -55
  22. package/fesm2015/coolon-angular-ui-powerups.mjs +2079 -1883
  23. package/fesm2015/coolon-angular-ui-powerups.mjs.map +1 -1
  24. package/fesm2020/coolon-angular-ui-powerups.mjs +3317 -3123
  25. package/fesm2020/coolon-angular-ui-powerups.mjs.map +1 -1
  26. package/lib/place/components/abstract-place-navigation.component.d.ts +2 -0
  27. package/lib/place/components/place-outlet/place-outlet.component.d.ts +3 -5
  28. package/lib/place/exports.d.ts +2 -1
  29. package/lib/place/guards/place.guard.d.ts +4 -1
  30. package/lib/place/navigation/session/navigation-context.d.ts +3 -3
  31. package/lib/place/navigation/session/navigation-session.d.ts +7 -4
  32. package/lib/place/place-component.d.ts +3 -3
  33. package/lib/place/place-definition.d.ts +20 -15
  34. package/lib/place/place-history.d.ts +17 -11
  35. package/lib/place/place-router.d.ts +12 -21
  36. package/lib/place/route/parameter-definition.d.ts +2 -2
  37. package/lib/place/route/parameter-sanitiser.d.ts +2 -2
  38. package/lib/place/route/{visit-sanitiser.d.ts → visit-segment-sanitiser.d.ts} +3 -3
  39. package/lib/place/url-service.d.ts +2 -2
  40. package/lib/place/url-snapshot.d.ts +8 -7
  41. package/lib/place/visit-segment.d.ts +24 -0
  42. package/lib/place/visit.d.ts +22 -25
  43. package/package.json +1 -1
  44. package/esm2020/lib/place/route/visit-sanitiser.mjs +0 -41
  45. package/schematics/place-routes/templates/place-destinations.ts.template +0 -19
  46. package/schematics/place-routes/templates/place-visits.ts.template +0 -16
@@ -39,17 +39,17 @@ import { MatTableModule } from '@angular/material/table';
39
39
  import * as i4 from '@angular/material/tooltip';
40
40
  import { MatTooltipModule } from '@angular/material/tooltip';
41
41
  import * as i1$3 from '@coolon/pectin';
42
- import { GarbageCollector, DelegatingValueModel, assert, UnaryCommand, lang, Dsl, Logger, TrackExternal, ValueModel, StoreInValueModel, Command, MutableListModel, StoreInListModel, Disposable, DelegatingListModel, MutableValueModel, FocusManager, EventListenerList, Form, Guard, Binding, DebugContext, ListModel, Functions, HasDelegate, MultipleSelectionModel, SelectionModel, AbstractComputedListModel, DirtyTrackingForm, DelegatingSelectionModel, PageController, PagedListModel, ComputedListModel, Deferred } from '@coolon/pectin';
42
+ import { GarbageCollector, DelegatingValueModel, assert, UnaryCommand, lang, Dsl, Logger, TrackExternal, ValueModel, StoreInValueModel, Command, MutableListModel, StoreInListModel, Disposable, DelegatingListModel, MutableValueModel, FocusManager, EventListenerList, Form, Guard, Binding, DebugContext, ListModel, Functions, HasDelegate, MultipleSelectionModel, SelectionModel, AbstractComputedListModel, DirtyTrackingForm, DelegatingSelectionModel, PageController, PagedListModel, ComputedListModel, Deferred, Trace } from '@coolon/pectin';
43
43
  import { __decorate, __param, __metadata, __awaiter } from 'tslib';
44
44
  import escapeStringRegexp from 'escape-string-regexp';
45
- import { isEmpty, isString, isFunction, isNil, isInteger, isEqual, uniq, last, first, isObject, isNumber, isNaN as isNaN$1 } from 'lodash';
45
+ import { isEmpty, isString, isFunction, isNil, isInteger, isObject, isEqual, join, uniq, last as last$1, first, isNumber, isNaN as isNaN$1 } from 'lodash';
46
46
  import * as i1 from '@angular/platform-browser';
47
47
  import { marked } from 'marked';
48
48
  import { lang as lang$1, assert as assert$1, Stringy, Klass, Opts } from '@coolon/typescript-utilities';
49
49
  import { Enum } from 'typescript-string-enums';
50
50
  import { Memoize } from '@typescript-plus/fast-memoize-decorator';
51
51
  import * as i5 from '@angular/material/core';
52
- import { isEmpty as isEmpty$1, isFunction as isFunction$1, isNil as isNil$1, findLast } from 'lodash-es';
52
+ import { isEmpty as isEmpty$1, isFunction as isFunction$1, isNil as isNil$1, last, findLast } from 'lodash-es';
53
53
  import produce from 'immer';
54
54
  import ResizeObserver from 'resize-observer-polyfill';
55
55
  import * as i5$1 from '@angular/cdk/a11y';
@@ -59,11 +59,12 @@ import { FlexModule, GridModule } from '@angular/flex-layout';
59
59
  import * as i1$6 from '@angular/material/dialog';
60
60
  import { MatDialogModule, MAT_DIALOG_DEFAULT_OPTIONS } from '@angular/material/dialog';
61
61
  import * as i1$4 from '@angular/router';
62
- import { UrlSegment, NavigationStart, NavigationEnd, NavigationError, NavigationCancel, RouterModule, ActivatedRouteSnapshot } from '@angular/router';
62
+ import { ActivatedRouteSnapshot, UrlSegment, NavigationStart, NavigationEnd, NavigationError, NavigationCancel, RouterModule } from '@angular/router';
63
+ import { Memoize as Memoize$1 } from 'typescript-memoize';
64
+ import 'reflect-metadata';
63
65
  import * as i1$5 from '@angular/cdk/overlay';
64
66
  import * as i3$2 from '@angular/material/list';
65
67
  import { MatListModule } from '@angular/material/list';
66
- import 'reflect-metadata';
67
68
  import { style, query, group, animate, trigger, transition } from '@angular/animations';
68
69
 
69
70
  class CommandDirective extends GarbageCollector {
@@ -2901,13 +2902,11 @@ class AbstractTableComponent extends DisposableComponent {
2901
2902
  return this.identityOf ? this.identityOf(item) : index;
2902
2903
  };
2903
2904
  const { chain, when } = Dsl.disposeWith(this);
2904
- // this.rows$ = chain(this.dataSource$)
2905
- // .
2906
2905
  this._visibleRows$.setDelegate(this._dataSource$);
2907
2906
  when(chain(this._dataSource$).first()).becomesTruthy(it => {
2908
2907
  if (it === this.identityOf(it)) {
2909
2908
  console.warn("Table model identity function is using reference equality. This can cause lots of table re-rendering", {
2910
- row: it
2909
+ rowType: it
2911
2910
  });
2912
2911
  }
2913
2912
  }, { once: true });
@@ -6088,719 +6087,963 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.1.2", ngImpor
6088
6087
  type: Input
6089
6088
  }] } });
6090
6089
 
6091
- /**
6092
- * This class handles the logic around canDeactivate for a given router state transition. It's core responsibilities are:
6093
- * 1. Ensure we only ask the component to deactivate once on a given navigation cycle (since visit sanitisation can result in multiple round trips to through the router.)
6094
- * 2. Ensure only the primary place component is asked when there are nested places. The primary component is the one at the top
6095
- * of the routing change tree.
6096
- * 3. Automatically handle standard interaction scenarios on the components behalf.
6097
- */
6098
- class PlaceComponentDeactivationHandler {
6099
- constructor(component, navigationSession, isPrimaryComponent) {
6100
- this.component = component;
6101
- this.navigationSession = navigationSession;
6102
- this.isPrimaryComponent = isPrimaryComponent;
6103
- assert.notNil(component);
6090
+ const PARAMETER_DEFINITION_KEY = Symbol('parameterDefinition');
6091
+ class ParameterDefinition {
6092
+ constructor(propertyName, options, urlFormat) {
6093
+ this.propertyName = propertyName;
6094
+ this.urlFormat = urlFormat;
6095
+ this.options = Opts.get(options);
6096
+ this.remember = this.options.getOptional('remember', false);
6097
+ this.defaultValue = this.options.getOptional('defaultValue', null);
6104
6098
  }
6105
- get routerInteractionAdapter() {
6106
- return this.navigationSession.interactionServiceAdapter;
6099
+ get name() {
6100
+ return this.options.getOptional('as', this.propertyName);
6107
6101
  }
6108
- get urlService() {
6109
- return this.navigationSession.urlService;
6102
+ // @Trace()
6103
+ get isRouteParameter() {
6104
+ return !!this.urlFormat;
6110
6105
  }
6111
- get placeDefinition() {
6112
- return this.component.placeDefinition;
6106
+ createBackingModel() {
6107
+ const model = this.backingModelFactory();
6108
+ model[PARAMETER_DEFINITION_KEY] = this;
6109
+ return model;
6110
+ }
6111
+ getOptionValue(key) {
6112
+ return this.options.getOptional(key, null);
6113
6113
  }
6114
6114
  // @Trace()
6115
- canDeactivate(currentUrl, nextState) {
6115
+ sanitise(value, visit, placeHistory, injector, isPopState) {
6116
6116
  return __awaiter(this, void 0, void 0, function* () {
6117
- // We'll get called multiple times if there's any parameter sanitisation so
6118
- // we always return true if we accepted promise from a previous cycle of the current
6119
- // navigation session.
6120
- if (!this.canDeactivatePromise) {
6121
- // console.log(`creating deactivate promise for -> ${this.component.constructor.name}`);
6122
- this.canDeactivatePromise = this.canDeactivateComponent(currentUrl, nextState);
6123
- }
6124
- return this.canDeactivatePromise;
6117
+ // console.log(`sanitise(${this.propertyName})`)
6118
+ value = yield this.sanitiseMissing(visit, placeHistory, value);
6119
+ value = yield this.runCustomSanitiser(value, visit, placeHistory, injector, isPopState);
6120
+ return value;
6125
6121
  });
6126
6122
  }
6127
- // @Trace()
6128
- canDeactivateComponent(currentUrl, nextState) {
6123
+ runCustomSanitiser(value, visit, placeHistory, injector, isPopState) {
6129
6124
  return __awaiter(this, void 0, void 0, function* () {
6130
- // Automatically cancel any active activities if the navigation session was triggered by the back button.
6131
- // If we handled more than just the pop state then it leads to the UI ignoring clicks and just cancelling things which is deeply disconcerting.
6132
- if (this.navigationSession.isPopState) {
6133
- if (this.isPrimaryComponent && this.routerInteractionAdapter.isModalActive()) {
6134
- const routeIds = this.urlService.getActiveInteractionIdsFromUrl(nextState.url);
6135
- const currentIds = this.routerInteractionAdapter.getActiveInteractionContextIds();
6136
- if (!isEqual(currentIds, routeIds)) { // why am I checking this????
6137
- yield this.routerInteractionAdapter.cancelCurrentModalInteraction();
6138
- return false;
6139
- }
6140
- }
6141
- else {
6142
- // check if the component has an in place interaction
6143
- if (this.routerInteractionAdapter.isComponentInteracting(this.component)) {
6144
- yield this.routerInteractionAdapter.cancelComponentInteraction(this.component);
6145
- return false;
6146
- }
6147
- }
6148
- }
6149
- // No interaction in progress, so ask the component .
6150
- // This may start an interaction, hence checking the interaction context before now. I.e. if the place pops up the dialog, and
6151
- // the user clicks back again, we'll re-enter here and go bang when the component tries to open another dialog.
6152
- if (this.isGoingToADifferentPlace(nextState)) {
6153
- const canLeave = yield this.component._canLeavePlace(this.navigationSession.canDeactivateInteractionContext);
6154
- // The component has an active interaction but no deactivation hook. Rather than guessing what to do
6155
- // we'll just cancel the navigation and print a warning.
6156
- if (canLeave && this.routerInteractionAdapter.isComponentInteracting(this.component)) {
6157
- console.warn('Route changed while component has active interaction, cancelling navigation');
6158
- return false;
6125
+ const customSanitiser = this.prepareCustomSanitiser(injector);
6126
+ return customSanitiser ? customSanitiser.sanitise(value, visit, injector) : value;
6127
+ });
6128
+ }
6129
+ sanitiseMissing(visit, placeHistory, value) {
6130
+ if (this.isMissingFrom(visit)) {
6131
+ const returningFromSomewhereElse = !placeHistory.lastVisitIncluded(visit.placeDefinition);
6132
+ if (returningFromSomewhereElse) {
6133
+ const lastKnownVisit = placeHistory.getMostRecentVisitSegmentFor(visit.placeDefinition);
6134
+ if (this.remember && lastKnownVisit) {
6135
+ value = lastKnownVisit.getParameterValue(this);
6159
6136
  }
6160
- return canLeave;
6161
- }
6162
- else {
6163
- // either an interaction or visit parameter change.
6164
- return yield this.component._canChangeRouteParameters(this.navigationSession.canDeactivateInteractionContext, nextState);
6165
6137
  }
6166
- });
6138
+ }
6139
+ return this.isEmptyValue(value) ? this.defaultValue : value;
6167
6140
  }
6168
- isGoingToADifferentPlace(nextState) {
6169
- // Because places with a route-id cover two route segments we get asked to deactivate
6170
- // if the route id is added or removed. So if our path is still present the url
6171
- // then we shouldn't deactivate the place.
6172
- return !nextState.includesPathOf(this.component.placeDefinition);
6141
+ prepareCustomSanitiser(injector) {
6142
+ const customSanitiser = this.options.getOptional('sanitiser', null);
6143
+ if (isFunction(customSanitiser)) {
6144
+ return injector.get(customSanitiser);
6145
+ }
6146
+ if (isObject(customSanitiser)) {
6147
+ return isFunction(customSanitiser['sanitise']) ?
6148
+ customSanitiser :
6149
+ lang$1.illegalState(`expected @VisitParameter({sanitiser: ...}) for ${this.propertyName} to be a constructor or instance of ParameterSanitiser, got: ` + customSanitiser);
6150
+ }
6151
+ return undefined;
6152
+ }
6153
+ isMissingFrom(visit) {
6154
+ return !visit.hasParameter(this);
6173
6155
  }
6174
6156
  }
6175
-
6176
- /**
6177
- * Transient states
6178
- */
6179
- class NavigationSession extends GarbageCollector {
6180
- constructor(context, startingUrl) {
6181
- super();
6182
- this.context = context;
6183
- this.startingUrl = startingUrl;
6184
- this.debugPropertyKeys = [];
6185
- this._visits = new Map();
6186
- this.componentDeactivationHandlers = new Map();
6187
- // TODO: can I get away without creating one every time?
6188
- this._interactionContext = this.context.routerInteractionAdapter.createExclusiveInteractionContext();
6189
- this.onDispose(() => {
6190
- // the interaction context can be detached during the back button cancellation state transition
6191
- // as the transition is synchronous and activityCancellation isn't. Otherwise dispose will be
6192
- // called before the context has been cancelled. It might be work having the interaction context
6193
- // automatically cancel if the context is disposed so we don't have worry about detaching etc.
6194
- if (this._interactionContext) {
6195
- this._interactionContext.dispose(); // or do something like cancelAndDispose?
6196
- }
6197
- });
6157
+ (function (ParameterDefinition) {
6158
+ class RouteId extends ParameterDefinition {
6159
+ constructor() {
6160
+ super(...arguments);
6161
+ this.isRouteId = true;
6162
+ this.isArray = false;
6163
+ this.backingModelFactory = () => new MutableValueModel();
6164
+ }
6165
+ isEmptyValue(value) {
6166
+ return isNil(value);
6167
+ }
6168
+ hasChanged(a, b) {
6169
+ return a !== b;
6170
+ }
6198
6171
  }
6199
- get isInteractionSync() {
6200
- return false;
6172
+ ParameterDefinition.RouteId = RouteId;
6173
+ class ValueParameter extends ParameterDefinition {
6174
+ constructor() {
6175
+ super(...arguments);
6176
+ this.isRouteId = false;
6177
+ this.isArray = false;
6178
+ this.backingModelFactory = () => new MutableValueModel();
6179
+ }
6180
+ isEmptyValue(value) {
6181
+ return isNil(value);
6182
+ }
6183
+ hasChanged(a, b) {
6184
+ return a !== b;
6185
+ }
6201
6186
  }
6202
- get name() {
6203
- return this.constructor.name;
6187
+ ParameterDefinition.ValueParameter = ValueParameter;
6188
+ class ArrayParameter extends ParameterDefinition {
6189
+ constructor(parameterName, options, urlFormat) {
6190
+ super(parameterName, options, urlFormat);
6191
+ this.isRouteId = false;
6192
+ this.isArray = true;
6193
+ this.backingModelFactory = () => new MutableListModel();
6194
+ }
6195
+ isEmptyValue(value) {
6196
+ return isNil(value) || value.length < 1;
6197
+ }
6198
+ hasChanged(a, b) {
6199
+ return !isEqual(a, b);
6200
+ }
6204
6201
  }
6205
- get urlService() {
6206
- return this.context.urlService;
6202
+ ParameterDefinition.ArrayParameter = ArrayParameter;
6203
+ function get(model) {
6204
+ const parameterDefinition = model[PARAMETER_DEFINITION_KEY];
6205
+ if (!parameterDefinition) {
6206
+ lang$1.illegalArgument('model hasn\'t been annotated with @VisitParameter, @VisitParameterList or @RouteId');
6207
+ }
6208
+ return parameterDefinition;
6207
6209
  }
6208
- get interactionServiceAdapter() {
6209
- return this.context.routerInteractionAdapter;
6210
+ ParameterDefinition.get = get;
6211
+ })(ParameterDefinition || (ParameterDefinition = {}));
6212
+
6213
+ class PlaceDefinition {
6214
+ constructor(component, path, authenticate, role, data, routeParameters, children, redirectToFirstChild) {
6215
+ this.component = component;
6216
+ this.path = path;
6217
+ this.authenticate = authenticate;
6218
+ this.role = role;
6219
+ this.data = data;
6220
+ this.routeParameters = routeParameters;
6221
+ this.children = children;
6222
+ this.redirectToFirstChild = redirectToFirstChild;
6223
+ this.children.forEach(it => it.setParent(this));
6210
6224
  }
6211
- storeVisit(visit) {
6212
- // console.log(`Storing visit for ${visit.placeDefinition.component.name}`, {visit});
6213
- this._visits.set(visit.placeDefinition, visit);
6225
+ ancestors() {
6226
+ return this.parent ? this.parent.ancestors().concat([this.parent]) : [];
6214
6227
  }
6215
- getVisitFor(placeDef) {
6216
- const visit = this._visits.get(placeDef);
6217
- // console.log(`Getting visit for ${placeDef.component.name}`, {visit});
6218
- return visit;
6228
+ ancestorsAndSelf() {
6229
+ return this.ancestors().concat(this);
6219
6230
  }
6220
- get canDeactivateInteractionContext() {
6221
- return this._interactionContext;
6231
+ setParent(parent) {
6232
+ assert.isNil(this._parent);
6233
+ this._parent = parent;
6222
6234
  }
6223
- notifyActive() {
6224
- // noop.
6235
+ get parent() {
6236
+ return this._parent;
6225
6237
  }
6226
- onRouterStarted(event) {
6227
- // navigation sessions can have many cancel start cycles due to place guard redirects
6228
- this.ignore(event);
6238
+ isRoot() {
6239
+ return !this._parent;
6229
6240
  }
6230
- // @Trace()
6231
- onUrlChange(url) {
6232
- // Normally we just ignore these but they are the only way of detecting if the back button
6233
- // was clicked during a canDeactivate promise.
6234
- // 1. a route is in progress and awaiting a canDeactivateGuard
6235
- // 2. the user the clicks the back button.
6236
- // So to handle that scenario we need to check if we've got a can deactivate interaction in
6237
- // progress and the do the appropriate clean up.
6238
- if (this.canDeactivateInteractionContext && this.canDeactivateInteractionContext.isActive()) {
6239
- this.cancelCanDeactivateInteraction(url);
6240
- }
6241
+ hasParent() {
6242
+ return !this.parent;
6241
6243
  }
6242
- onPopState(event) {
6243
- return this.illegalTransition(event);
6244
+ hasChildren() {
6245
+ return !isEmpty(this.children);
6244
6246
  }
6245
- onRouterCancelled(event) {
6246
- return this.illegalTransition(event);
6247
+ findChild(predicate) {
6248
+ return this.children.find(predicate);
6247
6249
  }
6248
- onRouterError(event) {
6249
- return this.illegalTransition(event);
6250
+ hasRouteId() {
6251
+ return !!this.getRouteIdParameterDef();
6250
6252
  }
6251
- onRouterEnd(event) {
6252
- return this.illegalTransition(event);
6253
+ getRouteIdParameterDef() {
6254
+ return this.routeParameters.find(p => p.isRouteId);
6253
6255
  }
6254
- getVisits() {
6255
- return Array.from(this._visits.values());
6256
+ getRouteParameterDefs(includeRouteId = false) {
6257
+ return this.getVisitParameterDefs({ includeRouteId, includeRouteParameters: true });
6256
6258
  }
6257
- illegalTransition(message) {
6258
- return lang.illegalState(`${message.toString()} not supported by ${this.toString()}`);
6259
- }
6260
- currentRouterUrl() {
6261
- return this.urlService.getCurrentRouterUrl();
6262
- }
6263
- resetBrowserLocation(url, options = { replaceCurrent: false }) {
6264
- // console.log(`---> resetting browser location to: ${url}`);
6265
- this.urlService.resetBrowserLocation(url, options);
6259
+ getVisitParameterDefs(include) {
6260
+ const opts = Opts.get(include);
6261
+ // includes
6262
+ const includeRouteId = !include || opts.getOptional('includeRouteId', false);
6263
+ const includeRouteParameters = !include || opts.getOptional('includeRouteParameters', false);
6264
+ const includeNonRouteParameters = !include || opts.getOptional('includeNonRouteParameters', false);
6265
+ return this.routeParameters.filter(p => {
6266
+ return (includeRouteId && p.isRouteId)
6267
+ || (includeRouteParameters && p.isRouteParameter && !p.isRouteId) // route id is included in the line above
6268
+ || (includeNonRouteParameters && !p.isRouteParameter);
6269
+ });
6266
6270
  }
6267
- // @Trace()
6268
- repairBrowserHistoryAndUrlAfterGuardCancellation(poppedHistoryToReplace, activeUrl) {
6269
- // Important: I tried to perform this fix at a later point int he routing cycle but it created all kinds of
6270
- // strangeness.
6271
- Logger.get(this).info("WORK-AROUND: Updating browser location after pop state - see angular issue #13586");
6272
- // console.log(`replacing ${this.urlService.getCurrentLocationUrlSnapshot().url} with ${poppedHistoryToReplace}`);
6273
- this.urlService.resetBrowserLocation(poppedHistoryToReplace, { replaceCurrent: true });
6274
- // console.log(`pushing ${activeUrl} back onto the history.`);
6275
- this.urlService.resetBrowserLocation(activeUrl, { replaceCurrent: false });
6271
+ getPlaceData(key, defaultValue) {
6272
+ return this.data ?
6273
+ isNil(this.data[key]) ? defaultValue : this.data[key] :
6274
+ defaultValue;
6276
6275
  }
6277
- ignore(event, reason) {
6278
- reason = reason ? ` -> ${reason}` : "";
6279
- // Logger.get(this).info(`Ignoring router event${reason}: ${event.constructor.name} -> ${event.url} :: ${this.toString()}`);
6276
+ searchPlaceData(keys, defaultValue) {
6277
+ if (this.data) {
6278
+ const found = keys.find(key => !isNil(this.data[key]));
6279
+ return found ? this.data[found] : defaultValue;
6280
+ }
6281
+ else {
6282
+ return defaultValue;
6283
+ }
6280
6284
  }
6281
- toString() {
6282
- return `${this.constructor.name}(${this.debugState()})`;
6285
+ getRouteIdFrom(visit) {
6286
+ const routeIdParameterDef = this.getRouteIdParameterDef();
6287
+ return routeIdParameterDef ? visit.getParameterValue(routeIdParameterDef) : null;
6283
6288
  }
6284
- debugState(properties) {
6285
- return (properties || this.debugPropertyKeys).map(p => {
6286
- return `${p}: ${this[p]}`;
6287
- }).join(", ");
6289
+ getFormattedRouteId(visit) {
6290
+ // Note: RouteIds are always present in the url and are just empty strings when not defined. This is
6291
+ // mandated by the fact that redirects from <path> to <path>/:id always include the id parameter as
6292
+ // an empty string.
6293
+ return visit.hasRouteId() ? this.getRouteIdParameterDef().urlFormat.format(visit.getRouteId()) : "";
6288
6294
  }
6289
- canDeactivatePlace(component, currentUrl, nextUrl) {
6290
- return __awaiter(this, void 0, void 0, function* () {
6291
- // console.log(`---> canDeactivatePlace(${component.placeDefinition.path}, ${currentUrl.url} -> ${nextUrl.url})`);
6292
- // lookup the handler and create it if we've not seen it yet
6293
- let handler = this.componentDeactivationHandlers.get(component);
6294
- if (!handler) {
6295
- const isPrimaryHandler = this.componentDeactivationHandlers.size === 0; // only primary handler cancels the app model interations
6296
- handler = new PlaceComponentDeactivationHandler(component, this, isPrimaryHandler);
6297
- this.componentDeactivationHandlers.set(component, handler);
6295
+ // @Trace()
6296
+ getFormattedRouteParameters(visit, includeRouteId = false) {
6297
+ const result = {};
6298
+ this.getVisitParameterDefs({
6299
+ includeRouteId, includeRouteParameters: true
6300
+ }).forEach(def => {
6301
+ const value = visit.getParameterValue(def);
6302
+ if (!def.isEmptyValue(value)) {
6303
+ if (def.isArray) {
6304
+ assert.isArray(value);
6305
+ result[def.name] = value.map(v => def.urlFormat.format(v));
6306
+ }
6307
+ else {
6308
+ assert.isFalsey(Array.isArray(value));
6309
+ result[def.name] = def.urlFormat.format(value);
6310
+ }
6298
6311
  }
6299
- return handler.canDeactivate(currentUrl, nextUrl).then(result => {
6300
- // console.log(`<--- canDeactivatePlace(${component.placeDefinition.path}): ${result}`);
6301
- return result;
6302
- }).catch(error => {
6303
- throw error;
6304
- });
6305
6312
  });
6313
+ return result;
6306
6314
  }
6307
- cancelCanDeactivateInteraction(newUrl) {
6308
- Logger.get(this).info(`back button pressed during navigation session interaction promise`);
6309
- // detach the interaction from the session so it doesn't get disposed until the activity has finished
6310
- // all it's things.
6311
- const canDeactivateInteractionContext = this.detachCanDeactivateInteractionContext();
6312
- // TODO: I need to make the exclusive interaction context disallow nested activities or
6313
- // that would mess things up entirely. Or, can I do a context.abortAll().then(..)
6314
- Logger.get(this).info("cancelling current navigation activity..");
6315
- canDeactivateInteractionContext.cancelActiveActivity().then(() => {
6316
- canDeactivateInteractionContext.dispose();
6315
+ getNonRouteParameters(visit) {
6316
+ const result = {};
6317
+ this.getVisitParameterDefs({ includeNonRouteParameters: true }).forEach(def => {
6318
+ const value = visit.getParameterValue(def);
6319
+ if (!def.isEmptyValue(value)) {
6320
+ result[def.name] = value;
6321
+ }
6317
6322
  });
6318
- this.handleCanDeactivateCancelledEventScenario(newUrl);
6323
+ return result;
6319
6324
  }
6320
- reinstateUrlAfterAngularChangedItOnCancellation(url) {
6321
- // Angular calls _this.resetUrlToCurrentUrlTree() on cancelling and fucks our history.
6322
- // So this means that the top of the stack is the url we want to go back to, and not the one that was on
6323
- // it before the cancel event fired.
6324
- // So we need to:
6325
- // - replace the just inserted url with the one that used to be there.
6326
- // - push our actual url back onto the top of the stack.
6327
- this.resetBrowserLocation(url, { replaceCurrent: true });
6325
+ // @Trace()
6326
+ parseRouteParams(params) {
6327
+ const result = {};
6328
+ this.getVisitParameterDefs({
6329
+ includeRouteId: true,
6330
+ includeRouteParameters: true,
6331
+ includeNonRouteParameters: false
6332
+ }).forEach(def => {
6333
+ // params will return null for non existent names
6334
+ if (params.has(def.name)) {
6335
+ if (def.isArray) {
6336
+ // const values = params.getAll(def.name); // TODO: EEEK getAll is returning ["1,2,3,4"] when we gave it ["1","2","3","4"].
6337
+ const values = params.get(def.name).split(',').map(s => s.trim());
6338
+ result[def.name] = values.map(v => def.urlFormat.parse(v));
6339
+ }
6340
+ else {
6341
+ const value = params.get(def.name);
6342
+ if (def.isRouteId) { // TODO: Move this to parameter def so it's a strategy pattern
6343
+ // because our id routes redirect if the id isn't present we always have a id
6344
+ // parameter in our params. This will bugger our remember and defaultvalue sanitisation
6345
+ // as it'll see that the id is present (event thought its a blank string).
6346
+ if (!isEmpty(value)) {
6347
+ result[def.name] = def.urlFormat.parse(value);
6348
+ }
6349
+ }
6350
+ else {
6351
+ result[def.name] = def.urlFormat.parse(value);
6352
+ }
6353
+ }
6354
+ }
6355
+ });
6356
+ return result;
6328
6357
  }
6329
- detachCanDeactivateInteractionContext() {
6330
- const context = this._interactionContext;
6331
- this._interactionContext = null;
6332
- return context;
6358
+ validateRouteParameters(params) {
6359
+ const defs = this.getVisitParameterDefs({
6360
+ includeRouteId: true,
6361
+ includeRouteParameters: true,
6362
+ includeNonRouteParameters: true
6363
+ }).reduce((result, def) => {
6364
+ return Object.assign(Object.assign({}, result), { [def.name]: def });
6365
+ }, {});
6366
+ Object.keys(params).forEach(key => {
6367
+ const parameterDef = defs[key];
6368
+ if (!parameterDef) {
6369
+ lang$1.illegalState(`Parameter ${key} is not valid. Must be one of ${join(Object.keys(defs))}`);
6370
+ }
6371
+ if (!!params[key] && (Array.isArray(params[key]) !== parameterDef.isArray)) {
6372
+ lang$1.illegalState(`Parameter ${key} ${parameterDef.isArray ? "must be an array" : "must not be an array"}. Got ${params[key]}`);
6373
+ }
6374
+ });
6333
6375
  }
6334
- }
6335
-
6336
- class EventCleanUpSession extends NavigationSession {
6337
- handleCanDeactivateCancelledEventScenario(newUrl) {
6338
- lang$1.illegalState('onCanDeactivateInteractionCancelled not supported for event clean up states');
6376
+ hasAncestor(placeComponent) {
6377
+ return this.ancestors().find(a => a.component === placeComponent) != null;
6339
6378
  }
6340
6379
  }
6380
+ __decorate([
6381
+ Memoize(),
6382
+ __metadata("design:type", Function),
6383
+ __metadata("design:paramtypes", []),
6384
+ __metadata("design:returntype", Array)
6385
+ ], PlaceDefinition.prototype, "ancestors", null);
6386
+ __decorate([
6387
+ Memoize(),
6388
+ __metadata("design:type", Function),
6389
+ __metadata("design:paramtypes", []),
6390
+ __metadata("design:returntype", Array)
6391
+ ], PlaceDefinition.prototype, "ancestorsAndSelf", null);
6392
+ __decorate([
6393
+ Memoize(),
6394
+ __metadata("design:type", Function),
6395
+ __metadata("design:paramtypes", []),
6396
+ __metadata("design:returntype", ParameterDefinition)
6397
+ ], PlaceDefinition.prototype, "getRouteIdParameterDef", null);
6398
+ __decorate([
6399
+ Memoize(),
6400
+ __metadata("design:type", Function),
6401
+ __metadata("design:paramtypes", [Object]),
6402
+ __metadata("design:returntype", Array)
6403
+ ], PlaceDefinition.prototype, "getRouteParameterDefs", null);
6404
+ __decorate([
6405
+ Memoize(),
6406
+ __metadata("design:type", Function),
6407
+ __metadata("design:paramtypes", [Object]),
6408
+ __metadata("design:returntype", Array)
6409
+ ], PlaceDefinition.prototype, "getVisitParameterDefs", null);
6341
6410
 
6342
- /**
6343
- * The sequence of router events are:
6344
- * NavigationError -> url = url of navigation link
6345
- * NavigationEnd
6346
- * onPopState url = Our currentUrl sans and interaction query params
6347
- * NavigationCancel url == same as above.
6348
- */
6349
- class WaitUntilLeavingInteractionTransitionCancelled extends EventCleanUpSession {
6350
- constructor(context, startingUrl, locationChangeTriggerUrl) {
6351
- super(context, startingUrl);
6352
- this.locationChangeTriggerUrl = locationChangeTriggerUrl;
6353
- this.isPopState = false;
6354
- this.firstCancelHandled = false;
6355
- this.popStateHandled = false;
6356
- this.debugPropertyKeys = ['idle', 'startingUrl', 'poppedHistoryUrl', 'locationChangeTriggerUrl', 'popStateEventUrl', 'firstCancelHandled', 'popStateHandled'];
6357
- }
6358
- // @Trace()
6359
- onRouterStarted(event) {
6360
- this.ignore(event);
6361
- }
6362
- // @Trace()
6363
- onRouterCancelled(event) {
6364
- this.repairBrowserHistoryAndUrlAfterGuardCancellation(this.locationChangeTriggerUrl, this.startingUrl);
6365
- this.context.finishRoutingSession();
6366
- }
6367
- // @Trace()
6368
- onRouterEnd(event) {
6369
- this.ignore(event);
6370
- }
6371
- // @Trace()
6372
- onRouterError(event) {
6373
- this.ignore(event);
6374
- }
6375
- // @Trace()
6376
- onPopState(event) {
6377
- this.ignore(event);
6411
+ // RAKE: making this Symbol(...) broke things.
6412
+ const DEFINITION_META_DATA_KEY = 'PLACE_DEFINITION_OPTIONS';
6413
+ // this one seems ok.
6414
+ const ROUTE_PARAMETER_LIST_KEY = Symbol('place:route:parameters');
6415
+ class ParameterChangeInterceptor {
6416
+ constructor(parameterDef, model, callback, options) {
6378
6417
  }
6379
- canDeactivatePlace(component, currentUrl, nextUrl) {
6418
+ canProceed(nextState, interactionContext) {
6380
6419
  return __awaiter(this, void 0, void 0, function* () {
6381
- return false;
6420
+ return true;
6382
6421
  });
6383
6422
  }
6384
6423
  }
6385
-
6386
- /**
6387
- * This session tracks the process of removing the last interaction context from the URL and provides a promise
6388
- * the resolves when the process and completed. This case is special as the process involves a regular routing cycle
6389
- * followed by a call to location.back(). The later triggers a url change with no other routing events. So this
6390
- * class tracks when the first routing cycle finishes and then waits for the subsequent lone url change event.
6391
- */
6392
- class RemoveLastInteractionFromUrlNavigationSession extends NavigationSession {
6393
- constructor(context, startingUrl) {
6394
- super(context, startingUrl);
6395
- this.isPopState = true;
6396
- this.debugPropertyKeys = ['startingUrl', 'poppedHistoryUrl'];
6397
- this.finished = Deferred.defer();
6398
- }
6399
- get isInteractionSync() {
6400
- return true;
6401
- }
6402
- // @Trace()
6403
- onPopState(event) {
6404
- this.gotPopState = true;
6405
- }
6406
- // @Trace()
6407
- onRouterStarted(event) {
6408
- this.ignore(event);
6424
+ class PlaceComponent extends DisposableComponent {
6425
+ constructor() {
6426
+ super();
6427
+ this._placeReadyCallbacks = [];
6428
+ this.visitModel = new MutableValueModel();
6429
+ this._inVisitUpdate = new Guard();
6430
+ this._active = new MutableValueModel(false);
6431
+ this._parameterChangeInterceptors = [];
6432
+ const { chain, valueOf, before, when, after, observe, switchOn } = Dsl.disposeWith(this);
6433
+ when(this._active).becomesTruthy(() => this._notifyPlaceReady());
6434
+ this.childPlaces = this.placeDefinition.children.map(d => d.component);
6409
6435
  }
6410
- // @Trace()
6411
- onRouterCancelled(event) {
6412
- this.ignore(event);
6436
+ initialiseVisit(visit, notifyVisitChanged) {
6437
+ assert.isNil(this.visitModel.value);
6438
+ const { when } = Dsl.disposeWith(this);
6439
+ this.visitModel.value = visit;
6440
+ DebugContext.getOrCreate(this.visitModel).tag(`${this.placeDefinition.component.name}.visitModel`);
6441
+ // we track if the any of the bindings updated the route. If so we remember it and update the
6442
+ // route in one go at the end.
6443
+ this.placeDefinition
6444
+ .getVisitParameterDefs()
6445
+ .forEach(parameterDef => this.installAndInitialiseBinding(visit, parameterDef));
6446
+ when(this.visitModel).changes((current, previous) => {
6447
+ notifyVisitChanged(current, previous);
6448
+ }, { unless: this._inVisitUpdate });
6449
+ // TODO: this needs to do a replace url option so that the new url isn't put in the history.... for
6450
+ // now we're not doing it as it's a fair bit of effort and will only affect people if they're
6451
+ // cutting and pasting urls to each other.
6452
+ // // the binding process can update the visit (e.g. if a selection model has already selected during
6453
+ // // component construction) and there was no value specified in the route
6454
+ // if (visit.hasRoutingChangedFrom(this.visitModel.value)) {
6455
+ // notifyVisitChanged(this.visitModel.value, visit)
6456
+ // }
6413
6457
  }
6414
- // @Trace()
6415
- onUrlChange(url) {
6458
+ updateVisit(visit) {
6459
+ assert.isTruthy(this.isInitialised());
6460
+ assert.notNil(visit);
6461
+ this._inVisitUpdate.whileTrue(() => {
6462
+ this.visitModel.value = visit;
6463
+ });
6416
6464
  }
6417
- finishUp() {
6418
- this.context.finishRoutingSession();
6419
- this.finished.resolve(true);
6465
+ isInitialised() {
6466
+ return !!this.visitModel.value;
6420
6467
  }
6421
6468
  // @Trace()
6422
- onRouterEnd(event) {
6423
- if (this.gotPopState) {
6424
- this.finishUp();
6469
+ /**
6470
+ * Initialised the component bindings. If any binding has an initial model value (e.g. a selection model
6471
+ * initialised during the constructor) and the route has nothing, then the visit will be udpated and this
6472
+ * method will return ture to nofiy the the visit has changed.
6473
+ */
6474
+ installAndInitialiseBinding(initialVisit, parameterDef) {
6475
+ const model = this[parameterDef.propertyName];
6476
+ DebugContext.tag(model, `${this.placeDefinition.component.name}.${parameterDef.propertyName}`);
6477
+ const binding = this.registerDisposable(new Binding(this.visitModel, model, {
6478
+ toRight(visit) {
6479
+ const value = visit.getParameterValue(parameterDef);
6480
+ // console.log('push to component', { name: parameterDef.name, value, visit });
6481
+ return value;
6482
+ },
6483
+ toLeft(value, currentVisit) {
6484
+ // console.log('push to route', { name: parameterDef.name, value, currentVisit });
6485
+ return currentVisit.replace(parameterDef, value);
6486
+ }
6487
+ }));
6488
+ // Now we need to initialise the binding direction. If we have a value in the Url then we should always push
6489
+ // that to the view. If we don't and the view already has a value (e.g. a selection model has already initialised in the
6490
+ // component constructor) then we should push that to the route.
6491
+ const isInVisit = !isNil(initialVisit.getParameterValue(parameterDef));
6492
+ const isInModel = !isNil(model.value);
6493
+ if (!isInVisit && isInModel) {
6494
+ binding.writeLeft(); // push it to the route
6495
+ }
6496
+ else {
6497
+ binding.writeRight(); // push it to the model
6425
6498
  }
6426
6499
  }
6427
- // @Trace()
6428
- handleCanDeactivateCancelledEventScenario(locationTriggerUrl) {
6429
- lang.illegalState('onCanDeactivateInteractionCancelled not supported for activity context synchronisation since we should never leave a place');
6430
- }
6431
- get finishedPromise() {
6432
- return this.finished.promise;
6433
- }
6434
- }
6435
-
6436
- class SynchroniseInteractionContextIdsWithRoute extends NavigationSession {
6437
- constructor(context, startingUrl, wasTriggeredByPopState) {
6438
- super(context, startingUrl);
6439
- this.wasTriggeredByPopState = wasTriggeredByPopState;
6440
- this.isPopState = false;
6500
+ get placeDefinition() {
6501
+ const definition = PlaceComponent.getDefinition(this.constructor);
6502
+ if (!definition) {
6503
+ lang.illegalState(`${this.constructor.name} extends PlaceComponent but doesn't have @Place({..}) decorator.`);
6504
+ }
6505
+ return definition;
6441
6506
  }
6442
- get isInteractionSync() {
6443
- return true;
6507
+ get active() {
6508
+ return this._active.readonly;
6444
6509
  }
6445
- notifyActive() {
6446
- // TODO: Do I still need this??
6447
- setTimeout(() => {
6448
- this.syncInteractionIdsWithRouter();
6510
+ /**
6511
+ * Called by the router to see if this component can deactivate. This isn't called for route parameter changes.
6512
+ * @param interactionContext
6513
+ */
6514
+ _canLeavePlace(interactionContext) {
6515
+ return __awaiter(this, void 0, void 0, function* () {
6516
+ return this.canDeactivate ? this.canDeactivate(interactionContext) : true;
6449
6517
  });
6450
6518
  }
6451
- // @Trace()
6452
- onRouterEnd(event) {
6453
- this.context.finishRoutingSession();
6519
+ /**
6520
+ * Called by the router to see if this component can deactivate. This isn't called for route parameter changes.
6521
+ * @param interactionContext
6522
+ * @param nextState
6523
+ */
6524
+ _canChangeRouteParameters(interactionContext, nextState) {
6525
+ return __awaiter(this, void 0, void 0, function* () {
6526
+ if (this._parameterChangeInterceptors.length > 0) {
6527
+ const visit = nextState.createVisitSegmentFor(this.placeDefinition);
6528
+ for (let i = 0; i < this._parameterChangeInterceptors.length; i++) {
6529
+ const interceptor = this._parameterChangeInterceptors[i];
6530
+ const keepGoing = yield interceptor.canProceed(visit, interactionContext);
6531
+ if (!keepGoing) {
6532
+ return false;
6533
+ }
6534
+ }
6535
+ }
6536
+ return true;
6537
+ });
6454
6538
  }
6455
- // @Trace()
6456
- onRouterCancelled(event) {
6457
- this.context.finishRoutingSession();
6539
+ /**
6540
+ * Called by the router when the place is ready to interact after any animations have run.
6541
+ */
6542
+ _notifyActive(active) {
6543
+ this._active.value = active;
6458
6544
  }
6459
- // @Trace()
6460
- syncInteractionIdsWithRouter() {
6461
- const currentIds = this.interactionServiceAdapter.getActiveInteractionContextIds();
6462
- const previousIds = this.urlService.getCurrentLocationUrlSnapshot().getInteractionIds();
6463
- // console.log(`---> synchroniseInteractionIds`, { is: currentIds.join(','), was: previousIds.join(',') });
6464
- if (isEqual(currentIds, previousIds)) {
6465
- // console.log('### Activity context ids were the same, skipping');
6466
- this.context.finishRoutingSession();
6545
+ /**
6546
+ * Called by the router when the place is ready to interact after any animations have run.
6547
+ */
6548
+ _notifyPlaceReady() {
6549
+ if (this.onPlaceReady.length === 1) {
6550
+ this._placeReadyCallbacks.forEach(callback => callback());
6467
6551
  }
6468
6552
  else {
6469
- if (currentIds.length > previousIds.length) {
6470
- const isFirstActivity = currentIds.length > previousIds.length && previousIds.length < 1;
6471
- this.addActivityContextToRoute(currentIds, isFirstActivity);
6472
- }
6473
- else {
6474
- this.removeActivityContextFromRoute(currentIds);
6475
- }
6553
+ console.warn('Overriding PlaceComponent.onPlaceReady has been deprecated. Use PlaceComponent.onPlaceReady(() => {... do stuff...}) instead.');
6554
+ this.onPlaceReady(undefined);
6476
6555
  }
6477
6556
  }
6478
- // @Trace()
6479
- addActivityContextToRoute(activeInteractionContextIds, isFirst) {
6480
- const urlSnapshot = this.urlService.getCurrentRouterSnapshot().updateInteractionIds(activeInteractionContextIds);
6481
- this.context.navigateByUrl(urlSnapshot, {
6482
- replaceUrl: !isFirst
6483
- }).then(result => {
6484
- if (!this.urlService.getCurrentLocationUrlSnapshot().hasInteractionIds(activeInteractionContextIds)) {
6485
- lang$1.illegalState(`Expected url to be ${urlSnapshot.url} but was ${this.urlService.getCurrentLocationUrl()}`);
6486
- // this.urlService.resetBrowserLocation(urlSnapshot.url, {replaceCurrent: !isFirst})
6487
- }
6488
- });
6557
+ onPlaceReady(callback) {
6558
+ this._placeReadyCallbacks.push(callback);
6489
6559
  }
6490
- // @Trace()
6491
- removeActivityContextFromRoute(activeInteractionContextId) {
6492
- const urlSnapshot = this.urlService.getCurrentRouterSnapshot().updateInteractionIds(activeInteractionContextId);
6493
- const isRemovingLastActivity = activeInteractionContextId.length < 1;
6494
- if (isRemovingLastActivity) {
6495
- if (this.wasTriggeredByPopState) {
6496
- // console.log('removal was triggered by pop state, nothing to do.');
6497
- // noop. Our url will be back to the non interaction version now so we dont' need to do anything.
6498
- }
6499
- else {
6500
- // now we just pop our interaction id's from the browser history.
6501
- // console.log(`Removal of the last activity wasn't triggered by pop state so we have to trigger one to clean the history`);
6502
- const session = new RemoveLastInteractionFromUrlNavigationSession(this.context, this.urlService.getCurrentRouterUrl());
6503
- this.context.transitionTo(session);
6504
- this.urlService.back();
6560
+ interceptVisitParameterChange(model, callback, options) {
6561
+ const parameterDef = ParameterDefinition.get(model);
6562
+ this._parameterChangeInterceptors.push(new ParameterChangeInterceptor(parameterDef, model, callback, options));
6563
+ }
6564
+ }
6565
+ PlaceComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: PlaceComponent, deps: [], target: i0.ɵɵFactoryTarget.Directive });
6566
+ PlaceComponent.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "14.1.2", type: PlaceComponent, usesInheritance: true, ngImport: i0 });
6567
+ __decorate([
6568
+ Memoize(),
6569
+ __metadata("design:type", PlaceDefinition),
6570
+ __metadata("design:paramtypes", [])
6571
+ ], PlaceComponent.prototype, "placeDefinition", null);
6572
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: PlaceComponent, decorators: [{
6573
+ type: Directive
6574
+ }], ctorParameters: function () { return []; }, propDecorators: { placeDefinition: [] } });
6575
+ (function (PlaceComponent) {
6576
+ function isPlaceComponentConstructor(target) {
6577
+ return lang.constructorChain(target).includes(PlaceComponent);
6578
+ }
6579
+ PlaceComponent.isPlaceComponentConstructor = isPlaceComponentConstructor;
6580
+ function getRouteParameters(klass) {
6581
+ return Klass.get(klass).getMetadataList(ROUTE_PARAMETER_LIST_KEY);
6582
+ }
6583
+ PlaceComponent.getRouteParameters = getRouteParameters;
6584
+ function getDefinition(snapshotOrConstructor) {
6585
+ if (snapshotOrConstructor instanceof ActivatedRouteSnapshot) {
6586
+ const component = snapshotOrConstructor.component;
6587
+ if (!isPlaceComponentConstructor(component)) {
6588
+ throw new Error(`ActivatedRouteSnapshot component is not a PlaceComponent, got ${component}`);
6505
6589
  }
6590
+ return Reflect.getMetadata(DEFINITION_META_DATA_KEY, component);
6506
6591
  }
6507
6592
  else {
6508
- // we've removed an interaction, but we still have remaining activities so we
6509
- // update the url in place if it wasn't a pop state. If it was a pop state we need
6510
- // to push it back up.
6511
- // this.urlService.resetBrowserLocation(urlSnapshot.url, { replaceCurrent: !this.wasTriggeredByPopState });
6512
- this.context.navigateByUrl(urlSnapshot, { replaceUrl: !this.wasTriggeredByPopState });
6593
+ return Reflect.getMetadata(DEFINITION_META_DATA_KEY, snapshotOrConstructor);
6513
6594
  }
6514
6595
  }
6515
- handleCanDeactivateCancelledEventScenario(newUrl) {
6516
- lang$1.methodNotSupported();
6596
+ PlaceComponent.getDefinition = getDefinition;
6597
+ function injectDefinition(klass, definition) {
6598
+ Reflect.defineMetadata(DEFINITION_META_DATA_KEY, definition, klass);
6517
6599
  }
6518
- }
6600
+ PlaceComponent.injectDefinition = injectDefinition;
6601
+ })(PlaceComponent || (PlaceComponent = {}));
6519
6602
 
6520
- /**
6521
- * This state exists to handle all events while any kind of navigation is in progress. That way all other states can
6522
- * happily ignore interaction contexts.
6523
- * NOTE: This state is activated when ever an interaction is started. It might be better to split it into
6524
- * different states for different scenarios, e.g. starting model, starting model during route guard etc.
6525
- */
6526
- class NavigatingDuringInteraction extends NavigationSession {
6527
- constructor() {
6528
- super(...arguments);
6529
- this.isPopState = false;
6603
+ class VisitSegment {
6604
+ constructor(placeDefinition, visitParameters = {}) {
6605
+ this.placeDefinition = placeDefinition;
6606
+ placeDefinition.validateRouteParameters(visitParameters);
6607
+ this.visitParameters = Object.freeze(visitParameters);
6530
6608
  }
6531
6609
  // @Trace()
6532
- onRouterCancelled(event) {
6533
- this.context.finishRoutingSession();
6534
- }
6535
- // @Trace()
6536
- onRouterError(event) {
6537
- // navigation was aborted.
6538
- this.context.finishRoutingSession();
6539
- }
6540
- // @Trace()
6541
- onRouterEnd(event) {
6542
- if (this.context.routerInteractionAdapter.isActive()) {
6543
- this.context.transitionTo(new SynchroniseInteractionContextIdsWithRoute(this.context, this.startingUrl, false));
6544
- }
6545
- else {
6546
- this.context.finishRoutingSession(this.getVisits());
6547
- }
6610
+ getRouteId() {
6611
+ return this.placeDefinition.getRouteIdFrom(this);
6548
6612
  }
6549
6613
  // @Trace()
6550
- handleCanDeactivateCancelledEventScenario(locationTriggerUrl) {
6551
- this.context.transitionTo(new WaitUntilLeavingInteractionTransitionCancelled(this.context, this.startingUrl, locationTriggerUrl));
6614
+ hasRouteId() {
6615
+ return !isNil(this.getRouteId());
6552
6616
  }
6553
- }
6554
-
6555
- class AbstractPopStateNavigation extends NavigationSession {
6556
- constructor(context, startingUrl, poppedHistoryUrl) {
6557
- super(context, startingUrl);
6558
- this.poppedHistoryUrl = poppedHistoryUrl;
6559
- this.isPopState = true;
6560
- this.debugPropertyKeys = ['startingUrl', 'poppedHistoryUrl'];
6617
+ /**
6618
+ * Returns the value of the place parameter with the specified name. The parameter
6619
+ * name is taken from the `as` option, e.g. {as: 'aCustomName'} otherwise it is the
6620
+ * same as the ValueModel property name.
6621
+ * @param parameter the visit parameter definition
6622
+ */
6623
+ getParameterValue(parameter) {
6624
+ return isString(parameter) ? this.visitParameters[parameter] : this.visitParameters[parameter.name];
6561
6625
  }
6562
6626
  // @Trace()
6563
- repairBrowserHistoryAndUrlAfterGuardCancellation() {
6564
- super.repairBrowserHistoryAndUrlAfterGuardCancellation(this.poppedHistoryUrl, this.startingUrl);
6627
+ hasParameter(parameterDef) {
6628
+ return Object.keys(this.visitParameters).includes(parameterDef.name);
6565
6629
  }
6566
- }
6567
-
6568
- /**
6569
- * This state exists to handle all events while any kind of navigation is in progress. That way all other states can
6570
- * happily ignore interaction contexts.
6571
- */
6572
- class PopStateDuringInteractionNavigation extends AbstractPopStateNavigation {
6573
- constructor(context, startingUrl, poppedHistoryUrl) {
6574
- super(context, startingUrl, poppedHistoryUrl);
6630
+ replace(parameter, value) {
6631
+ return new VisitSegment(this.placeDefinition, Object.assign(Object.assign({}, this.visitParameters), { [parameter.name]: value }));
6575
6632
  }
6576
- /**
6577
- * Invoked when the place refuses to deactivate because of an unfinished interaction.
6578
- * @param event
6579
- */
6580
- // @Trace()
6581
- onRouterCancelled(event) {
6582
- this.repairBrowserHistoryAndUrlAfterGuardCancellation();
6583
- // NOTE: for now we need to wasTriggeredByPopState=false because we're resetting the url and history in the previous line.
6584
- this.context.transitionTo(new SynchroniseInteractionContextIdsWithRoute(this.context, this.poppedHistoryUrl, false));
6633
+ mergeRouteParameters(routeParams) {
6634
+ // todo: whitelist parameters.
6635
+ const routeParameterKeys = Object.keys(routeParams);
6636
+ const params = {};
6637
+ this.placeDefinition.getVisitParameterDefs().forEach(def => {
6638
+ if (def.isRouteId || def.isRouteParameter) {
6639
+ if (routeParameterKeys.includes(def.name)) {
6640
+ params[def.name] = routeParams[def.name];
6641
+ }
6642
+ }
6643
+ else {
6644
+ // copy non route params as is, but only if they already exist otherwise we'll inject nil values and break the
6645
+ // defaults and remember sanitisation process.
6646
+ const value = this.getParameterValue(def);
6647
+ if (this.hasParameter(def)) {
6648
+ params[def.name] = value;
6649
+ }
6650
+ }
6651
+ });
6652
+ return new VisitSegment(this.placeDefinition, params);
6585
6653
  }
6586
6654
  // @Trace()
6587
- onRouterEnd(event) {
6588
- // this.context.transitionTo(new SynchroniseInteractionContextIdsWithRoute(this.context, this.poppedHistoryUrl, false));
6589
- this.context.finishRoutingSession();
6655
+ hasRoutingChangedFrom(other) {
6656
+ const samePlace = other.placeDefinition === this.placeDefinition;
6657
+ const currentParams = this.placeDefinition.getFormattedRouteParameters(this, true);
6658
+ const otherParams = this.placeDefinition.getFormattedRouteParameters(other, true);
6659
+ // console.log({currentParams, otherParams});
6660
+ const sameRouteParameters = isEqual(currentParams, otherParams);
6661
+ return !samePlace || !sameRouteParameters;
6590
6662
  }
6591
- handleCanDeactivateCancelledEventScenario(newUrl) {
6592
- this.illegalTransition('Leaving interaction after pop-state should\'t block so should never see a back button click');
6663
+ hasChangedFrom(other) {
6664
+ const sameNonRouteParameters = isEqual(this.placeDefinition.getNonRouteParameters(this), this.placeDefinition.getNonRouteParameters(other));
6665
+ return !sameNonRouteParameters || this.hasRoutingChangedFrom(other);
6593
6666
  }
6594
- }
6595
-
6596
- /**
6597
- * This state handles the scenario where a link navigation triggered an interaction and the user clicked back a to cancel it.
6598
- * The routing event sequence is different depending on the link that was clicked.
6599
- *
6600
- * NOTE: In angular prior to 10 the sequence of routing events was different depending on the initial link that was clicked.
6601
- * This class used have ugle if/else code to handle it and a not that it should be split into sub states.
6602
- * During the update to angular 10 I did this (as the tests for this scenario were failings). After doing so
6603
- * it appears that angular now behaves the same in both cases. But rather that revert the changes I've left the
6604
- * sub-state handling in in case it ever comes back.
6605
- */
6606
- class WaitUntilLinkTriggeredNavigationInteractionCancellationTypeDetermined extends EventCleanUpSession {
6607
- constructor(context, startingUrl, clickedLinkUrl) {
6608
- super(context, startingUrl);
6609
- this.clickedLinkUrl = clickedLinkUrl;
6610
- this.isPopState = false;
6611
- this.clickedLinkMatchedBackButtonUrl = false;
6612
- this.debugPropertyKeys = ['idle', 'startingUrl', 'clickedLinkUrl', 'firstCancelEventUrl', 'clickedLinkMatchedBackButtonUrl', 'popStateEventUrl'];
6667
+ createRouterCommands() {
6668
+ return this.hasRouteId() ?
6669
+ [this.placeDefinition.getFormattedRouteId(this), this.placeDefinition.getFormattedRouteParameters(this)] :
6670
+ [this.placeDefinition.getFormattedRouteParameters(this)];
6613
6671
  }
6614
- // @Trace()
6615
- onRouterStarted(event) {
6616
- this.ignore(event);
6672
+ copyMissingFrom(other) {
6673
+ return new VisitSegment(this.placeDefinition, Object.assign(Object.assign({}, other.visitParameters), this.visitParameters));
6617
6674
  }
6618
- // @Trace()
6619
- onRouterCancelled(event) {
6620
- if (event.url === this.clickedLinkUrl) {
6621
- this.context.transitionTo(new WaitForLinkSameAsBackToPlayOut(this.context, this.startingUrl, this.clickedLinkUrl));
6675
+ toDebugString() {
6676
+ const bits = [this.placeDefinition.path];
6677
+ if (this.placeDefinition.authenticate) {
6678
+ bits.push("🔐");
6622
6679
  }
6623
- else {
6624
- this.context.transitionTo(new WaitForLinkDifferentFromBackToPlayOut(this.context, this.startingUrl, this.clickedLinkUrl));
6680
+ const keys = Object.keys(this.visitParameters);
6681
+ if (keys.length > 0) {
6682
+ bits.push(`(${keys.map(k => `${k}=${this.visitParameters[k]}`)}})`);
6625
6683
  }
6684
+ return bits.join('');
6626
6685
  }
6627
- canDeactivatePlace(component, currentUrl, nextUrl) {
6628
- return __awaiter(this, void 0, void 0, function* () {
6629
- return false;
6686
+ }
6687
+
6688
+ class Visit {
6689
+ constructor(segments) {
6690
+ this.segmentsByPlaceComponent = new Map();
6691
+ assert$1.isTruthy(segments.length > 0);
6692
+ this.destinationSegment = last(segments);
6693
+ this.destinationPlaceDef = this.destinationSegment.placeDefinition;
6694
+ segments.forEach(s => this.segmentsByPlaceComponent.set(s.placeDefinition.component, s));
6695
+ }
6696
+ static goto(placeComponent, visitParameters) {
6697
+ return new Visit([new VisitSegment(PlaceComponent.getDefinition(placeComponent), visitParameters)]);
6698
+ }
6699
+ static fromSegments(segments) {
6700
+ return new Visit(segments);
6701
+ }
6702
+ get definedSegments() {
6703
+ return Array.from(this.segmentsByPlaceComponent.values()).reduce((map, s) => {
6704
+ map.set(s.placeDefinition.component, s);
6705
+ return map;
6706
+ }, new Map());
6707
+ }
6708
+ withAncestorParameters(placeComponent, parameters) {
6709
+ if (!this.destinationPlaceDef.hasAncestor(placeComponent)) {
6710
+ throw new Error(`Place ${placeComponent.name} is not an ancestor of ${this.destinationPlaceDef.component.name}`);
6711
+ }
6712
+ this.segmentsByPlaceComponent.set(placeComponent, new VisitSegment(PlaceComponent.getDefinition(placeComponent), parameters));
6713
+ return this;
6714
+ }
6715
+ get segments() {
6716
+ return this.resolveSegments(this.definedSegments);
6717
+ }
6718
+ resolveSegments(...defaults) {
6719
+ return this.destinationPlaceDef.ancestorsAndSelf()
6720
+ .map(a => {
6721
+ const visit = new VisitSegment(a, {});
6722
+ return defaults
6723
+ .map(segments => segments.get(a.component))
6724
+ .filter(it => !!it)
6725
+ .reduce((it, other) => it.copyMissingFrom(other), visit);
6630
6726
  });
6631
6727
  }
6632
- }
6633
- class WaitForLinkSameAsBackToPlayOut extends EventCleanUpSession {
6634
- constructor(context, startingUrl, clickedLinkUrl) {
6635
- super(context, startingUrl);
6636
- this.clickedLinkUrl = clickedLinkUrl;
6637
- this.isPopState = false;
6638
- this.debugPropertyKeys = ['idle', 'startingUrl', 'clickedLinkUrl', 'popStateEventUrl'];
6728
+ copyWithDefaultsFrom(other) {
6729
+ const segments = this.resolveSegments(this.definedSegments, other.definedSegments);
6730
+ return new Visit(segments);
6639
6731
  }
6640
- // @Trace()
6641
- onRouterEnd(event) {
6642
- this.ignore(event);
6732
+ copyAndReplaceSegment(replace) {
6733
+ // console.log("copyAndReplaceSegment", replace.toDebugString());
6734
+ const segments = this.segments.map(s => s.placeDefinition === replace.placeDefinition ? replace : s);
6735
+ // console.log("copyAndReplaceSegment.result", segments.map(s => s.toDebugString()).join("\n"));
6736
+ return new Visit(segments);
6643
6737
  }
6644
- // @Trace()
6645
- onRouterError(event) {
6646
- this.ignore(event);
6738
+ isPlaceActive(placeDefinition) {
6739
+ return !!this.getSegmentFor(placeDefinition);
6647
6740
  }
6648
- // @Trace()
6649
- onPopState(event) {
6650
- this.popStateEventUrl = event.url;
6651
- this.ignore(event);
6741
+ getSegmentFor(placeDefinition) {
6742
+ return this.segments.find(v => v.placeDefinition === placeDefinition);
6652
6743
  }
6653
- // @Trace()
6654
- onRouterCancelled(event) {
6655
- if (this.popStateEventUrl) {
6656
- this.finaliseRouting();
6657
- }
6744
+ getRouterCommands() {
6745
+ return this.segments.reduce((result, v) => {
6746
+ const path = v.placeDefinition.path;
6747
+ return isEmpty$1(path) ?
6748
+ [...result, path] : // Angular doesn't support route params on empty path segments
6749
+ [...result, path, ...v.createRouterCommands()];
6750
+ }, []);
6658
6751
  }
6659
- // @Trace()
6660
- finaliseRouting() {
6661
- this.repairBrowserHistoryAndUrlAfterGuardCancellation(this.clickedLinkUrl, this.startingUrl);
6662
- return this.context.finishRoutingSession();
6752
+ isAuthorised(guard) {
6753
+ return this.segments.find(s => !guard.isAuthorised(s.placeDefinition)) == null;
6663
6754
  }
6664
- canDeactivatePlace(component, currentUrl, nextUrl) {
6665
- return __awaiter(this, void 0, void 0, function* () {
6666
- return false;
6667
- });
6755
+ requiresAuthentication() {
6756
+ return !!this.segments.find(s => s.placeDefinition.authenticate);
6668
6757
  }
6669
- }
6670
- // See the note above. This class is identical to the previous but I've left it here in case angular decides to
6671
- // route differently in this scenario going forward.
6672
- class WaitForLinkDifferentFromBackToPlayOut extends EventCleanUpSession {
6673
- constructor(context, startingUrl, clickedLinkUrl) {
6674
- super(context, startingUrl);
6675
- this.clickedLinkUrl = clickedLinkUrl;
6676
- this.isPopState = false;
6677
- this.debugPropertyKeys = ['idle', 'startingUrl', 'clickedLinkUrl', 'popStateEventUrl'];
6758
+ toDebugString() {
6759
+ return this.segments.map(s => s.toDebugString()).join("/");
6678
6760
  }
6679
- // @Trace()
6680
- onRouterEnd(event) {
6681
- this.ignore(event);
6761
+ }
6762
+ __decorate([
6763
+ Memoize$1(),
6764
+ __metadata("design:type", Function),
6765
+ __metadata("design:paramtypes", [PlaceDefinition]),
6766
+ __metadata("design:returntype", VisitSegment)
6767
+ ], Visit.prototype, "getSegmentFor", null);
6768
+ // const visit2 = Visit.goto(AnotherPlace, {id: "fred"})
6769
+ // .withAncestorParameters(ParentA, {id: "a"}) // barf if not a ancestor or missing parameters are required or parameter isn't valid
6770
+ // .withAncestorParameters(ParentB, {id: "c"}) // barf if not a ancestor or missing parameters are required or parameter isn't valid
6771
+ //
6772
+
6773
+ /**
6774
+ * This class handles the logic around canDeactivate for a given router state transition. It's core responsibilities are:
6775
+ * 1. Ensure we only ask the component to deactivate once on a given navigation cycle (since visit sanitisation can result in multiple round trips to through the router.)
6776
+ * 2. Ensure only the primary place component is asked when there are nested places. The primary component is the one at the top
6777
+ * of the routing change tree.
6778
+ * 3. Automatically handle standard interaction scenarios on the components behalf.
6779
+ */
6780
+ class PlaceComponentDeactivationHandler {
6781
+ constructor(component, navigationSession, isPrimaryComponent) {
6782
+ this.component = component;
6783
+ this.navigationSession = navigationSession;
6784
+ this.isPrimaryComponent = isPrimaryComponent;
6785
+ assert.notNil(component);
6682
6786
  }
6683
- // @Trace()
6684
- onRouterError(event) {
6685
- this.ignore(event);
6787
+ get routerInteractionAdapter() {
6788
+ return this.navigationSession.interactionServiceAdapter;
6686
6789
  }
6687
- // @Trace()
6688
- onPopState(event) {
6689
- this.popStateEventUrl = event.url;
6690
- this.ignore(event);
6790
+ get urlService() {
6791
+ return this.navigationSession.urlService;
6691
6792
  }
6692
- // @Trace()
6693
- onRouterCancelled(event) {
6694
- if (this.popStateEventUrl) {
6695
- this.finaliseRouting();
6696
- }
6793
+ get placeDefinition() {
6794
+ return this.component.placeDefinition;
6697
6795
  }
6698
6796
  // @Trace()
6699
- finaliseRouting() {
6700
- this.repairBrowserHistoryAndUrlAfterGuardCancellation(this.clickedLinkUrl, this.startingUrl);
6701
- return this.context.finishRoutingSession();
6702
- }
6703
- canDeactivatePlace(component, currentUrl, nextUrl) {
6797
+ canDeactivate(currentUrl, nextState) {
6704
6798
  return __awaiter(this, void 0, void 0, function* () {
6705
- return false;
6799
+ // We'll get called multiple times if there's any parameter sanitisation so
6800
+ // we always return true if we accepted promise from a previous cycle of the current
6801
+ // navigation session.
6802
+ if (!this.canDeactivatePromise) {
6803
+ // console.log(`creating deactivate promise for -> ${this.component.constructor.name}`);
6804
+ this.canDeactivatePromise = this.canDeactivateComponent(currentUrl, nextState);
6805
+ }
6806
+ return this.canDeactivatePromise;
6706
6807
  });
6707
6808
  }
6708
- }
6709
- //
6710
- // ### Router State Transition: null -> Navigating(startingUrl: /activities/dialogs;l=en, urlAfterRedirects: undefined)
6711
- // ### ###### Router Event: NavigationStart
6712
- // NavigationStart(id: 6, url: '/home')
6713
- // NavigationStart {id: 6, url: "/home", navigationTrigger: "imperative", restoredState: null}
6714
- // logger.js:39 Ignoring router event: NavigationStart -> /home :: Navigating(startingUrl: /activities/dialogs;l=en, urlAfterRedirects: undefined)
6715
- // ### ###### Router Event: RoutesRecognized
6716
- // RoutesRecognized(id: 6, url: '/home', urlAfterRedirects: '/home', state: Route(url:'', path:'') { Route(url:'home', path:'home') } )
6717
- // RoutesRecognized {id: 6, url: "/home", urlAfterRedirects: "/home", state: RouterStateSnapshot}
6718
- // ###### Router Event: GuardsCheckStart
6719
- // GuardsCheckStart(id: 6, url: '/home', urlAfterRedirects: '/home', state: Route(url:'', path:'') { Route(url:'home', path:'home') } )
6720
- // GuardsCheckStart {id: 6, url: "/home", urlAfterRedirects: "/home", state: RouterStateSnapshot}
6721
- // logger.js:39 back button pressed during navigation session interaction promise
6722
- // logger.js:39 cancelling current navigation activity..
6723
- // logger.js:39 ### Router State Transition: Navigating(startingUrl: /activities/dialogs;l=en, urlAfterRedirects: undefined) -> WaitUntilLinkTriggeredNavigationInteractionCancellationEventsFinish(idle: undefined, startingUrl: /activities/dialogs;l=en, clickedLinkUrl: /home, firstCancelEventUrl: undefined, clickedLinkMatchedBackButtonUrl: false, popStateEventUrl: undefined)
6724
- // ###### Router Event: GuardsCheckEnd
6725
- // GuardsCheckEnd(id: 6, url: '/home', urlAfterRedirects: '/home', state: Route(url:'', path:'') { Route(url:'home', path:'home') } , shouldActivate: false)
6726
- // GuardsCheckEnd {id: 6, url: "/home", urlAfterRedirects: "/home", state: RouterStateSnapshot, shouldActivate: false}
6727
- // ###### Router Event: NavigationCancel
6728
- // NavigationCancel(id: 6, url: '/home')
6729
- // NavigationCancel {id: 6, url: "/home", reason: ""}
6730
- // logger.js:54 WaitUntilLinkTriggeredNavigationInteractionCancellationEventsFinish.onRouterCancelled
6731
- // logger.js:19 args NavigationCancel {id: 6, url: "/home", reason: ""}
6732
- // logger.js:39 Ignoring router event: NavigationCancel -> /home :: WaitUntilLinkTriggeredNavigationInteractionCancellationEventsFinish(idle: undefined, startingUrl: /activities/dialogs;l=en, clickedLinkUrl: /home, firstCancelEventUrl: /home, clickedLinkMatchedBackButtonUrl: true, popStateEventUrl: undefined)
6733
- // logger.js:28 <-- WaitUntilLinkTriggeredNavigationInteractionCancellationEventsFinish.onRouterCancelled undefined
6734
- // logger.js:54 WaitUntilLinkTriggeredNavigationInteractionCancellationEventsFinish.onRouterEnd
6735
- // logger.js:19 args NavigationEnd {id: -1, url: "", urlAfterRedirects: ""}
6736
- // logger.js:54 WaitUntilLinkTriggeredNavigationInteractionCancellationEventsFinish.finaliseRouting
6737
- // logger.js:39 WORK-AROUND: Updating browser location after pop state - see angular issue #13586
6738
- // navigation-session.ts:129 replacing /activities/dialogs;l=en with /home
6739
- // navigation-session.ts:131 pushing /activities/dialogs;l=en back onto the history.
6740
- // ????? place-router.ts:281 ### Router Session Finished (was WaitUntilLinkTriggeredNavigationInteractionCancellationEventsFinish(idle: undefined, startingUrl: /activities/dialogs;l=en, clickedLinkUrl: /home, firstCancelEventUrl: /home, clickedLinkMatchedBackButtonUrl: true, popStateEventUrl: undefined))
6741
- // logger.js:28 <-- WaitUntilLinkTriggeredNavigationInteractionCancellationEventsFinish.finaliseRouting undefined
6742
- // logger.js:28 <-- WaitUntilLinkTriggeredNavigationInteractionCancellationEventsFinish.onRouterEnd undefined
6743
- // ###### Router Event: NavigationStart
6744
- // NavigationStart(id: 7, url: '/home')
6745
- // NavigationStart {id: 7, url: "/home", navigationTrigger: "popstate", restoredState: {…}}
6746
- // logger.js:39 ### Router State Transition: null -> PopStateNavigation(startingUrl: /activities/dialogs;l=en, poppedHistoryUrl: /home)
6747
- // ###### Router Event: RoutesRecognized
6748
- // RoutesRecognized(id: 7, url: '/home', urlAfterRedirects: '/home', state: Route(url:'', path:'') { Route(url:'home', path:'home') } )
6749
- // RoutesRecognized {id: 7, url: "/home", urlAfterRedirects: "/home", state: RouterStateSnapshot}
6750
- // ###### Router Event: GuardsCheckStart
6751
- // GuardsCheckStart(id: 7, url: '/home', urlAfterRedirects: '/home', state: Route(url:'', path:'') { Route(url:'home', path:'home') } )
6809
+ // @Trace()
6810
+ canDeactivateComponent(currentUrl, nextState) {
6811
+ return __awaiter(this, void 0, void 0, function* () {
6812
+ // Automatically cancel any active activities if the navigation session was triggered by the back button.
6813
+ // If we handled more than just the pop state then it leads to the UI ignoring clicks and just cancelling things which is deeply disconcerting.
6814
+ if (this.navigationSession.isPopState) {
6815
+ if (this.isPrimaryComponent && this.routerInteractionAdapter.isModalActive()) {
6816
+ const routeIds = this.urlService.getActiveInteractionIdsFromUrl(nextState.url);
6817
+ const currentIds = this.routerInteractionAdapter.getActiveInteractionContextIds();
6818
+ if (!isEqual(currentIds, routeIds)) { // why am I checking this????
6819
+ yield this.routerInteractionAdapter.cancelCurrentModalInteraction();
6820
+ return false;
6821
+ }
6822
+ }
6823
+ else {
6824
+ // check if the component has an in place interaction
6825
+ if (this.routerInteractionAdapter.isComponentInteracting(this.component)) {
6826
+ yield this.routerInteractionAdapter.cancelComponentInteraction(this.component);
6827
+ return false;
6828
+ }
6829
+ }
6830
+ }
6831
+ // No interaction in progress, so ask the component .
6832
+ // This may start an interaction, hence checking the interaction context before now. I.e. if the place pops up the dialog, and
6833
+ // the user clicks back again, we'll re-enter here and go bang when the component tries to open another dialog.
6834
+ if (this.isGoingToADifferentPlace(nextState)) {
6835
+ const canLeave = yield this.component._canLeavePlace(this.navigationSession.canDeactivateInteractionContext);
6836
+ // The component has an active interaction but no deactivation hook. Rather than guessing what to do
6837
+ // we'll just cancel the navigation and print a warning.
6838
+ if (canLeave && this.routerInteractionAdapter.isComponentInteracting(this.component)) {
6839
+ console.warn('Route changed while component has active interaction, cancelling navigation');
6840
+ return false;
6841
+ }
6842
+ return canLeave;
6843
+ }
6844
+ else {
6845
+ // either an interaction or visit parameter change.
6846
+ return yield this.component._canChangeRouteParameters(this.navigationSession.canDeactivateInteractionContext, nextState);
6847
+ }
6848
+ });
6849
+ }
6850
+ isGoingToADifferentPlace(nextState) {
6851
+ // Because places with a route-id cover two route segments we get asked to deactivate
6852
+ // if the route id is added or removed. So if our path is still present the url
6853
+ // then we shouldn't deactivate the place.
6854
+ return !nextState.includesPathOf(this.component.placeDefinition);
6855
+ }
6856
+ }
6752
6857
 
6753
- class Navigating extends NavigationSession {
6754
- constructor() {
6755
- super(...arguments);
6756
- this.isPopState = false;
6757
- this.debugPropertyKeys = ['startingUrl', 'urlAfterRedirects'];
6858
+ /**
6859
+ * Transient states
6860
+ */
6861
+ class NavigationSession extends GarbageCollector {
6862
+ constructor(context, startingUrl) {
6863
+ super();
6864
+ this.context = context;
6865
+ this.startingUrl = startingUrl;
6866
+ this.debugPropertyKeys = [];
6867
+ this._visitSegments = new Map();
6868
+ this.componentDeactivationHandlers = new Map();
6869
+ // console.log(`new ${this.constructor.name}`)
6870
+ // TODO: can I get away without creating one every time?
6871
+ this._interactionContext = this.context.routerInteractionAdapter.createExclusiveInteractionContext();
6872
+ this.onDispose(() => {
6873
+ // the interaction context can be detached during the back button cancellation state transition
6874
+ // as the transition is synchronous and activityCancellation isn't. Otherwise dispose will be
6875
+ // called before the context has been cancelled. It might be work having the interaction context
6876
+ // automatically cancel if the context is disposed so we don't have worry about detaching etc.
6877
+ if (this._interactionContext) {
6878
+ this._interactionContext.dispose(); // or do something like cancelAndDispose?
6879
+ }
6880
+ });
6881
+ }
6882
+ get isInteractionSync() {
6883
+ return false;
6884
+ }
6885
+ get name() {
6886
+ return this.constructor.name;
6887
+ }
6888
+ get urlService() {
6889
+ return this.context.urlService;
6890
+ }
6891
+ get interactionServiceAdapter() {
6892
+ return this.context.routerInteractionAdapter;
6893
+ }
6894
+ initialiseVisitSegments(visit) {
6895
+ visit.segments.forEach(it => this.updateVisitSegment(it));
6896
+ }
6897
+ updateVisitSegment(segment) {
6898
+ // console.log(`updateVisitSegment`, segment.toDebugString());
6899
+ this._visitSegments.set(segment.placeDefinition, segment);
6900
+ }
6901
+ getVisitSegmentFor(placeDef) {
6902
+ const visit = this._visitSegments.get(placeDef);
6903
+ // console.log(`Getting visit for ${placeDef.component.name}`, {visit});
6904
+ return visit;
6905
+ }
6906
+ createUpdatedVisit(url) {
6907
+ // The visit segments can have arbirary places in them after redirects
6908
+ // so we have to filter them based on the final url.
6909
+ const snapshot = this.urlService.parseUrl(url);
6910
+ const filteredSegments = Array.from(this._visitSegments.values())
6911
+ .filter(it => snapshot.containsVisitSegment(it));
6912
+ return Visit.fromSegments(filteredSegments);
6913
+ }
6914
+ get canDeactivateInteractionContext() {
6915
+ return this._interactionContext;
6916
+ }
6917
+ notifyActive() {
6918
+ // noop.
6919
+ }
6920
+ onRouterStarted(event) {
6921
+ // navigation sessions can have many cancel start cycles due to place guard redirects
6922
+ this.ignore(event);
6923
+ }
6924
+ // @Trace()
6925
+ onUrlChange(url) {
6926
+ // Normally we just ignore these but they are the only way of detecting if the back button
6927
+ // was clicked during a canDeactivate promise.
6928
+ // 1. a route is in progress and awaiting a canDeactivateGuard
6929
+ // 2. the user the clicks the back button.
6930
+ // So to handle that scenario we need to check if we've got a can deactivate interaction in
6931
+ // progress and the do the appropriate clean up.
6932
+ if (this.canDeactivateInteractionContext && this.canDeactivateInteractionContext.isActive()) {
6933
+ this.cancelCanDeactivateInteraction(url);
6934
+ }
6935
+ }
6936
+ onPopState(event) {
6937
+ return this.illegalTransition(event);
6758
6938
  }
6759
6939
  onRouterCancelled(event) {
6940
+ return this.illegalTransition(event);
6760
6941
  }
6761
6942
  onRouterError(event) {
6762
- // navigation was aborted.
6763
- this.context.finishRoutingSession();
6943
+ return this.illegalTransition(event);
6764
6944
  }
6765
6945
  onRouterEnd(event) {
6766
- this.urlAfterRedirects = event.urlAfterRedirects;
6767
- this.context.finishRoutingSession(this.getVisits());
6946
+ return this.illegalTransition(event);
6768
6947
  }
6769
- handleCanDeactivateCancelledEventScenario(newUrl) {
6770
- this.context.transitionTo(new WaitUntilLinkTriggeredNavigationInteractionCancellationTypeDetermined(this.context, this.startingUrl, newUrl));
6948
+ getVisitSegments() {
6949
+ return Array.from(this._visitSegments.values());
6950
+ }
6951
+ illegalTransition(message) {
6952
+ return lang.illegalState(`${message.toString()} not supported by ${this.toString()}`);
6953
+ }
6954
+ currentRouterUrl() {
6955
+ return this.urlService.getCurrentRouterUrl();
6956
+ }
6957
+ resetBrowserLocation(url, options = { replaceCurrent: false }) {
6958
+ // console.log(`---> resetting browser location to: ${url}`);
6959
+ this.urlService.resetBrowserLocation(url, options);
6960
+ }
6961
+ // @Trace()
6962
+ repairBrowserHistoryAndUrlAfterGuardCancellation(poppedHistoryToReplace, activeUrl) {
6963
+ // Important: I tried to perform this fix at a later point int he routing cycle but it created all kinds of
6964
+ // strangeness.
6965
+ Logger.get(this).info("WORK-AROUND: Updating browser location after pop state - see angular issue #13586");
6966
+ // console.log(`replacing ${this.urlService.getCurrentLocationUrlSnapshot().url} with ${poppedHistoryToReplace}`);
6967
+ this.urlService.resetBrowserLocation(poppedHistoryToReplace, { replaceCurrent: true });
6968
+ // console.log(`pushing ${activeUrl} back onto the history.`);
6969
+ this.urlService.resetBrowserLocation(activeUrl, { replaceCurrent: false });
6970
+ }
6971
+ ignore(event, reason) {
6972
+ reason = reason ? ` -> ${reason}` : "";
6973
+ // Logger.get(this).info(`Ignoring router event${reason}: ${event.constructor.name} -> ${event.url} :: ${this.toString()}`);
6974
+ }
6975
+ toString() {
6976
+ return `${this.constructor.name}(${this.debugState()})`;
6977
+ }
6978
+ debugState(properties) {
6979
+ return (properties || this.debugPropertyKeys).map(p => {
6980
+ return `${p}: ${this[p]}`;
6981
+ }).join(", ");
6982
+ }
6983
+ canDeactivatePlace(component, currentUrl, nextUrl) {
6984
+ return __awaiter(this, void 0, void 0, function* () {
6985
+ // console.log(`---> canDeactivatePlace(${component.placeDefinition.path}, ${currentUrl.url} -> ${nextUrl.url})`);
6986
+ // lookup the handler and create it if we've not seen it yet
6987
+ let handler = this.componentDeactivationHandlers.get(component);
6988
+ if (!handler) {
6989
+ const isPrimaryHandler = this.componentDeactivationHandlers.size === 0; // only primary handler cancels the app model interations
6990
+ handler = new PlaceComponentDeactivationHandler(component, this, isPrimaryHandler);
6991
+ this.componentDeactivationHandlers.set(component, handler);
6992
+ }
6993
+ return handler.canDeactivate(currentUrl, nextUrl).then(result => {
6994
+ // console.log(`<--- canDeactivatePlace(${component.placeDefinition.path}): ${result}`);
6995
+ return result;
6996
+ }).catch(error => {
6997
+ throw error;
6998
+ });
6999
+ });
7000
+ }
7001
+ cancelCanDeactivateInteraction(newUrl) {
7002
+ Logger.get(this).info(`back button pressed during navigation session interaction promise`);
7003
+ // detach the interaction from the session so it doesn't get disposed until the activity has finished
7004
+ // all it's things.
7005
+ const canDeactivateInteractionContext = this.detachCanDeactivateInteractionContext();
7006
+ // TODO: I need to make the exclusive interaction context disallow nested activities or
7007
+ // that would mess things up entirely. Or, can I do a context.abortAll().then(..)
7008
+ Logger.get(this).info("cancelling current navigation activity..");
7009
+ canDeactivateInteractionContext.cancelActiveActivity().then(() => {
7010
+ canDeactivateInteractionContext.dispose();
7011
+ });
7012
+ this.handleCanDeactivateCancelledEventScenario(newUrl);
7013
+ }
7014
+ reinstateUrlAfterAngularChangedItOnCancellation(url) {
7015
+ // Angular calls _this.resetUrlToCurrentUrlTree() on cancelling and fucks our history.
7016
+ // So this means that the top of the stack is the url we want to go back to, and not the one that was on
7017
+ // it before the cancel event fired.
7018
+ // So we need to:
7019
+ // - replace the just inserted url with the one that used to be there.
7020
+ // - push our actual url back onto the top of the stack.
7021
+ this.resetBrowserLocation(url, { replaceCurrent: true });
7022
+ }
7023
+ detachCanDeactivateInteractionContext() {
7024
+ const context = this._interactionContext;
7025
+ this._interactionContext = null;
7026
+ return context;
6771
7027
  }
6772
7028
  }
6773
7029
 
6774
- var NavigationContext;
6775
- (function (NavigationContext) {
6776
- class Impl {
6777
- constructor(urlService, routerInteractionAdapter, navigateByUrl, transitionTo, finishRoutingSession) {
6778
- this.urlService = urlService;
6779
- this.routerInteractionAdapter = routerInteractionAdapter;
6780
- this.navigateByUrl = navigateByUrl;
6781
- this.transitionTo = transitionTo;
6782
- this.finishRoutingSession = finishRoutingSession;
6783
- }
7030
+ class EventCleanUpSession extends NavigationSession {
7031
+ handleCanDeactivateCancelledEventScenario(newUrl) {
7032
+ lang$1.illegalState('onCanDeactivateInteractionCancelled not supported for event clean up states');
6784
7033
  }
6785
- NavigationContext.Impl = Impl;
6786
- })(NavigationContext || (NavigationContext = {}));
7034
+ }
6787
7035
 
6788
7036
  /**
6789
- * This state handles the scenario where a pop state triggered and interaction and the user clickeb back a second time to cancel it.
6790
- * The sequence of routing events/state transitions is as follows.
6791
- * -> Idle -> PopStateTransition (poppedHistoryUrl == page to go to, startingUrl = page to stay on )
6792
- * -> confirm dialog shown.
6793
- * -> click back
6794
- * -> PopStateTransition -> CancelledDuringBackButtonNavigationInteraction(trigger url is the page before the popped history url)
6795
- * -> NavigationCancel (for the previous back)
6796
- * -> PopState
6797
- * -> NavigationCancel
7037
+ * The sequence of router events are:
7038
+ * NavigationError -> url = url of navigation link
7039
+ * NavigationEnd
7040
+ * onPopState url = Our currentUrl sans and interaction query params
7041
+ * NavigationCancel url == same as above.
6798
7042
  */
6799
- class WaitUntilPopStateDuringCanDeactivateInteractionFinishes extends EventCleanUpSession {
6800
- constructor(context, startingUrl, locationChangeTriggerUrl, poppedHistoryUrl) {
7043
+ class WaitUntilLeavingInteractionTransitionCancelled extends EventCleanUpSession {
7044
+ constructor(context, startingUrl, locationChangeTriggerUrl) {
6801
7045
  super(context, startingUrl);
6802
7046
  this.locationChangeTriggerUrl = locationChangeTriggerUrl;
6803
- this.poppedHistoryUrl = poppedHistoryUrl;
6804
7047
  this.isPopState = false;
6805
7048
  this.firstCancelHandled = false;
6806
7049
  this.popStateHandled = false;
@@ -6812,20 +7055,8 @@ class WaitUntilPopStateDuringCanDeactivateInteractionFinishes extends EventClean
6812
7055
  }
6813
7056
  // @Trace()
6814
7057
  onRouterCancelled(event) {
6815
- if (!this.firstCancelHandled) {
6816
- this.firstCancelHandled = true;
6817
- this.parentPageUrl = event.url;
6818
- this.ignore(event);
6819
- }
6820
- else {
6821
- if (this.popStateHandled) {
6822
- const grandParentPageUrl = event.url;
6823
- this.repairBrowserHistoryAndUrlAfterGuardCancellation(grandParentPageUrl, this.parentPageUrl);
6824
- // we've had one more back click than normal so we need to add our initial url back in as well.
6825
- this.resetBrowserLocation(this.startingUrl, { replaceCurrent: false });
6826
- return this.context.finishRoutingSession();
6827
- }
6828
- }
7058
+ this.repairBrowserHistoryAndUrlAfterGuardCancellation(this.locationChangeTriggerUrl, this.startingUrl);
7059
+ this.context.finishRoutingSession();
6829
7060
  }
6830
7061
  // @Trace()
6831
7062
  onRouterEnd(event) {
@@ -6833,12 +7064,10 @@ class WaitUntilPopStateDuringCanDeactivateInteractionFinishes extends EventClean
6833
7064
  }
6834
7065
  // @Trace()
6835
7066
  onRouterError(event) {
6836
- void this.ignore(event);
7067
+ this.ignore(event);
6837
7068
  }
6838
7069
  // @Trace()
6839
7070
  onPopState(event) {
6840
- this.popStateHandled = true;
6841
- this.popStateEventUrl = event.url;
6842
7071
  this.ignore(event);
6843
7072
  }
6844
7073
  canDeactivatePlace(component, currentUrl, nextUrl) {
@@ -6848,574 +7077,985 @@ class WaitUntilPopStateDuringCanDeactivateInteractionFinishes extends EventClean
6848
7077
  }
6849
7078
  }
6850
7079
 
6851
- class PopStateNavigation extends AbstractPopStateNavigation {
7080
+ /**
7081
+ * This session tracks the process of removing the last interaction context from the URL and provides a promise
7082
+ * the resolves when the process and completed. This case is special as the process involves a regular routing cycle
7083
+ * followed by a call to location.back(). The later triggers a url change with no other routing events. So this
7084
+ * class tracks when the first routing cycle finishes and then waits for the subsequent lone url change event.
7085
+ */
7086
+ class RemoveLastInteractionFromUrlNavigationSession extends NavigationSession {
7087
+ constructor(context, startingUrl) {
7088
+ super(context, startingUrl);
7089
+ this.isPopState = true;
7090
+ this.debugPropertyKeys = ['startingUrl', 'poppedHistoryUrl'];
7091
+ this.finished = Deferred.defer();
7092
+ }
7093
+ get isInteractionSync() {
7094
+ return true;
7095
+ }
7096
+ // @Trace()
7097
+ onPopState(event) {
7098
+ this.gotPopState = true;
7099
+ }
7100
+ // @Trace()
7101
+ onRouterStarted(event) {
7102
+ this.ignore(event);
7103
+ }
7104
+ // @Trace()
6852
7105
  onRouterCancelled(event) {
6853
- this.repairBrowserHistoryAndUrlAfterGuardCancellation();
7106
+ this.ignore(event);
7107
+ }
7108
+ // @Trace()
7109
+ onUrlChange(url) {
7110
+ }
7111
+ finishUp() {
6854
7112
  this.context.finishRoutingSession();
7113
+ this.finished.resolve(true);
6855
7114
  }
7115
+ // @Trace()
6856
7116
  onRouterEnd(event) {
6857
- this.context.finishRoutingSession(this.getVisits());
7117
+ if (this.gotPopState) {
7118
+ this.finishUp();
7119
+ }
6858
7120
  }
7121
+ // @Trace()
6859
7122
  handleCanDeactivateCancelledEventScenario(locationTriggerUrl) {
6860
- this.context.transitionTo(new WaitUntilPopStateDuringCanDeactivateInteractionFinishes(this.context, this.startingUrl, locationTriggerUrl, this.poppedHistoryUrl));
7123
+ lang.illegalState('onCanDeactivateInteractionCancelled not supported for activity context synchronisation since we should never leave a place');
7124
+ }
7125
+ get finishedPromise() {
7126
+ return this.finished.promise;
6861
7127
  }
6862
7128
  }
6863
7129
 
6864
- var PlaceAccessGuard;
6865
- (function (PlaceAccessGuard) {
6866
- class NoAuth {
6867
- // @Trace()
6868
- isAuthenticated() {
6869
- return true;
7130
+ class SynchroniseInteractionContextIdsWithRoute extends NavigationSession {
7131
+ constructor(context, startingUrl, wasTriggeredByPopState) {
7132
+ super(context, startingUrl);
7133
+ this.wasTriggeredByPopState = wasTriggeredByPopState;
7134
+ this.isPopState = false;
7135
+ }
7136
+ get isInteractionSync() {
7137
+ return true;
7138
+ }
7139
+ notifyActive() {
7140
+ // TODO: Do I still need this??
7141
+ setTimeout(() => {
7142
+ this.syncInteractionIdsWithRouter();
7143
+ });
7144
+ }
7145
+ // @Trace()
7146
+ onRouterEnd(event) {
7147
+ this.context.finishRoutingSession();
7148
+ }
7149
+ // @Trace()
7150
+ onRouterCancelled(event) {
7151
+ this.context.finishRoutingSession();
7152
+ }
7153
+ // @Trace()
7154
+ syncInteractionIdsWithRouter() {
7155
+ const currentIds = this.interactionServiceAdapter.getActiveInteractionContextIds();
7156
+ const previousIds = this.urlService.getCurrentLocationUrlSnapshot().getInteractionIds();
7157
+ // console.log(`---> synchroniseInteractionIds`, { is: currentIds.join(','), was: previousIds.join(',') });
7158
+ if (isEqual(currentIds, previousIds)) {
7159
+ // console.log('### Activity context ids were the same, skipping');
7160
+ this.context.finishRoutingSession();
6870
7161
  }
6871
- // @Trace()
6872
- isAuthorised(placeDefinition) {
6873
- return true;
7162
+ else {
7163
+ if (currentIds.length > previousIds.length) {
7164
+ const isFirstActivity = currentIds.length > previousIds.length && previousIds.length < 1;
7165
+ this.addActivityContextToRoute(currentIds, isFirstActivity);
7166
+ }
7167
+ else {
7168
+ this.removeActivityContextFromRoute(currentIds);
7169
+ }
6874
7170
  }
6875
7171
  }
6876
- PlaceAccessGuard.NoAuth = NoAuth;
6877
- })(PlaceAccessGuard || (PlaceAccessGuard = {}));
6878
-
6879
- class InteractionServiceRoutingAdapter {
6880
- constructor(activeInteractionContextIds, activeModalContext, createExclusiveInteractionContext) {
6881
- this.activeInteractionContextIds = activeInteractionContextIds;
6882
- this.activeModalContext = activeModalContext;
6883
- this.createExclusiveInteractionContext = createExclusiveInteractionContext;
7172
+ // @Trace()
7173
+ addActivityContextToRoute(activeInteractionContextIds, isFirst) {
7174
+ const urlSnapshot = this.urlService.getCurrentRouterSnapshot().updateInteractionIds(activeInteractionContextIds);
7175
+ this.context.navigateByUrl(urlSnapshot, {
7176
+ replaceUrl: !isFirst
7177
+ }).then(result => {
7178
+ if (!this.urlService.getCurrentLocationUrlSnapshot().hasInteractionIds(activeInteractionContextIds)) {
7179
+ lang$1.illegalState(`Expected url to be ${urlSnapshot.url} but was ${this.urlService.getCurrentLocationUrl()}`);
7180
+ // this.urlService.resetBrowserLocation(urlSnapshot.url, {replaceCurrent: !isFirst})
7181
+ }
7182
+ });
6884
7183
  }
6885
- isActive() {
6886
- return this.getActiveInteractionContextIds().length > 0;
7184
+ // @Trace()
7185
+ removeActivityContextFromRoute(activeInteractionContextId) {
7186
+ const urlSnapshot = this.urlService.getCurrentRouterSnapshot().updateInteractionIds(activeInteractionContextId);
7187
+ const isRemovingLastActivity = activeInteractionContextId.length < 1;
7188
+ if (isRemovingLastActivity) {
7189
+ if (this.wasTriggeredByPopState) {
7190
+ // console.log('removal was triggered by pop state, nothing to do.');
7191
+ // noop. Our url will be back to the non interaction version now so we dont' need to do anything.
7192
+ }
7193
+ else {
7194
+ // now we just pop our interaction id's from the browser history.
7195
+ // console.log(`Removal of the last activity wasn't triggered by pop state so we have to trigger one to clean the history`);
7196
+ const session = new RemoveLastInteractionFromUrlNavigationSession(this.context, this.urlService.getCurrentRouterUrl());
7197
+ this.context.transitionTo(session);
7198
+ this.urlService.back();
7199
+ }
7200
+ }
7201
+ else {
7202
+ // we've removed an interaction, but we still have remaining activities so we
7203
+ // update the url in place if it wasn't a pop state. If it was a pop state we need
7204
+ // to push it back up.
7205
+ // this.urlService.resetBrowserLocation(urlSnapshot.url, { replaceCurrent: !this.wasTriggeredByPopState });
7206
+ this.context.navigateByUrl(urlSnapshot, { replaceUrl: !this.wasTriggeredByPopState });
7207
+ }
6887
7208
  }
6888
- isModalActive() {
6889
- return !!this.activeModalContext.value;
7209
+ handleCanDeactivateCancelledEventScenario(newUrl) {
7210
+ lang$1.methodNotSupported();
7211
+ }
7212
+ }
7213
+
7214
+ /**
7215
+ * This state exists to handle all events while any kind of navigation is in progress. That way all other states can
7216
+ * happily ignore interaction contexts.
7217
+ * NOTE: This state is activated when ever an interaction is started. It might be better to split it into
7218
+ * different states for different scenarios, e.g. starting model, starting model during route guard etc.
7219
+ */
7220
+ class NavigatingDuringInteraction extends NavigationSession {
7221
+ constructor() {
7222
+ super(...arguments);
7223
+ this.isPopState = false;
6890
7224
  }
6891
7225
  // @Trace()
6892
- isComponentInteracting(component) {
6893
- return component.interactionContext && component.interactionContext.isActive();
7226
+ onRouterCancelled(event) {
7227
+ this.context.finishRoutingSession();
6894
7228
  }
6895
- getActiveInteractionContextIds() {
6896
- return this.activeInteractionContextIds.value;
7229
+ // @Trace()
7230
+ onRouterError(event) {
7231
+ // navigation was aborted.
7232
+ this.context.finishRoutingSession();
6897
7233
  }
6898
7234
  // @Trace()
6899
- cancelCurrentModalInteraction() {
6900
- return this.activeModalContext.value.cancelActiveActivity();
7235
+ onRouterEnd(event) {
7236
+ if (this.context.routerInteractionAdapter.isActive()) {
7237
+ this.context.transitionTo(new SynchroniseInteractionContextIdsWithRoute(this.context, this.startingUrl, false));
7238
+ }
7239
+ else {
7240
+ this.context.finishRoutingSession(this.createUpdatedVisit(event.urlAfterRedirects));
7241
+ }
6901
7242
  }
6902
7243
  // @Trace()
6903
- cancelComponentInteraction(component) {
6904
- return component.interactionContext.cancelActiveActivity();
7244
+ handleCanDeactivateCancelledEventScenario(locationTriggerUrl) {
7245
+ this.context.transitionTo(new WaitUntilLeavingInteractionTransitionCancelled(this.context, this.startingUrl, locationTriggerUrl));
6905
7246
  }
6906
7247
  }
6907
7248
 
6908
- class ModalInteractionContextFactory {
7249
+ class AbstractPopStateNavigation extends NavigationSession {
7250
+ constructor(context, startingUrl, poppedHistoryUrl) {
7251
+ super(context, startingUrl);
7252
+ this.poppedHistoryUrl = poppedHistoryUrl;
7253
+ this.isPopState = true;
7254
+ this.debugPropertyKeys = ['startingUrl', 'poppedHistoryUrl'];
7255
+ }
7256
+ // @Trace()
7257
+ repairBrowserHistoryAndUrlAfterGuardCancellation() {
7258
+ super.repairBrowserHistoryAndUrlAfterGuardCancellation(this.poppedHistoryUrl, this.startingUrl);
7259
+ }
6909
7260
  }
6910
7261
 
6911
- let inplaceMonitorCount = 0;
6912
- class InteractionService {
6913
- constructor(modelInteractionContextFactory) {
6914
- this.modelInteractionContextFactory = modelInteractionContextFactory;
6915
- this.garbage = new GarbageCollector();
6916
- // private readonly _activeModalContext = new MutableValueModel<InteractionContext>();
6917
- // private readonly _activeInlineContext = new MutableValueModel<InteractionContext>();
6918
- // private readonly _activeContext: ValueModelChain<InteractionContext>;
6919
- this._navigationInProgress = new DelegatingValueModel().withDefault(false);
6920
- const { chain, valueOf, before, when, after, observe, switchOn } = Dsl.disposeWith(this.garbage);
6921
- this.exclusiveInteractionRegistry = new InteractionService.ContextRegistry();
6922
- this.modalInteractionRegistry = new InteractionService.ContextRegistry();
6923
- this.inPlaceInteractionRegistry = new InteractionService.ContextRegistry();
6924
- this.modalInteractionRegistry.disableWhen(valueOf.any(this.exclusiveInteractionRegistry.active, this.modalInteractionRegistry.active).areTruthy());
6925
- this.inPlaceInteractionRegistry.disableWhen(valueOf.any(this.exclusiveInteractionRegistry.active, this.modalInteractionRegistry.active, this.inPlaceInteractionRegistry.active).areTruthy());
6926
- this.active = valueOf.any(this.inPlaceInteractionRegistry.active, this.modalInteractionRegistry.active).areTruthy();
6927
- // TODO: chain.concat(listOrValueModels) would be nice.
6928
- this.activeInteractionContextIds = chain(this.inPlaceInteractionRegistry.interactionContextIds)
6929
- .concat(this.modalInteractionRegistry.interactionContextIds);
6930
- this.activeModalContext = chain(this.modalInteractionRegistry.interactionContexts).first();
6931
- this.inModalInteraction = chain(this.activeModalContext).isNotNil();
6932
- }
6933
- isActive() {
6934
- return this.active.value;
7262
+ /**
7263
+ * This state exists to handle all events while any kind of navigation is in progress. That way all other states can
7264
+ * happily ignore interaction contexts.
7265
+ */
7266
+ class PopStateDuringInteractionNavigation extends AbstractPopStateNavigation {
7267
+ constructor(context, startingUrl, poppedHistoryUrl) {
7268
+ super(context, startingUrl, poppedHistoryUrl);
6935
7269
  }
6936
7270
  /**
6937
- * @deprecated use #createModalInteractionContextDisposedWith instead.
6938
- * @param disposable
7271
+ * Invoked when the place refuses to deactivate because of an unfinished interaction.
7272
+ * @param event
6939
7273
  */
6940
- createModalInteractionContextFor(disposable) {
6941
- return this.createModalInteractionContextDisposedWith(disposable);
7274
+ // @Trace()
7275
+ onRouterCancelled(event) {
7276
+ this.repairBrowserHistoryAndUrlAfterGuardCancellation();
7277
+ // NOTE: for now we need to wasTriggeredByPopState=false because we're resetting the url and history in the previous line.
7278
+ this.context.transitionTo(new SynchroniseInteractionContextIdsWithRoute(this.context, this.poppedHistoryUrl, false));
6942
7279
  }
6943
- /**
6944
- * Creates a new model interaction context that will be disposed along with the component.
6945
- * @param disposable
6946
- */
6947
- createModalInteractionContextDisposedWith(disposable) {
6948
- // TODO: look at making the registry the factory..
6949
- return this.modelInteractionContextFactory.createInteractionContext("modal", new InteractionService.ApiAdapter(this.placeRouter, this.modalInteractionRegistry));
7280
+ // @Trace()
7281
+ onRouterEnd(event) {
7282
+ // this.context.transitionTo(new SynchroniseInteractionContextIdsWithRoute(this.context, this.poppedHistoryUrl, false));
7283
+ this.context.finishRoutingSession();
6950
7284
  }
6951
- registerInplaceInteractionContext(interactionContext) {
6952
- // TODO: look at making the registry the factory..
6953
- // Todo: check for double registration.
6954
- // Todo: allow multiple inplace interactions..
6955
- interactionContext.onInplaceInteractionContextRegistered(`ip${++inplaceMonitorCount}`, new InteractionService.ApiAdapter(this.placeRouter, this.inPlaceInteractionRegistry));
6956
- }
6957
- /**
6958
- * Creates an interaction context that will prevent any other contexts from starting an
6959
- * activity until it is disposed. This is intended for use by the router for passing
6960
- * to PlaceComponent.canDeactivate(interactionContext). This ensures components don't
6961
- * try and interact in a way that we can't track and synchronise with the browser back
6962
- * button.
6963
- */
6964
- registerPlaceRouter(router) {
6965
- assert$1.isFalsey(this.placeRouter);
6966
- this.placeRouter = router;
6967
- this._navigationInProgress.setDelegate(this.placeRouter.navigationInProgress$);
6968
- const self = this;
6969
- return new InteractionServiceRoutingAdapter(this.activeInteractionContextIds, this.activeModalContext, () => {
6970
- return self.modelInteractionContextFactory.createInteractionContext("exclusive", new InteractionService.ApiAdapter(this.placeRouter, this.exclusiveInteractionRegistry));
6971
- });
7285
+ handleCanDeactivateCancelledEventScenario(newUrl) {
7286
+ this.illegalTransition('Leaving interaction after pop-state should\'t block so should never see a back button click');
6972
7287
  }
6973
7288
  }
6974
- InteractionService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: InteractionService, deps: [{ token: ModalInteractionContextFactory }], target: i0.ɵɵFactoryTarget.Injectable });
6975
- InteractionService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: InteractionService, providedIn: "root" });
6976
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: InteractionService, decorators: [{
6977
- type: Injectable,
6978
- args: [{
6979
- providedIn: "root"
6980
- }]
6981
- }], ctorParameters: function () { return [{ type: ModalInteractionContextFactory }]; } });
6982
- (function (InteractionService) {
6983
- /**
6984
- * Provides a mechanism for the service to keep track of what the API adapters are doing to
6985
- * ensure the rules are followed, i.e. modal or in-place interaction aren't started while
6986
- * an exclusive routing interaction is active.
6987
- */
6988
- class ContextRegistry extends GarbageCollector {
6989
- constructor() {
6990
- super();
6991
- this._interactions = new MutableListModel();
6992
- this._disabledDelegate = this.registerDisposable(new DelegatingValueModel().withDefault(false));
6993
- const { chain, valueOf, before, when, after, observe, switchOn } = Dsl.disposeWith(this);
6994
- this.active = chain(this._interactions).isNotEmpty();
6995
- this.interactionContextIds = chain(this._interactions).pluck("identifier");
6996
- }
6997
- get interactionContexts() {
6998
- return this._interactions.readonly;
6999
- }
7000
- start(context) {
7001
- this._interactions.push(context);
7002
- }
7003
- finish(context) {
7004
- this._interactions.remove(context);
7005
- }
7006
- isActive() {
7007
- return this.active.value;
7008
- }
7009
- disableWhen(disabled) {
7010
- this._disabledDelegate.setDelegate(disabled);
7011
- }
7012
- }
7013
- InteractionService.ContextRegistry = ContextRegistry;
7014
- class ApiAdapter extends GarbageCollector {
7015
- constructor(placeRouter, contextRegistry) {
7016
- super();
7017
- this.placeRouter = placeRouter;
7018
- this.contextRegistry = contextRegistry;
7019
- }
7020
- // @Trace()
7021
- notifyActive(context) {
7022
- assert$1.isTruthy(context.identifier);
7023
- this.contextRegistry.start(context);
7024
- return this.isNavigationInProgress() ? Promise.resolve() : this.placeRouter.syncInteractionContextIdsWithRouter();
7025
- }
7026
- // @Trace()
7027
- isNavigationInProgress() {
7028
- return this.placeRouter.navigationInProgress$.value;
7029
- }
7030
- // @Trace()
7031
- notifyFinished(context) {
7032
- this.contextRegistry.finish(context);
7033
- // :: Important ::
7034
- // This method will be traversed by both the place router (during can canDeactivate guards) and user land code
7035
- // (both when routing is idle and while it is active in PlaceComponent.canDeactivate()).
7036
- // The result of pushInteractionIdsToRoute will not start until after the current route finishes, and the
7037
- // current route won't finish until after this promise returns... Deadlock.
7038
- // So in order to keep this logic out of the activities we perform the check here and ensure that
7039
- // any interactions with the context while routing is active returns immediately.
7040
- return this.isNavigationInProgress() ?
7041
- Promise.resolve() :
7042
- this.placeRouter.syncInteractionContextIdsWithRouter();
7043
- }
7044
- }
7045
- InteractionService.ApiAdapter = ApiAdapter;
7046
- })(InteractionService || (InteractionService = {}));
7047
7289
 
7048
7290
  /**
7049
- * This a work around for the fact that an activated route with multiple segments doesn't
7050
- * include the segment params in the paramMap as well as each segment returns an empty
7051
- * param map even when `parameter`s has content.
7291
+ * This state handles the scenario where a link navigation triggered an interaction and the user clicked back a to cancel it.
7292
+ * The routing event sequence is different depending on the link that was clicked.
7293
+ *
7294
+ * NOTE: In angular prior to 10 the sequence of routing events was different depending on the initial link that was clicked.
7295
+ * This class used have ugle if/else code to handle it and a not that it should be split into sub states.
7296
+ * During the update to angular 10 I did this (as the tests for this scenario were failings). After doing so
7297
+ * it appears that angular now behaves the same in both cases. But rather that revert the changes I've left the
7298
+ * sub-state handling in in case it ever comes back.
7052
7299
  */
7053
- class ConsolidatedParameterMap {
7054
- constructor(urlSegments, paramMap) {
7055
- this.paramMaps = [];
7056
- // TODO: can we get all our params from teh url segments? If so we can drop the paramMap altogether.
7057
- const segmentParams = (urlSegments || []).map(s => new ParamMapAdapter(s.parameters));
7058
- this.paramMaps = segmentParams
7059
- .concat(paramMap)
7060
- .filter(m => !!m); // the activated route param map can be null
7061
- }
7062
- get(name) {
7063
- const paramMap = this.paramMaps.find(m => m.has(name));
7064
- return paramMap.get(name);
7300
+ class WaitUntilLinkTriggeredNavigationInteractionCancellationTypeDetermined extends EventCleanUpSession {
7301
+ constructor(context, startingUrl, clickedLinkUrl) {
7302
+ super(context, startingUrl);
7303
+ this.clickedLinkUrl = clickedLinkUrl;
7304
+ this.isPopState = false;
7305
+ this.clickedLinkMatchedBackButtonUrl = false;
7306
+ this.debugPropertyKeys = ['idle', 'startingUrl', 'clickedLinkUrl', 'firstCancelEventUrl', 'clickedLinkMatchedBackButtonUrl', 'popStateEventUrl'];
7065
7307
  }
7066
- getAll(name) {
7067
- const paramMap = this.paramMaps.find(m => m.has(name));
7068
- return paramMap.getAll(name);
7308
+ // @Trace()
7309
+ onRouterStarted(event) {
7310
+ this.ignore(event);
7069
7311
  }
7070
- has(name) {
7071
- return !!this.paramMaps.find(m => m.has(name));
7312
+ // @Trace()
7313
+ onRouterCancelled(event) {
7314
+ if (event.url === this.clickedLinkUrl) {
7315
+ this.context.transitionTo(new WaitForLinkSameAsBackToPlayOut(this.context, this.startingUrl, this.clickedLinkUrl));
7316
+ }
7317
+ else {
7318
+ this.context.transitionTo(new WaitForLinkDifferentFromBackToPlayOut(this.context, this.startingUrl, this.clickedLinkUrl));
7319
+ }
7072
7320
  }
7073
- get keys() {
7074
- return uniq(this.paramMaps.reduce((result, params) => result.concat(params.keys), []));
7321
+ canDeactivatePlace(component, currentUrl, nextUrl) {
7322
+ return __awaiter(this, void 0, void 0, function* () {
7323
+ return false;
7324
+ });
7075
7325
  }
7076
7326
  }
7077
- __decorate([
7078
- Memoize(),
7079
- __metadata("design:type", Array),
7080
- __metadata("design:paramtypes", [])
7081
- ], ConsolidatedParameterMap.prototype, "keys", null);
7082
- class ParamMapAdapter {
7083
- constructor(params) {
7084
- this.params = params;
7327
+ class WaitForLinkSameAsBackToPlayOut extends EventCleanUpSession {
7328
+ constructor(context, startingUrl, clickedLinkUrl) {
7329
+ super(context, startingUrl);
7330
+ this.clickedLinkUrl = clickedLinkUrl;
7331
+ this.isPopState = false;
7332
+ this.debugPropertyKeys = ['idle', 'startingUrl', 'clickedLinkUrl', 'popStateEventUrl'];
7085
7333
  }
7086
- get(name) {
7087
- return this.params[name];
7334
+ // @Trace()
7335
+ onRouterEnd(event) {
7336
+ this.ignore(event);
7088
7337
  }
7089
- getAll(name) {
7090
- const value = this.get(name);
7091
- return Array.isArray(value) ? value : [value];
7338
+ // @Trace()
7339
+ onRouterError(event) {
7340
+ this.ignore(event);
7092
7341
  }
7093
- has(name) {
7094
- return this.keys.includes(name);
7342
+ // @Trace()
7343
+ onPopState(event) {
7344
+ this.popStateEventUrl = event.url;
7345
+ this.ignore(event);
7095
7346
  }
7096
- get keys() {
7097
- return Object.keys(this.params);
7347
+ // @Trace()
7348
+ onRouterCancelled(event) {
7349
+ if (this.popStateEventUrl) {
7350
+ this.finaliseRouting();
7351
+ }
7352
+ }
7353
+ // @Trace()
7354
+ finaliseRouting() {
7355
+ this.repairBrowserHistoryAndUrlAfterGuardCancellation(this.clickedLinkUrl, this.startingUrl);
7356
+ return this.context.finishRoutingSession();
7357
+ }
7358
+ canDeactivatePlace(component, currentUrl, nextUrl) {
7359
+ return __awaiter(this, void 0, void 0, function* () {
7360
+ return false;
7361
+ });
7098
7362
  }
7099
7363
  }
7100
-
7101
- class Visit {
7102
- constructor(placeDefinition, visitParameters = {}) {
7103
- this.placeDefinition = placeDefinition;
7104
- this.visitParameters = visitParameters;
7364
+ // See the note above. This class is identical to the previous but I've left it here in case angular decides to
7365
+ // route differently in this scenario going forward.
7366
+ class WaitForLinkDifferentFromBackToPlayOut extends EventCleanUpSession {
7367
+ constructor(context, startingUrl, clickedLinkUrl) {
7368
+ super(context, startingUrl);
7369
+ this.clickedLinkUrl = clickedLinkUrl;
7370
+ this.isPopState = false;
7371
+ this.debugPropertyKeys = ['idle', 'startingUrl', 'clickedLinkUrl', 'popStateEventUrl'];
7105
7372
  }
7106
7373
  // @Trace()
7107
- getRouteId() {
7108
- return this.placeDefinition.getRouteIdFrom(this);
7374
+ onRouterEnd(event) {
7375
+ this.ignore(event);
7109
7376
  }
7110
7377
  // @Trace()
7111
- hasRouteId() {
7112
- return !isNil(this.getRouteId());
7113
- }
7114
- /**
7115
- * Returns the value of the place parameter with the specified name. The parameter
7116
- * name is taken from the `as` option, e.g. {as: 'aCustomName'} otherwise it is the
7117
- * same as the the ValueModel property name.
7118
- * @param parameter the visit parameter definition
7119
- */
7120
- getParameterValue(parameter) {
7121
- return isString(parameter) ? this.visitParameters[parameter] : this.visitParameters[parameter.name];
7378
+ onRouterError(event) {
7379
+ this.ignore(event);
7122
7380
  }
7123
7381
  // @Trace()
7124
- hasParameter(parameterDef) {
7125
- return Object.keys(this.visitParameters).includes(parameterDef.name);
7126
- }
7127
- replace(parameter, value) {
7128
- return new Visit(this.placeDefinition, Object.assign(Object.assign({}, this.visitParameters), { [parameter.name]: value }));
7382
+ onPopState(event) {
7383
+ this.popStateEventUrl = event.url;
7384
+ this.ignore(event);
7129
7385
  }
7130
- mergeRouteParameters(routeParams) {
7131
- // todo: whitelist parameters.
7132
- const routeParameterKeys = Object.keys(routeParams);
7133
- const params = {};
7134
- this.placeDefinition.getVisitParameterDefs().forEach(def => {
7135
- if (def.isRouteId || def.isRouteParameter) {
7136
- if (routeParameterKeys.includes(def.name)) {
7137
- params[def.name] = routeParams[def.name];
7138
- }
7139
- }
7140
- else {
7141
- // copy non route params as is, but only if they already exist otherwise we'll inject nil values and break the
7142
- // defaults and remember sanitisation process.
7143
- const value = this.getParameterValue(def);
7144
- if (this.hasParameter(def)) {
7145
- params[def.name] = value;
7146
- }
7147
- }
7148
- });
7149
- return new Visit(this.placeDefinition, params);
7386
+ // @Trace()
7387
+ onRouterCancelled(event) {
7388
+ if (this.popStateEventUrl) {
7389
+ this.finaliseRouting();
7390
+ }
7150
7391
  }
7151
7392
  // @Trace()
7152
- hasRoutingChangedFrom(other) {
7153
- const samePlace = other.placeDefinition === this.placeDefinition;
7154
- const currentParams = this.placeDefinition.getFormattedRouteParameters(this, true);
7155
- const otherParams = this.placeDefinition.getFormattedRouteParameters(other, true);
7156
- // console.log({currentParams, otherParams});
7157
- const sameRouteParameters = isEqual(currentParams, otherParams);
7158
- return !samePlace || !sameRouteParameters;
7159
- }
7160
- hasChangedFrom(other) {
7161
- const sameNonRouteParameters = isEqual(this.placeDefinition.getNonRouteParameters(this), this.placeDefinition.getNonRouteParameters(other));
7162
- return !sameNonRouteParameters || this.hasRoutingChangedFrom(other);
7393
+ finaliseRouting() {
7394
+ this.repairBrowserHistoryAndUrlAfterGuardCancellation(this.clickedLinkUrl, this.startingUrl);
7395
+ return this.context.finishRoutingSession();
7163
7396
  }
7164
- toDebugString() {
7165
- return Object.keys(this.visitParameters).map(k => `${k}=${this.visitParameters[k]}`).join(',');
7397
+ canDeactivatePlace(component, currentUrl, nextUrl) {
7398
+ return __awaiter(this, void 0, void 0, function* () {
7399
+ return false;
7400
+ });
7166
7401
  }
7167
7402
  }
7403
+ //
7404
+ // ### Router State Transition: null -> Navigating(startingUrl: /activities/dialogs;l=en, urlAfterRedirects: undefined)
7405
+ // ### ###### Router Event: NavigationStart
7406
+ // NavigationStart(id: 6, url: '/home')
7407
+ // NavigationStart {id: 6, url: "/home", navigationTrigger: "imperative", restoredState: null}
7408
+ // logger.js:39 Ignoring router event: NavigationStart -> /home :: Navigating(startingUrl: /activities/dialogs;l=en, urlAfterRedirects: undefined)
7409
+ // ### ###### Router Event: RoutesRecognized
7410
+ // RoutesRecognized(id: 6, url: '/home', urlAfterRedirects: '/home', state: Route(url:'', path:'') { Route(url:'home', path:'home') } )
7411
+ // RoutesRecognized {id: 6, url: "/home", urlAfterRedirects: "/home", state: RouterStateSnapshot}
7412
+ // ###### Router Event: GuardsCheckStart
7413
+ // GuardsCheckStart(id: 6, url: '/home', urlAfterRedirects: '/home', state: Route(url:'', path:'') { Route(url:'home', path:'home') } )
7414
+ // GuardsCheckStart {id: 6, url: "/home", urlAfterRedirects: "/home", state: RouterStateSnapshot}
7415
+ // logger.js:39 back button pressed during navigation session interaction promise
7416
+ // logger.js:39 cancelling current navigation activity..
7417
+ // logger.js:39 ### Router State Transition: Navigating(startingUrl: /activities/dialogs;l=en, urlAfterRedirects: undefined) -> WaitUntilLinkTriggeredNavigationInteractionCancellationEventsFinish(idle: undefined, startingUrl: /activities/dialogs;l=en, clickedLinkUrl: /home, firstCancelEventUrl: undefined, clickedLinkMatchedBackButtonUrl: false, popStateEventUrl: undefined)
7418
+ // ###### Router Event: GuardsCheckEnd
7419
+ // GuardsCheckEnd(id: 6, url: '/home', urlAfterRedirects: '/home', state: Route(url:'', path:'') { Route(url:'home', path:'home') } , shouldActivate: false)
7420
+ // GuardsCheckEnd {id: 6, url: "/home", urlAfterRedirects: "/home", state: RouterStateSnapshot, shouldActivate: false}
7421
+ // ###### Router Event: NavigationCancel
7422
+ // NavigationCancel(id: 6, url: '/home')
7423
+ // NavigationCancel {id: 6, url: "/home", reason: ""}
7424
+ // logger.js:54 WaitUntilLinkTriggeredNavigationInteractionCancellationEventsFinish.onRouterCancelled
7425
+ // logger.js:19 args NavigationCancel {id: 6, url: "/home", reason: ""}
7426
+ // logger.js:39 Ignoring router event: NavigationCancel -> /home :: WaitUntilLinkTriggeredNavigationInteractionCancellationEventsFinish(idle: undefined, startingUrl: /activities/dialogs;l=en, clickedLinkUrl: /home, firstCancelEventUrl: /home, clickedLinkMatchedBackButtonUrl: true, popStateEventUrl: undefined)
7427
+ // logger.js:28 <-- WaitUntilLinkTriggeredNavigationInteractionCancellationEventsFinish.onRouterCancelled undefined
7428
+ // logger.js:54 WaitUntilLinkTriggeredNavigationInteractionCancellationEventsFinish.onRouterEnd
7429
+ // logger.js:19 args NavigationEnd {id: -1, url: "", urlAfterRedirects: ""}
7430
+ // logger.js:54 WaitUntilLinkTriggeredNavigationInteractionCancellationEventsFinish.finaliseRouting
7431
+ // logger.js:39 WORK-AROUND: Updating browser location after pop state - see angular issue #13586
7432
+ // navigation-session.ts:129 replacing /activities/dialogs;l=en with /home
7433
+ // navigation-session.ts:131 pushing /activities/dialogs;l=en back onto the history.
7434
+ // ????? place-router.ts:281 ### Router Session Finished (was WaitUntilLinkTriggeredNavigationInteractionCancellationEventsFinish(idle: undefined, startingUrl: /activities/dialogs;l=en, clickedLinkUrl: /home, firstCancelEventUrl: /home, clickedLinkMatchedBackButtonUrl: true, popStateEventUrl: undefined))
7435
+ // logger.js:28 <-- WaitUntilLinkTriggeredNavigationInteractionCancellationEventsFinish.finaliseRouting undefined
7436
+ // logger.js:28 <-- WaitUntilLinkTriggeredNavigationInteractionCancellationEventsFinish.onRouterEnd undefined
7437
+ // ###### Router Event: NavigationStart
7438
+ // NavigationStart(id: 7, url: '/home')
7439
+ // NavigationStart {id: 7, url: "/home", navigationTrigger: "popstate", restoredState: {…}}
7440
+ // logger.js:39 ### Router State Transition: null -> PopStateNavigation(startingUrl: /activities/dialogs;l=en, poppedHistoryUrl: /home)
7441
+ // ###### Router Event: RoutesRecognized
7442
+ // RoutesRecognized(id: 7, url: '/home', urlAfterRedirects: '/home', state: Route(url:'', path:'') { Route(url:'home', path:'home') } )
7443
+ // RoutesRecognized {id: 7, url: "/home", urlAfterRedirects: "/home", state: RouterStateSnapshot}
7444
+ // ###### Router Event: GuardsCheckStart
7445
+ // GuardsCheckStart(id: 7, url: '/home', urlAfterRedirects: '/home', state: Route(url:'', path:'') { Route(url:'home', path:'home') } )
7168
7446
 
7169
- function extractPrimarySegments(urlTree) {
7170
- var _a, _b;
7171
- return (_b = (_a = urlTree.root.children.primary) === null || _a === void 0 ? void 0 : _a.segments) !== null && _b !== void 0 ? _b : [];
7172
- }
7173
- class UrlSnapshot {
7174
- // TODO: Update this accept a url Parser so it can be immutable and generate new trees on mutation using toString() are parseUrl.
7175
- constructor(urlSerializer, url) {
7176
- this.urlSerializer = urlSerializer;
7177
- this.url = url;
7178
- this.urlTree = urlSerializer.parse(url);
7447
+ class Navigating extends NavigationSession {
7448
+ constructor() {
7449
+ super(...arguments);
7450
+ this.isPopState = false;
7451
+ this.debugPropertyKeys = ['startingUrl', 'urlAfterRedirects'];
7179
7452
  }
7180
- // @Trace()
7181
- updateVisitSegments(visit) {
7182
- const newUrlTree = this.urlSerializer.parse(this.url);
7183
- // Ugly, but it works for now.
7184
- const segments = [...extractPrimarySegments(newUrlTree)];
7185
- const visitSegments = this.getSegmentsFor(visit);
7186
- const replaceAt = segments.findIndex(segment => segment.path === visitSegments[0].path);
7187
- // do not use the return value, it's the items that were removed!
7188
- segments.splice(replaceAt, visitSegments.length, ...visitSegments);
7189
- newUrlTree.root.children.primary.segments = segments;
7190
- return new UrlSnapshot(this.urlSerializer, newUrlTree.toString());
7453
+ onRouterCancelled(event) {
7454
+ // redirects come from our guards so we'll be processing parameter updates and need
7455
+ // to keep the same session running so we don't loose any accumulated state.
7456
+ if (event.code !== 0 /* NavigationCancellationCode.Redirect */) {
7457
+ this.context.finishRoutingSession();
7458
+ }
7191
7459
  }
7192
- appendVisit(visit) {
7193
- // TODO: make this work properly with visit parameters
7194
- return new UrlSnapshot(this.urlSerializer, this.url + "/" + visit.placeDefinition.path);
7460
+ onRouterError(event) {
7461
+ // navigation was aborted.
7462
+ this.context.finishRoutingSession();
7195
7463
  }
7196
- getPrimarySegments() {
7197
- return extractPrimarySegments(this.urlTree);
7464
+ onRouterEnd(event) {
7465
+ this.context.finishRoutingSession(this.createUpdatedVisit(event.urlAfterRedirects));
7198
7466
  }
7199
- /**
7200
- * Converts the visit into segments. Please not that these segments are not e
7201
- * @param visit
7202
- */
7203
- getSegmentsFor(visit) {
7204
- return visit.placeDefinition.hasRouteId() ?
7205
- [
7206
- // NOTE:
7207
- // It's important to attach the params to the root path and not the id. If we attach them
7208
- // to an empty id then the angular router won't match the pattern.
7209
- new UrlSegment(visit.placeDefinition.path, visit.placeDefinition.getFormattedRouteParameters(visit)),
7210
- new UrlSegment(visit.placeDefinition.getFormattedRouteId(visit), {})
7211
- ]
7212
- :
7213
- [
7214
- new UrlSegment(visit.placeDefinition.path, visit.placeDefinition.getFormattedRouteParameters(visit))
7215
- ];
7467
+ handleCanDeactivateCancelledEventScenario(newUrl) {
7468
+ this.context.transitionTo(new WaitUntilLinkTriggeredNavigationInteractionCancellationTypeDetermined(this.context, this.startingUrl, newUrl));
7216
7469
  }
7217
- includesPathOf(placeDef) {
7218
- return this.getPrimarySegments().find(s => s.path === placeDef.path);
7470
+ }
7471
+
7472
+ var NavigationContext;
7473
+ (function (NavigationContext) {
7474
+ class Impl {
7475
+ constructor(urlService, routerInteractionAdapter, navigateByUrl, transitionTo, finishRoutingSession) {
7476
+ this.urlService = urlService;
7477
+ this.routerInteractionAdapter = routerInteractionAdapter;
7478
+ this.navigateByUrl = navigateByUrl;
7479
+ this.transitionTo = transitionTo;
7480
+ this.finishRoutingSession = finishRoutingSession;
7481
+ }
7219
7482
  }
7220
- isLastPlaceInUrl(placeDef) {
7221
- return last(this.getPrimarySegments()).path === placeDef.path;
7483
+ NavigationContext.Impl = Impl;
7484
+ })(NavigationContext || (NavigationContext = {}));
7485
+
7486
+ /**
7487
+ * This state handles the scenario where a pop state triggered and interaction and the user clickeb back a second time to cancel it.
7488
+ * The sequence of routing events/state transitions is as follows.
7489
+ * -> Idle -> PopStateTransition (poppedHistoryUrl == page to go to, startingUrl = page to stay on )
7490
+ * -> confirm dialog shown.
7491
+ * -> click back
7492
+ * -> PopStateTransition -> CancelledDuringBackButtonNavigationInteraction(trigger url is the page before the popped history url)
7493
+ * -> NavigationCancel (for the previous back)
7494
+ * -> PopState
7495
+ * -> NavigationCancel
7496
+ */
7497
+ class WaitUntilPopStateDuringCanDeactivateInteractionFinishes extends EventCleanUpSession {
7498
+ constructor(context, startingUrl, locationChangeTriggerUrl, poppedHistoryUrl) {
7499
+ super(context, startingUrl);
7500
+ this.locationChangeTriggerUrl = locationChangeTriggerUrl;
7501
+ this.poppedHistoryUrl = poppedHistoryUrl;
7502
+ this.isPopState = false;
7503
+ this.firstCancelHandled = false;
7504
+ this.popStateHandled = false;
7505
+ this.debugPropertyKeys = ['idle', 'startingUrl', 'poppedHistoryUrl', 'locationChangeTriggerUrl', 'popStateEventUrl', 'firstCancelHandled', 'popStateHandled'];
7222
7506
  }
7223
- createVisitFor(placeDef) {
7224
- return new Visit(placeDef, new ConsolidatedParameterMap(this.getPrimarySegments()));
7507
+ // @Trace()
7508
+ onRouterStarted(event) {
7509
+ this.ignore(event);
7225
7510
  }
7226
- getInteractionIds() {
7227
- const queryParam = this.urlTree.queryParams[UrlSnapshot.INTERACTION_QUERY_PARAM];
7228
- if (queryParam) {
7229
- return UrlSnapshot.parseInteractionIds(queryParam);
7511
+ // @Trace()
7512
+ onRouterCancelled(event) {
7513
+ if (!this.firstCancelHandled) {
7514
+ this.firstCancelHandled = true;
7515
+ this.parentPageUrl = event.url;
7516
+ this.ignore(event);
7230
7517
  }
7231
7518
  else {
7232
- return [];
7519
+ if (this.popStateHandled) {
7520
+ const grandParentPageUrl = event.url;
7521
+ this.repairBrowserHistoryAndUrlAfterGuardCancellation(grandParentPageUrl, this.parentPageUrl);
7522
+ // we've had one more back click than normal so we need to add our initial url back in as well.
7523
+ this.resetBrowserLocation(this.startingUrl, { replaceCurrent: false });
7524
+ return this.context.finishRoutingSession();
7525
+ }
7233
7526
  }
7234
7527
  }
7235
- hasInteractions() {
7236
- return this.getInteractionIds().length > 0;
7237
- }
7238
- hasInteractionIds(ids) {
7239
- return isEqual(this.getInteractionIds(), ids);
7528
+ // @Trace()
7529
+ onRouterEnd(event) {
7530
+ this.ignore(event);
7240
7531
  }
7241
7532
  // @Trace()
7242
- updateInteractionIds(ids) {
7243
- if (ids.length === 0) {
7244
- return this.removeInteractionIds();
7245
- }
7246
- else {
7247
- const urlTree = this.urlSerializer.parse(this.url);
7248
- urlTree.queryParams[UrlSnapshot.INTERACTION_QUERY_PARAM] = UrlSnapshot.createPathIdFor(ids);
7249
- return new UrlSnapshot(this.urlSerializer, urlTree.toString());
7250
- }
7533
+ onRouterError(event) {
7534
+ void this.ignore(event);
7251
7535
  }
7252
7536
  // @Trace()
7253
- removeInteractionIds() {
7254
- const urlTree = this.urlSerializer.parse(this.url);
7255
- if (urlTree.queryParams && urlTree.queryParams[UrlSnapshot.INTERACTION_QUERY_PARAM]) {
7256
- urlTree.queryParams = {}; //[UrlSnapshot.INTERACTION_ROUTER_OUTLET]
7257
- }
7258
- return new UrlSnapshot(this.urlSerializer, urlTree.toString());
7537
+ onPopState(event) {
7538
+ this.popStateHandled = true;
7539
+ this.popStateEventUrl = event.url;
7540
+ this.ignore(event);
7259
7541
  }
7260
- toString() {
7261
- return `UrlSnapshot(${this.url})`;
7542
+ canDeactivatePlace(component, currentUrl, nextUrl) {
7543
+ return __awaiter(this, void 0, void 0, function* () {
7544
+ return false;
7545
+ });
7262
7546
  }
7263
7547
  }
7264
- __decorate([
7265
- Memoize(),
7266
- __metadata("design:type", Function),
7267
- __metadata("design:paramtypes", []),
7268
- __metadata("design:returntype", Array)
7269
- ], UrlSnapshot.prototype, "getPrimarySegments", null);
7270
- (function (UrlSnapshot) {
7271
- UrlSnapshot.INTERACTION_QUERY_PARAM = 'aup-interactions';
7272
- UrlSnapshot.INTERACTION_ID_SEPARATOR = '--';
7273
- function parseInteractionIds(path) {
7274
- return path.split(UrlSnapshot.INTERACTION_ID_SEPARATOR);
7548
+
7549
+ class PopStateNavigation extends AbstractPopStateNavigation {
7550
+ onRouterCancelled(event) {
7551
+ this.repairBrowserHistoryAndUrlAfterGuardCancellation();
7552
+ this.context.finishRoutingSession();
7275
7553
  }
7276
- UrlSnapshot.parseInteractionIds = parseInteractionIds;
7277
- function createPathIdFor(interactionIds) {
7278
- return interactionIds.join(UrlSnapshot.INTERACTION_ID_SEPARATOR);
7554
+ onRouterEnd(event) {
7555
+ this.context.finishRoutingSession(this.createUpdatedVisit(event.urlAfterRedirects));
7279
7556
  }
7280
- UrlSnapshot.createPathIdFor = createPathIdFor;
7281
- })(UrlSnapshot || (UrlSnapshot = {}));
7557
+ handleCanDeactivateCancelledEventScenario(locationTriggerUrl) {
7558
+ this.context.transitionTo(new WaitUntilPopStateDuringCanDeactivateInteractionFinishes(this.context, this.startingUrl, locationTriggerUrl, this.poppedHistoryUrl));
7559
+ }
7560
+ }
7282
7561
 
7283
- class UrlService {
7284
- constructor(angularRouter, angularLocation, urlSerializer) {
7285
- this.angularRouter = angularRouter;
7286
- this.angularLocation = angularLocation;
7287
- this.urlSerializer = urlSerializer;
7562
+ var PlaceAccessGuard;
7563
+ (function (PlaceAccessGuard) {
7564
+ class NoAuth {
7565
+ // @Trace()
7566
+ isAuthenticated() {
7567
+ return true;
7568
+ }
7569
+ // @Trace()
7570
+ isAuthorised(placeDefinition) {
7571
+ return true;
7572
+ }
7288
7573
  }
7289
- parseUrl(url) {
7290
- return new UrlSnapshot(this.urlSerializer, url);
7574
+ PlaceAccessGuard.NoAuth = NoAuth;
7575
+ })(PlaceAccessGuard || (PlaceAccessGuard = {}));
7576
+
7577
+ class InteractionServiceRoutingAdapter {
7578
+ constructor(activeInteractionContextIds, activeModalContext, createExclusiveInteractionContext) {
7579
+ this.activeInteractionContextIds = activeInteractionContextIds;
7580
+ this.activeModalContext = activeModalContext;
7581
+ this.createExclusiveInteractionContext = createExclusiveInteractionContext;
7291
7582
  }
7292
- createUrlSnapshot(...visits) {
7293
- const bits = [];
7294
- visits.forEach(v => {
7295
- bits.push(this.parseUrl(`${v.placeDefinition.path}`).updateVisitSegments(v).url);
7296
- });
7297
- return this.parseUrl(bits.join(''));
7583
+ isActive() {
7584
+ return this.getActiveInteractionContextIds().length > 0;
7298
7585
  }
7299
- getCurrentRouterUrl() {
7300
- return this.angularRouter.routerState ? this.angularRouter.routerState.snapshot.url : null;
7586
+ isModalActive() {
7587
+ return !!this.activeModalContext.value;
7301
7588
  }
7302
- getCurrentLocationUrl() {
7303
- return this.angularLocation.path();
7589
+ // @Trace()
7590
+ isComponentInteracting(component) {
7591
+ return component.interactionContext && component.interactionContext.isActive();
7592
+ }
7593
+ getActiveInteractionContextIds() {
7594
+ return this.activeInteractionContextIds.value;
7595
+ }
7596
+ // @Trace()
7597
+ cancelCurrentModalInteraction() {
7598
+ return this.activeModalContext.value.cancelActiveActivity();
7599
+ }
7600
+ // @Trace()
7601
+ cancelComponentInteraction(component) {
7602
+ return component.interactionContext.cancelActiveActivity();
7603
+ }
7604
+ }
7605
+
7606
+ class ModalInteractionContextFactory {
7607
+ }
7608
+
7609
+ let inplaceMonitorCount = 0;
7610
+ class InteractionService {
7611
+ constructor(modelInteractionContextFactory) {
7612
+ this.modelInteractionContextFactory = modelInteractionContextFactory;
7613
+ this.garbage = new GarbageCollector();
7614
+ // private readonly _activeModalContext = new MutableValueModel<InteractionContext>();
7615
+ // private readonly _activeInlineContext = new MutableValueModel<InteractionContext>();
7616
+ // private readonly _activeContext: ValueModelChain<InteractionContext>;
7617
+ this._navigationInProgress = new DelegatingValueModel().withDefault(false);
7618
+ const { chain, valueOf, before, when, after, observe, switchOn } = Dsl.disposeWith(this.garbage);
7619
+ this.exclusiveInteractionRegistry = new InteractionService.ContextRegistry();
7620
+ this.modalInteractionRegistry = new InteractionService.ContextRegistry();
7621
+ this.inPlaceInteractionRegistry = new InteractionService.ContextRegistry();
7622
+ this.modalInteractionRegistry.disableWhen(valueOf.any(this.exclusiveInteractionRegistry.active, this.modalInteractionRegistry.active).areTruthy());
7623
+ this.inPlaceInteractionRegistry.disableWhen(valueOf.any(this.exclusiveInteractionRegistry.active, this.modalInteractionRegistry.active, this.inPlaceInteractionRegistry.active).areTruthy());
7624
+ this.active = valueOf.any(this.inPlaceInteractionRegistry.active, this.modalInteractionRegistry.active).areTruthy();
7625
+ // TODO: chain.concat(listOrValueModels) would be nice.
7626
+ this.activeInteractionContextIds = chain(this.inPlaceInteractionRegistry.interactionContextIds)
7627
+ .concat(this.modalInteractionRegistry.interactionContextIds);
7628
+ this.activeModalContext = chain(this.modalInteractionRegistry.interactionContexts).first();
7629
+ this.inModalInteraction = chain(this.activeModalContext).isNotNil();
7630
+ }
7631
+ isActive() {
7632
+ return this.active.value;
7304
7633
  }
7305
7634
  /**
7306
- * Return the a UrlSnapshot using the browsers current location. Note this may not be the same
7307
- * as the routers current url.
7635
+ * @deprecated use #createModalInteractionContextDisposedWith instead.
7636
+ * @param disposable
7308
7637
  */
7309
- getCurrentLocationUrlSnapshot() {
7310
- return this.parseUrl(this.getCurrentLocationUrl());
7638
+ createModalInteractionContextFor(disposable) {
7639
+ return this.createModalInteractionContextDisposedWith(disposable);
7311
7640
  }
7312
7641
  /**
7313
- * Return the a UrlSnapshot using the routers current state. This may not be the same as
7314
- * the browsers actual url.
7642
+ * Creates a new model interaction context that will be disposed along with the component.
7643
+ * @param disposable
7315
7644
  */
7316
- getCurrentRouterSnapshot() {
7317
- return this.parseUrl(this.getCurrentRouterUrl());
7318
- }
7319
- getActiveInteractionIdsFromUrl(url) {
7320
- return this.parseUrl(url).getInteractionIds();
7321
- }
7322
- hasActiveInteractions(url) {
7323
- return this.getActiveInteractionIdsFromUrl(url).length > 0;
7645
+ createModalInteractionContextDisposedWith(disposable) {
7646
+ // TODO: look at making the registry the factory..
7647
+ return this.modelInteractionContextFactory.createInteractionContext("modal", new InteractionService.ApiAdapter(this.placeRouter, this.modalInteractionRegistry));
7324
7648
  }
7325
- resetBrowserLocation(url, options) {
7326
- options.replaceCurrent ? this.angularLocation.replaceState(url) : this.angularLocation.go(url);
7649
+ registerInplaceInteractionContext(interactionContext) {
7650
+ // TODO: look at making the registry the factory..
7651
+ // Todo: check for double registration.
7652
+ // Todo: allow multiple inplace interactions..
7653
+ interactionContext.onInplaceInteractionContextRegistered(`ip${++inplaceMonitorCount}`, new InteractionService.ApiAdapter(this.placeRouter, this.inPlaceInteractionRegistry));
7327
7654
  }
7328
- back() {
7329
- this.angularLocation.back();
7655
+ /**
7656
+ * Creates an interaction context that will prevent any other contexts from starting an
7657
+ * activity until it is disposed. This is intended for use by the router for passing
7658
+ * to PlaceComponent.canDeactivate(interactionContext). This ensures components don't
7659
+ * try and interact in a way that we can't track and synchronise with the browser back
7660
+ * button.
7661
+ */
7662
+ registerPlaceRouter(router) {
7663
+ assert$1.isFalsey(this.placeRouter);
7664
+ this.placeRouter = router;
7665
+ this._navigationInProgress.setDelegate(this.placeRouter.navigationInProgress$);
7666
+ const self = this;
7667
+ return new InteractionServiceRoutingAdapter(this.activeInteractionContextIds, this.activeModalContext, () => {
7668
+ return self.modelInteractionContextFactory.createInteractionContext("exclusive", new InteractionService.ApiAdapter(this.placeRouter, this.exclusiveInteractionRegistry));
7669
+ });
7330
7670
  }
7331
7671
  }
7332
- UrlService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: UrlService, deps: [{ token: i1$4.Router }, { token: i1$1.Location }, { token: i1$4.UrlSerializer }], target: i0.ɵɵFactoryTarget.Injectable });
7333
- UrlService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: UrlService, providedIn: 'root' });
7334
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: UrlService, decorators: [{
7672
+ InteractionService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: InteractionService, deps: [{ token: ModalInteractionContextFactory }], target: i0.ɵɵFactoryTarget.Injectable });
7673
+ InteractionService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: InteractionService, providedIn: "root" });
7674
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: InteractionService, decorators: [{
7335
7675
  type: Injectable,
7336
7676
  args: [{
7337
- providedIn: 'root'
7677
+ providedIn: "root"
7338
7678
  }]
7339
- }], ctorParameters: function () { return [{ type: i1$4.Router }, { type: i1$1.Location }, { type: i1$4.UrlSerializer }]; } });
7340
-
7341
- class PlaceHistory {
7342
- constructor() {
7343
- this._archive = new Map();
7344
- this.placeHistoryDepth = 4;
7679
+ }], ctorParameters: function () { return [{ type: ModalInteractionContextFactory }]; } });
7680
+ (function (InteractionService) {
7681
+ /**
7682
+ * Provides a mechanism for the service to keep track of what the API adapters are doing to
7683
+ * ensure the rules are followed, i.e. modal or in-place interaction aren't started while
7684
+ * an exclusive routing interaction is active.
7685
+ */
7686
+ class ContextRegistry extends GarbageCollector {
7687
+ constructor() {
7688
+ super();
7689
+ this._interactions = new MutableListModel();
7690
+ this._disabledDelegate = this.registerDisposable(new DelegatingValueModel().withDefault(false));
7691
+ const { chain, valueOf, before, when, after, observe, switchOn } = Dsl.disposeWith(this);
7692
+ this.active = chain(this._interactions).isNotEmpty();
7693
+ this.interactionContextIds = chain(this._interactions).pluck("identifier");
7694
+ }
7695
+ get interactionContexts() {
7696
+ return this._interactions.readonly;
7697
+ }
7698
+ start(context) {
7699
+ this._interactions.push(context);
7700
+ }
7701
+ finish(context) {
7702
+ this._interactions.remove(context);
7703
+ }
7704
+ isActive() {
7705
+ return this.active.value;
7706
+ }
7707
+ disableWhen(disabled) {
7708
+ this._disabledDelegate.setDelegate(disabled);
7709
+ }
7345
7710
  }
7346
- notifyNavigationStarted() {
7347
- if (this._activeVisits) {
7348
- this.archive(this._activeVisits.visits);
7349
- this._previousVisits = this._activeVisits;
7711
+ InteractionService.ContextRegistry = ContextRegistry;
7712
+ class ApiAdapter extends GarbageCollector {
7713
+ constructor(placeRouter, contextRegistry) {
7714
+ super();
7715
+ this.placeRouter = placeRouter;
7716
+ this.contextRegistry = contextRegistry;
7717
+ }
7718
+ // @Trace()
7719
+ notifyActive(context) {
7720
+ assert$1.isTruthy(context.identifier);
7721
+ this.contextRegistry.start(context);
7722
+ return this.isNavigationInProgress() ? Promise.resolve() : this.placeRouter.syncInteractionContextIdsWithRouter();
7723
+ }
7724
+ // @Trace()
7725
+ isNavigationInProgress() {
7726
+ return this.placeRouter.navigationInProgress$.value;
7727
+ }
7728
+ // @Trace()
7729
+ notifyFinished(context) {
7730
+ this.contextRegistry.finish(context);
7731
+ // :: Important ::
7732
+ // This method will be traversed by both the place router (during can canDeactivate guards) and user land code
7733
+ // (both when routing is idle and while it is active in PlaceComponent.canDeactivate()).
7734
+ // The result of pushInteractionIdsToRoute will not start until after the current route finishes, and the
7735
+ // current route won't finish until after this promise returns... Deadlock.
7736
+ // So in order to keep this logic out of the activities we perform the check here and ensure that
7737
+ // any interactions with the context while routing is active returns immediately.
7738
+ return this.isNavigationInProgress() ?
7739
+ Promise.resolve() :
7740
+ this.placeRouter.syncInteractionContextIdsWithRouter();
7350
7741
  }
7351
7742
  }
7352
- notifyNavigationFinished(visits) {
7353
- this._activeVisits = new PlaceHistory.VisitRecord(visits);
7743
+ InteractionService.ApiAdapter = ApiAdapter;
7744
+ })(InteractionService || (InteractionService = {}));
7745
+
7746
+ /**
7747
+ * This a work around for the fact that an activated route with multiple segments doesn't
7748
+ * include the segment params in the paramMap as well as each segment returns an empty
7749
+ * param map even when `parameter`s has content.
7750
+ */
7751
+ class ConsolidatedParameterMap {
7752
+ constructor(urlSegments, paramMap) {
7753
+ this.paramMaps = [];
7754
+ // TODO: can we get all our params from teh url segments? If so we can drop the paramMap altogether.
7755
+ const segmentParams = (urlSegments || []).map(s => new ParamMapAdapter(s.parameters));
7756
+ this.paramMaps = segmentParams
7757
+ .concat(paramMap)
7758
+ .filter(m => !!m); // the activated route param map can be null
7354
7759
  }
7355
- updateVisit(visit) {
7356
- assert.isTruthy(this._activeVisits);
7357
- this._activeVisits.update(visit);
7760
+ get(name) {
7761
+ const paramMap = this.paramMaps.find(m => m.has(name));
7762
+ return paramMap.get(name);
7358
7763
  }
7359
- lastVisitIncluded(placeDef) {
7360
- var _a;
7361
- return !!((_a = this._previousVisits) === null || _a === void 0 ? void 0 : _a.getVisitFor(placeDef));
7764
+ getAll(name) {
7765
+ const paramMap = this.paramMaps.find(m => m.has(name));
7766
+ return paramMap.getAll(name);
7362
7767
  }
7363
- getMostRecentVisitFor(placeDef) {
7364
- return first(this.getHistory(placeDef));
7768
+ has(name) {
7769
+ return !!this.paramMaps.find(m => m.has(name));
7365
7770
  }
7366
- getHistory(placeDef) {
7367
- let history = this._archive.get(placeDef);
7368
- if (!history) {
7369
- history = [];
7370
- this.setHistory(placeDef, history);
7371
- }
7372
- return history;
7771
+ get keys() {
7772
+ return uniq(this.paramMaps.reduce((result, params) => result.concat(params.keys), []));
7373
7773
  }
7374
- setHistory(placeDef, history) {
7375
- this._archive.set(placeDef, history);
7774
+ }
7775
+ __decorate([
7776
+ Memoize(),
7777
+ __metadata("design:type", Array),
7778
+ __metadata("design:paramtypes", [])
7779
+ ], ConsolidatedParameterMap.prototype, "keys", null);
7780
+ class ParamMapAdapter {
7781
+ constructor(params) {
7782
+ this.params = params;
7376
7783
  }
7377
- archive(visits) {
7378
- visits.forEach(state => {
7379
- const history = this.getHistory(state.placeDefinition);
7380
- const previousState = first(history);
7381
- if (!previousState || state.hasChangedFrom(previousState)) {
7382
- history.unshift(state); // LIFO
7383
- this.setHistory(state.placeDefinition, history.slice(0, this.placeHistoryDepth));
7384
- }
7385
- });
7784
+ get(name) {
7785
+ return this.params[name];
7386
7786
  }
7387
- }
7388
- PlaceHistory.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: PlaceHistory, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
7389
- PlaceHistory.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: PlaceHistory, providedIn: 'root' });
7390
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: PlaceHistory, decorators: [{
7391
- type: Injectable,
7392
- args: [{
7393
- providedIn: 'root'
7394
- }]
7395
- }], ctorParameters: function () { return []; } });
7396
- (function (PlaceHistory) {
7397
- class VisitRecord {
7398
- constructor(visits) {
7399
- this.visits = visits;
7400
- }
7401
- update(visit) {
7402
- this.visits = this.visits.filter(v => v.placeDefinition !== visit.placeDefinition).concat(visit);
7403
- }
7404
- getVisitFor(placeDef) {
7405
- return this.visits.find(v => v.placeDefinition === placeDef);
7406
- }
7787
+ getAll(name) {
7788
+ const value = this.get(name);
7789
+ return Array.isArray(value) ? value : [value];
7407
7790
  }
7408
- PlaceHistory.VisitRecord = VisitRecord;
7409
- // export class Query {
7410
- // private _history: Visit.State[];
7411
- // private _places: Place[];
7412
- // private _predicate: (visit: any) => boolean;
7413
- // private _limit: number;
7414
- //
7415
- // constructor(history, limit = history.length) {
7416
- // this._history = history;
7417
- // this._places = [];
7418
- // this._predicate = (visit => true);
7791
+ has(name) {
7792
+ return this.keys.includes(name);
7793
+ }
7794
+ get keys() {
7795
+ return Object.keys(this.params);
7796
+ }
7797
+ }
7798
+
7799
+ function extractPrimaryUrlSegments(urlTree) {
7800
+ var _a, _b;
7801
+ return (_b = (_a = urlTree.root.children.primary) === null || _a === void 0 ? void 0 : _a.segments) !== null && _b !== void 0 ? _b : [];
7802
+ }
7803
+ class UrlSnapshot {
7804
+ // TODO: Update this accept a url Parser so it can be immutable and generate new trees on mutation using toString() are parseUrl.
7805
+ constructor(urlSerializer, url) {
7806
+ this.urlSerializer = urlSerializer;
7807
+ this.url = url;
7808
+ this.urlTree = urlSerializer.parse(url);
7809
+ }
7810
+ // @Trace()
7811
+ updateVisitSegment(visitSegment) {
7812
+ const newUrlTree = this.urlSerializer.parse(this.url);
7813
+ // Ugly, but it works for now.
7814
+ const segments = [...extractPrimaryUrlSegments(newUrlTree)];
7815
+ const urlSegments = this.getUrlSegmentsForVisitSegment(visitSegment);
7816
+ const replaceAt = segments.findIndex(segment => segment.path === urlSegments[0].path);
7817
+ // do not use the return value, it's the items that were removed!
7818
+ segments.splice(replaceAt, urlSegments.length, ...urlSegments);
7819
+ newUrlTree.root.children.primary.segments = segments;
7820
+ return new UrlSnapshot(this.urlSerializer, newUrlTree.toString());
7821
+ }
7822
+ appendSegment(visitSegment) {
7823
+ // TODO: make this work properly with visit parameters
7824
+ return new UrlSnapshot(this.urlSerializer, this.url + "/" + visitSegment.placeDefinition.path);
7825
+ }
7826
+ getPrimaryUrlSegments() {
7827
+ return extractPrimaryUrlSegments(this.urlTree);
7828
+ }
7829
+ /**
7830
+ * Converts the visit into segments. Please not that these segments are not e
7831
+ * @param visitSegment
7832
+ */
7833
+ getUrlSegmentsForVisitSegment(visitSegment) {
7834
+ return visitSegment.placeDefinition.hasRouteId() ?
7835
+ [
7836
+ // NOTE:
7837
+ // It's important to attach the params to the root path and not the id. If we attach them
7838
+ // to an empty id then the angular router won't match the pattern.
7839
+ new UrlSegment(visitSegment.placeDefinition.path, visitSegment.placeDefinition.getFormattedRouteParameters(visitSegment)),
7840
+ new UrlSegment(visitSegment.placeDefinition.getFormattedRouteId(visitSegment), {})
7841
+ ]
7842
+ :
7843
+ [
7844
+ new UrlSegment(visitSegment.placeDefinition.path, visitSegment.placeDefinition.getFormattedRouteParameters(visitSegment))
7845
+ ];
7846
+ }
7847
+ includesPathOf(placeDef) {
7848
+ return this.getPrimaryUrlSegments().find(s => s.path === placeDef.path);
7849
+ }
7850
+ isLastPlaceInUrl(placeDef) {
7851
+ return last$1(this.getPrimaryUrlSegments()).path === placeDef.path;
7852
+ }
7853
+ createVisitSegmentFor(placeDef) {
7854
+ return new VisitSegment(placeDef, new ConsolidatedParameterMap(this.getPrimaryUrlSegments()));
7855
+ }
7856
+ getInteractionIds() {
7857
+ const queryParam = this.urlTree.queryParams[UrlSnapshot.INTERACTION_QUERY_PARAM];
7858
+ if (queryParam) {
7859
+ return UrlSnapshot.parseInteractionIds(queryParam);
7860
+ }
7861
+ else {
7862
+ return [];
7863
+ }
7864
+ }
7865
+ hasInteractions() {
7866
+ return this.getInteractionIds().length > 0;
7867
+ }
7868
+ hasInteractionIds(ids) {
7869
+ return isEqual(this.getInteractionIds(), ids);
7870
+ }
7871
+ // @Trace()
7872
+ updateInteractionIds(ids) {
7873
+ if (ids.length === 0) {
7874
+ return this.removeInteractionIds();
7875
+ }
7876
+ else {
7877
+ const urlTree = this.urlSerializer.parse(this.url);
7878
+ urlTree.queryParams[UrlSnapshot.INTERACTION_QUERY_PARAM] = UrlSnapshot.createPathIdFor(ids);
7879
+ return new UrlSnapshot(this.urlSerializer, urlTree.toString());
7880
+ }
7881
+ }
7882
+ // @Trace()
7883
+ removeInteractionIds() {
7884
+ const urlTree = this.urlSerializer.parse(this.url);
7885
+ if (urlTree.queryParams && urlTree.queryParams[UrlSnapshot.INTERACTION_QUERY_PARAM]) {
7886
+ urlTree.queryParams = {}; //[UrlSnapshot.INTERACTION_ROUTER_OUTLET]
7887
+ }
7888
+ return new UrlSnapshot(this.urlSerializer, urlTree.toString());
7889
+ }
7890
+ toString() {
7891
+ return `UrlSnapshot(${this.url})`;
7892
+ }
7893
+ containsVisitSegment(segment) {
7894
+ return !!this.getPrimaryUrlSegments().find(s => s.path === segment.placeDefinition.path);
7895
+ }
7896
+ }
7897
+ __decorate([
7898
+ Memoize(),
7899
+ __metadata("design:type", Function),
7900
+ __metadata("design:paramtypes", []),
7901
+ __metadata("design:returntype", Array)
7902
+ ], UrlSnapshot.prototype, "getPrimaryUrlSegments", null);
7903
+ (function (UrlSnapshot) {
7904
+ UrlSnapshot.INTERACTION_QUERY_PARAM = 'aup-interactions';
7905
+ UrlSnapshot.INTERACTION_ID_SEPARATOR = '--';
7906
+ function parseInteractionIds(path) {
7907
+ return path.split(UrlSnapshot.INTERACTION_ID_SEPARATOR);
7908
+ }
7909
+ UrlSnapshot.parseInteractionIds = parseInteractionIds;
7910
+ function createPathIdFor(interactionIds) {
7911
+ return interactionIds.join(UrlSnapshot.INTERACTION_ID_SEPARATOR);
7912
+ }
7913
+ UrlSnapshot.createPathIdFor = createPathIdFor;
7914
+ })(UrlSnapshot || (UrlSnapshot = {}));
7915
+
7916
+ class UrlService {
7917
+ constructor(angularRouter, angularLocation, urlSerializer) {
7918
+ this.angularRouter = angularRouter;
7919
+ this.angularLocation = angularLocation;
7920
+ this.urlSerializer = urlSerializer;
7921
+ }
7922
+ parseUrl(url) {
7923
+ return new UrlSnapshot(this.urlSerializer, url);
7924
+ }
7925
+ createUrlSnapshot(visits) {
7926
+ const bits = [];
7927
+ visits.forEach(v => {
7928
+ bits.push(this.parseUrl(`${v.placeDefinition.path}`).updateVisitSegment(v).url);
7929
+ });
7930
+ return this.parseUrl(bits.join(''));
7931
+ }
7932
+ getCurrentRouterUrl() {
7933
+ return this.angularRouter.routerState ? this.angularRouter.routerState.snapshot.url : null;
7934
+ }
7935
+ getCurrentLocationUrl() {
7936
+ return this.angularLocation.path();
7937
+ }
7938
+ /**
7939
+ * Return the a UrlSnapshot using the browsers current location. Note this may not be the same
7940
+ * as the routers current url.
7941
+ */
7942
+ getCurrentLocationUrlSnapshot() {
7943
+ return this.parseUrl(this.getCurrentLocationUrl());
7944
+ }
7945
+ /**
7946
+ * Return the a UrlSnapshot using the routers current state. This may not be the same as
7947
+ * the browsers actual url.
7948
+ */
7949
+ getCurrentRouterSnapshot() {
7950
+ return this.parseUrl(this.getCurrentRouterUrl());
7951
+ }
7952
+ getActiveInteractionIdsFromUrl(url) {
7953
+ return this.parseUrl(url).getInteractionIds();
7954
+ }
7955
+ hasActiveInteractions(url) {
7956
+ return this.getActiveInteractionIdsFromUrl(url).length > 0;
7957
+ }
7958
+ resetBrowserLocation(url, options) {
7959
+ options.replaceCurrent ? this.angularLocation.replaceState(url) : this.angularLocation.go(url);
7960
+ }
7961
+ back() {
7962
+ this.angularLocation.back();
7963
+ }
7964
+ }
7965
+ UrlService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: UrlService, deps: [{ token: i1$4.Router }, { token: i1$1.Location }, { token: i1$4.UrlSerializer }], target: i0.ɵɵFactoryTarget.Injectable });
7966
+ UrlService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: UrlService, providedIn: 'root' });
7967
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: UrlService, decorators: [{
7968
+ type: Injectable,
7969
+ args: [{
7970
+ providedIn: 'root'
7971
+ }]
7972
+ }], ctorParameters: function () { return [{ type: i1$4.Router }, { type: i1$1.Location }, { type: i1$4.UrlSerializer }]; } });
7973
+
7974
+ /**
7975
+ * TODO: this should be updated to store the last x visists rathern than a map of places to visit segments.
7976
+ * This would allow it to return segments that are relevent to a particular parent path. Currently
7977
+ * it just returns the last segment so it can return child ids that don't belong to the current parent.
7978
+ */
7979
+ class PlaceHistory {
7980
+ constructor() {
7981
+ this._archive = new Map();
7982
+ this.placeHistoryDepth = 4;
7983
+ }
7984
+ notifyNavigationStarted() {
7985
+ if (this._activeSegments) {
7986
+ this.archiveSegments(this._activeSegments.visitSegments);
7987
+ this._previousVisits = this._activeSegments;
7988
+ }
7989
+ }
7990
+ notifyNavigationFinished(visits) {
7991
+ this._activeSegments = new PlaceHistory.VisitRecord(visits.segments);
7992
+ }
7993
+ updateVisitSegment(visit) {
7994
+ assert.isTruthy(this._activeSegments);
7995
+ this._activeSegments.update(visit);
7996
+ }
7997
+ lastVisitIncluded(placeDef) {
7998
+ var _a;
7999
+ return !!((_a = this._previousVisits) === null || _a === void 0 ? void 0 : _a.getVisitFor(placeDef));
8000
+ }
8001
+ getMostRecentVisitSegmentFor(placeDef) {
8002
+ return first(this.getSegmentHistoryFor(placeDef));
8003
+ }
8004
+ getSegmentHistoryFor(placeDef) {
8005
+ let history = this._archive.get(placeDef);
8006
+ if (!history) {
8007
+ history = [];
8008
+ this.setHistory(placeDef, history);
8009
+ }
8010
+ return history;
8011
+ }
8012
+ setHistory(placeDef, history) {
8013
+ this._archive.set(placeDef, history);
8014
+ }
8015
+ archiveSegments(visits) {
8016
+ visits.forEach(state => {
8017
+ const history = this.getSegmentHistoryFor(state.placeDefinition);
8018
+ const previousState = first(history);
8019
+ if (!previousState || state.hasChangedFrom(previousState)) {
8020
+ history.unshift(state); // LIFO
8021
+ this.setHistory(state.placeDefinition, history.slice(0, this.placeHistoryDepth));
8022
+ }
8023
+ });
8024
+ }
8025
+ }
8026
+ PlaceHistory.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: PlaceHistory, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
8027
+ PlaceHistory.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: PlaceHistory, providedIn: 'root' });
8028
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: PlaceHistory, decorators: [{
8029
+ type: Injectable,
8030
+ args: [{
8031
+ providedIn: 'root'
8032
+ }]
8033
+ }], ctorParameters: function () { return []; } });
8034
+ (function (PlaceHistory) {
8035
+ class VisitRecord {
8036
+ constructor(visitSegments) {
8037
+ this.visitSegments = visitSegments;
8038
+ }
8039
+ update(visit) {
8040
+ this.visitSegments = this.visitSegments
8041
+ .filter(v => v.placeDefinition !== visit.placeDefinition) // keep all that are not me
8042
+ .concat(visit); // and add me to the end
8043
+ }
8044
+ getVisitFor(placeDef) {
8045
+ return this.visitSegments.find(v => v.placeDefinition === placeDef);
8046
+ }
8047
+ }
8048
+ PlaceHistory.VisitRecord = VisitRecord;
8049
+ // export class Query {
8050
+ // private _history: Visit.State[];
8051
+ // private _places: Place[];
8052
+ // private _predicate: (visit: any) => boolean;
8053
+ // private _limit: number;
8054
+ //
8055
+ // constructor(history, limit = history.length) {
8056
+ // this._history = history;
8057
+ // this._places = [];
8058
+ // this._predicate = (visit => true);
7419
8059
  // this._limit = limit;
7420
8060
  // }
7421
8061
  //
@@ -7485,7 +8125,7 @@ class PlaceRouter extends GarbageCollector {
7485
8125
  this.urlService = urlService;
7486
8126
  this.placeHistory = placeHistory;
7487
8127
  this.navigationSession$ = new MutableValueModel();
7488
- this._activeVisits$ = new MutableListModel();
8128
+ this._activeVisit$ = new MutableValueModel();
7489
8129
  this.sessionFinishedJobs = [];
7490
8130
  /**
7491
8131
  * An observable model containing the authoriser function. This allows places to react to changes
@@ -7501,8 +8141,8 @@ class PlaceRouter extends GarbageCollector {
7501
8141
  return this.navigateByUrl(urlSnapshot, options);
7502
8142
  }, state => {
7503
8143
  this.transitionTo(state);
7504
- }, visits => {
7505
- this.routingSessionFinished(visits);
8144
+ }, segments => {
8145
+ this.routingSessionFinished(segments);
7506
8146
  });
7507
8147
  const { chain, valueOf, before, when, after, observe, switchOn } = Dsl.disposeWith(this);
7508
8148
  this.navigationInProgress$ = chain(this.navigationSession$).isNotNil();
@@ -7511,8 +8151,7 @@ class PlaceRouter extends GarbageCollector {
7511
8151
  this.navigationSessionName$ = chain(this.navigationSession$)
7512
8152
  .pluck("name")
7513
8153
  .otherwise(idleStateName);
7514
- DebugContext.tag(this._activeVisits$, "PlaceRouter.activeVisits");
7515
- this.state$ = chain(this._activeVisits$).reduce(visits => new PlaceRouter.State(visits));
8154
+ DebugContext.tag(this._activeVisit$, "PlaceRouter.activeVisit");
7516
8155
  // TODO: make setup the callbacks in during module initiation to make this testable.
7517
8156
  angularRouter.events.subscribe(event => {
7518
8157
  // Routing event sequence
@@ -7569,10 +8208,11 @@ class PlaceRouter extends GarbageCollector {
7569
8208
  this.redirections = redirections;
7570
8209
  }
7571
8210
  getAuthenticationFailureRedirect(activatedRoute, state) {
7572
- return this.redirections.onAuthenticationFailure(activatedRoute, state);
8211
+ const redirect = this.redirections.onAuthenticationFailure(activatedRoute, state);
8212
+ return redirect instanceof Visit ? redirect : Visit.goto(redirect);
7573
8213
  }
7574
8214
  getAuthorisationFailureRedirectOptions(component) {
7575
- return this.redirections.onAuthorisationFailure(component);
8215
+ return this.redirections.onAuthorisationFailure(component).map(it => it instanceof Visit ? it : Visit.goto(it));
7576
8216
  }
7577
8217
  get navigationSession() {
7578
8218
  return this.navigationSession$.value;
@@ -7603,7 +8243,6 @@ class PlaceRouter extends GarbageCollector {
7603
8243
  });
7604
8244
  });
7605
8245
  }
7606
- // @Trace()
7607
8246
  onPopState(event) {
7608
8247
  assert.isTruthy(event.navigationTrigger === "popstate");
7609
8248
  if (this.currentSession) {
@@ -7653,18 +8292,13 @@ class PlaceRouter extends GarbageCollector {
7653
8292
  onRouterEnd(event) {
7654
8293
  this.currentSession.onRouterEnd(event);
7655
8294
  }
7656
- navigate(visit, options) {
7657
- const commands = asArray(visit).reduce((result, v) => {
7658
- const path = v.placeDefinition.path;
7659
- return isEmpty$1(path) ?
7660
- [...result, path] : // Angular doesn't support route params on empty path segments
7661
- [...result, path, ...this.createRouteParameters(v)];
7662
- }, []);
7663
- return this.doNavigation(visit, (router) => __awaiter(this, void 0, void 0, function* () {
7664
- yield this.angularRouter.navigate(commands, {
7665
- relativeTo: options ? options.relativeTo : null
7666
- });
7667
- }));
8295
+ navigate(visitOrPlaceComponent, params) {
8296
+ return __awaiter(this, void 0, void 0, function* () {
8297
+ const visit = this.toVisit(visitOrPlaceComponent, params).copyWithDefaultsFrom(this.activeVisit$.value);
8298
+ return this.doNavigation(visit, (router) => __awaiter(this, void 0, void 0, function* () {
8299
+ yield this.angularRouter.navigate(visit.getRouterCommands());
8300
+ }));
8301
+ });
7668
8302
  }
7669
8303
  // @Trace()
7670
8304
  doNavigation(visit, runNavigationCommands) {
@@ -7677,7 +8311,7 @@ class PlaceRouter extends GarbageCollector {
7677
8311
  lang.illegalState("Navigation already in progress");
7678
8312
  }
7679
8313
  const navigation = this.createNavigationSession(this.urlService.getCurrentRouterUrl());
7680
- asArray(visit).forEach(v => navigation.storeVisit(v));
8314
+ navigation.initialiseVisitSegments(visit);
7681
8315
  this.transitionTo(navigation);
7682
8316
  try {
7683
8317
  yield runNavigationCommands(this.angularRouter);
@@ -7686,7 +8320,7 @@ class PlaceRouter extends GarbageCollector {
7686
8320
  // Check if the router has finished (in the case where no router change required) and we're still in a
7687
8321
  // transient state and finish of the transition.
7688
8322
  if (!this.angularRouter.getCurrentNavigation() && this.currentSession) {
7689
- this.currentSession.onRouterEnd(new NavigationEnd(-1, "", ""));
8323
+ this.currentSession.onRouterEnd(new NavigationEnd(-1, "", this.urlService.getCurrentRouterUrl()));
7690
8324
  }
7691
8325
  }
7692
8326
  });
@@ -7695,18 +8329,20 @@ class PlaceRouter extends GarbageCollector {
7695
8329
  // console.log(`### navigationByUrl -> ${urlSnapshot.urlTree.toString()}`);
7696
8330
  return this.angularRouter.navigateByUrl(urlSnapshot.urlTree, navigationExtras);
7697
8331
  }
7698
- get activeVisits$() {
7699
- return this._activeVisits$.readonly;
8332
+ get activeVisit$() {
8333
+ return this._activeVisit$.readonly;
7700
8334
  }
7701
- // @Trace()
7702
- pushVisitChangesToRoute(previous, next) {
8335
+ notifyVisitSegmentChanged(is, was) {
7703
8336
  return __awaiter(this, void 0, void 0, function* () {
7704
- this.placeHistory.updateVisit(next);
8337
+ // console.log("PlaceRouter.notifyVisitSegmentChanged", is.toDebugString(), was.toDebugString());
8338
+ this.placeHistory.updateVisitSegment(is);
7705
8339
  // FIXME: no route id -> route id duplicates route parameters
7706
- if (next.hasRoutingChangedFrom(previous)) {
7707
- return this.doNavigation(next, router => {
7708
- const urlSnapshot = this.urlService.parseUrl(this.angularRouter.routerState.snapshot.url).updateVisitSegments(next);
7709
- // console.log('### Push Changes to route Redirect', { commands: urlSnapshot.url });
8340
+ const visit = this.activeVisit$.value.copyAndReplaceSegment(is);
8341
+ if (is.hasRoutingChangedFrom(was)) {
8342
+ // TODO: can I just do a regular navigate using an updated visit?
8343
+ const { when } = Dsl.disposeWith(this);
8344
+ yield this.doNavigation(visit, router => {
8345
+ const urlSnapshot = this.urlService.parseUrl(this.angularRouter.routerState.snapshot.url).updateVisitSegment(is);
7710
8346
  return this.navigateByUrl(urlSnapshot);
7711
8347
  });
7712
8348
  }
@@ -7733,14 +8369,14 @@ class PlaceRouter extends GarbageCollector {
7733
8369
  next.notifyActive();
7734
8370
  }
7735
8371
  // @Trace()
7736
- routingSessionFinished(visits) {
7737
- if (visits && visits.length > 0) {
8372
+ routingSessionFinished(visit) {
8373
+ if (visit) {
7738
8374
  assert.isTruthy(this.navigationInProgress$.value);
7739
- this.placeHistory.notifyNavigationFinished(visits);
8375
+ this.placeHistory.notifyNavigationFinished(visit);
7740
8376
  // We update the active visits before we finish the session so the
7741
- // place outlets can ignore the incoming changes until things are
7742
- // settled. TODO: can we removed the event'ness here and just do a push?
7743
- this._activeVisits$.value = visits;
8377
+ // place outlets can ignore the incoming changes until things are settled.
8378
+ this._activeVisit$.value = visit;
8379
+ // console.log(visit.toDebugString())
7744
8380
  }
7745
8381
  const session = this.currentSession;
7746
8382
  session.dispose();
@@ -7759,8 +8395,7 @@ class PlaceRouter extends GarbageCollector {
7759
8395
  * the app directly and we don't get to ask.
7760
8396
  */
7761
8397
  // @Trace()
7762
- syncInteractionContextIdsWithRouter(onSyncComplete = () => {
7763
- }) {
8398
+ syncInteractionContextIdsWithRouter(onSyncComplete = () => { }) {
7764
8399
  if (this.navigationSession) {
7765
8400
  // console.log(`Navigation active -> ${this.navigationSession.toString()}, sync delayed until finished.`);
7766
8401
  const session = this.navigationSession;
@@ -7787,35 +8422,29 @@ class PlaceRouter extends GarbageCollector {
7787
8422
  }));
7788
8423
  }
7789
8424
  }
7790
- createRouteParameters(visit) {
7791
- const def = visit.placeDefinition;
7792
- return visit.hasRouteId() ?
7793
- [def.getFormattedRouteId(visit), def.getFormattedRouteParameters(visit)] :
7794
- [def.getFormattedRouteParameters(visit)];
8425
+ toVisit(visitOrPlaceComponent, params) {
8426
+ if (visitOrPlaceComponent instanceof Visit) {
8427
+ return visitOrPlaceComponent;
8428
+ }
8429
+ else {
8430
+ return Visit.goto(visitOrPlaceComponent, params);
8431
+ }
7795
8432
  }
7796
8433
  }
7797
8434
  PlaceRouter.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: PlaceRouter, deps: [{ token: i1$4.Router }, { token: i1$1.Location }, { token: InteractionService }, { token: UrlService }, { token: PlaceHistory }], target: i0.ɵɵFactoryTarget.Injectable });
7798
8435
  PlaceRouter.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: PlaceRouter, providedIn: "root" });
8436
+ __decorate([
8437
+ Trace(),
8438
+ __metadata("design:type", Function),
8439
+ __metadata("design:paramtypes", [NavigationStart]),
8440
+ __metadata("design:returntype", void 0)
8441
+ ], PlaceRouter.prototype, "onPopState", null);
7799
8442
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: PlaceRouter, decorators: [{
7800
8443
  type: Injectable,
7801
8444
  args: [{
7802
8445
  providedIn: "root"
7803
8446
  }]
7804
- }], ctorParameters: function () { return [{ type: i1$4.Router }, { type: i1$1.Location }, { type: InteractionService }, { type: UrlService }, { type: PlaceHistory }]; } });
7805
- (function (PlaceRouter) {
7806
- class State {
7807
- constructor(activeVisits) {
7808
- this.activeVisits = activeVisits;
7809
- }
7810
- isPlaceActive(placeDefinition) {
7811
- return !!this.getVisitFor(placeDefinition);
7812
- }
7813
- getVisitFor(placeDefinition) {
7814
- return this.activeVisits.find(v => v.placeDefinition === placeDefinition);
7815
- }
7816
- }
7817
- PlaceRouter.State = State;
7818
- })(PlaceRouter || (PlaceRouter = {}));
8447
+ }], ctorParameters: function () { return [{ type: i1$4.Router }, { type: i1$1.Location }, { type: InteractionService }, { type: UrlService }, { type: PlaceHistory }]; }, propDecorators: { onPopState: [] } });
7819
8448
 
7820
8449
  class ActivityContainerComponent extends AbstractInteractionContext {
7821
8450
  constructor(placeRouter) {
@@ -8890,693 +9519,239 @@ class InlineStringEditorComponent extends DisposableComponent {
8890
9519
  cancelFace: self.cancelFace.value,
8891
9520
  placeholder: self.placeHolderModel.value,
8892
9521
  label: self.label,
8893
- layout: InputActivity.Layout.INLINE,
8894
- validators: self.editorModel.validators.value,
8895
- save(value, inputContext) {
8896
- return __awaiter(this, void 0, void 0, function* () {
8897
- yield self.editorModel.saveCallback(value, inputContext);
8898
- });
8899
- }
8900
- };
8901
- }
8902
- cancelEdit() {
8903
- if (this.isEditing()) {
8904
- this.interactionContext.cancelActiveActivity();
8905
- }
8906
- }
8907
- startEdit() {
8908
- if (!this.isEditing() && this.editCommand.enabled$.value) {
8909
- this.editCommand.execute();
8910
- }
8911
- }
8912
- isEditing() {
8913
- return this.interactionContext.isActive();
8914
- }
8915
- isEmpty() {
8916
- return this.empty.value;
8917
- }
8918
- }
8919
- InlineStringEditorComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: InlineStringEditorComponent, deps: [{ token: InteractionService }], target: i0.ɵɵFactoryTarget.Component });
8920
- InlineStringEditorComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "14.1.2", type: InlineStringEditorComponent, selector: "aup-inline-string-editor", inputs: { editorModel: "editorModel", facesModel: "facesModel", faces: "faces", label: "label", placeHolder: "placeHolder", placeHolderModel: "placeHolderModel" }, viewQueries: [{ propertyName: "interactionContext", first: true, predicate: InPlaceInteractionContextComponent, descendants: true }], usesInheritance: true, ngImport: i0, template: "<div class=\"container\" *ngIf=\"!editorModel.isEditing()\">\n <mat-form-field appearance=\"standard\" floatLabel=\"always\" (click)=\"startEdit()\"\n [class.editable]=\"editingEnabled.value\" [class.empty]=\"isEmpty()\">\n <mat-label *ngIf=\"label\">{{label}}</mat-label>\n <input matInput\n placeholder=\"{{placeHolder}}\"\n [ngModel]=\"editorModel.valueModel.value\"\n [disabled]=\"true\"\n >\n <!-- <mat-hint *ngIf=\"showHint\">{{hint}}</mat-hint>-->\n <!-- <mat-error *ngIf=\"hasErrors\">{{firstError}}</mat-error>-->\n <!-- <aup-icon *ngIf=\"iconPrefix\" matPrefix [icon]=\"iconPrefix\"></aup-icon>-->\n </mat-form-field>\n <aup-command *ngIf=\"editCommand.enabled$.value\" [command]=\"editCommand\" [faceModel]=\"editFaceModel\"></aup-command>\n</div>\n<aup-in-place-interaction-context [animateFirstActivity]=\"false\"></aup-in-place-interaction-context>\n", dependencies: [{ kind: "directive", type: i1$1.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "component", type: CommandComponent, selector: "aup-command", inputs: ["command", "faceModel", "face", "busyFaceModel", "busyFace", "alignFace"] }, { kind: "directive", type: i2$4.DefaultValueAccessor, selector: "input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]" }, { kind: "directive", type: i2$4.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i2$4.NgModel, selector: "[ngModel]:not([formControlName]):not([formControl])", inputs: ["name", "disabled", "ngModel", "ngModelOptions"], outputs: ["ngModelChange"], exportAs: ["ngModel"] }, { kind: "component", type: i3$1.MatFormField, selector: "mat-form-field", inputs: ["color", "appearance", "hideRequiredMarker", "hintLabel", "floatLabel"], exportAs: ["matFormField"] }, { kind: "directive", type: i3$1.MatLabel, selector: "mat-label" }, { kind: "directive", type: i4$1.MatInput, selector: "input[matInput], textarea[matInput], select[matNativeControl], input[matNativeControl], textarea[matNativeControl]", inputs: ["disabled", "id", "placeholder", "name", "required", "type", "errorStateMatcher", "aria-describedby", "value", "readonly"], exportAs: ["matInput"] }, { kind: "component", type: InPlaceInteractionContextComponent, selector: "aup-in-place-interaction-context", inputs: ["animateFirstActivity", "syncWithRoutes"] }] });
8921
- __decorate([
8922
- TrackExternal(),
8923
- __metadata("design:type", InlineEditorModel)
8924
- ], InlineStringEditorComponent.prototype, "editorModel", void 0);
8925
- __decorate([
8926
- TrackExternal(),
8927
- __metadata("design:type", ValueModel)
8928
- ], InlineStringEditorComponent.prototype, "facesModel", void 0);
8929
- __decorate([
8930
- StoreInValueModel('facesModel'),
8931
- __metadata("design:type", Object)
8932
- ], InlineStringEditorComponent.prototype, "faces", void 0);
8933
- __decorate([
8934
- StoreInValueModel('placeHolderModel'),
8935
- __metadata("design:type", String)
8936
- ], InlineStringEditorComponent.prototype, "placeHolder", void 0);
8937
- __decorate([
8938
- TrackExternal(),
8939
- __metadata("design:type", ValueModel)
8940
- ], InlineStringEditorComponent.prototype, "placeHolderModel", void 0);
8941
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: InlineStringEditorComponent, decorators: [{
8942
- type: Component,
8943
- args: [{ selector: 'aup-inline-string-editor', template: "<div class=\"container\" *ngIf=\"!editorModel.isEditing()\">\n <mat-form-field appearance=\"standard\" floatLabel=\"always\" (click)=\"startEdit()\"\n [class.editable]=\"editingEnabled.value\" [class.empty]=\"isEmpty()\">\n <mat-label *ngIf=\"label\">{{label}}</mat-label>\n <input matInput\n placeholder=\"{{placeHolder}}\"\n [ngModel]=\"editorModel.valueModel.value\"\n [disabled]=\"true\"\n >\n <!-- <mat-hint *ngIf=\"showHint\">{{hint}}</mat-hint>-->\n <!-- <mat-error *ngIf=\"hasErrors\">{{firstError}}</mat-error>-->\n <!-- <aup-icon *ngIf=\"iconPrefix\" matPrefix [icon]=\"iconPrefix\"></aup-icon>-->\n </mat-form-field>\n <aup-command *ngIf=\"editCommand.enabled$.value\" [command]=\"editCommand\" [faceModel]=\"editFaceModel\"></aup-command>\n</div>\n<aup-in-place-interaction-context [animateFirstActivity]=\"false\"></aup-in-place-interaction-context>\n" }]
8944
- }], ctorParameters: function () { return [{ type: InteractionService }]; }, propDecorators: { editorModel: [{
8945
- type: Input
8946
- }], facesModel: [{
8947
- type: Input
8948
- }], faces: [{
8949
- type: Input
8950
- }], interactionContext: [{
8951
- type: ViewChild,
8952
- args: [InPlaceInteractionContextComponent]
8953
- }], label: [{
8954
- type: Input
8955
- }], placeHolder: [{
8956
- type: Input
8957
- }], placeHolderModel: [{
8958
- type: Input
8959
- }] } });
8960
- (function (InlineStringEditorComponent) {
8961
- InlineStringEditorComponent.DEFAULT_FACES = {
8962
- edit: {
8963
- icon: () => 'mat:edit'
8964
- },
8965
- save: {
8966
- icon: () => 'mat:check'
8967
- },
8968
- cancel: {
8969
- icon: () => 'mat:clear'
8970
- }
8971
- };
8972
- })(InlineStringEditorComponent || (InlineStringEditorComponent = {}));
8973
-
8974
- class InteractionModule {
8975
- }
8976
- InteractionModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: InteractionModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
8977
- InteractionModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "14.1.2", ngImport: i0, type: InteractionModule, declarations: [ActivityContainerComponent,
8978
- ConfirmationDialogComponent,
8979
- ConfirmThenDialogComponent,
8980
- ConfirmThenExecuteDialogComponent,
8981
- AlertDialogComponent,
8982
- ActivityOutletComponent,
8983
- InPlaceInteractionContextComponent,
8984
- AddItemInteractionContextComponent,
8985
- ActivityActionsComponent,
8986
- PopupInteractionContextComponent,
8987
- StringInputActivity,
8988
- SelectInputActivity,
8989
- InputActivity,
8990
- InteractionContextTriggerFor,
8991
- Activity,
8992
- ActivityTitleComponent,
8993
- ActivityBodyComponent,
8994
- ActivityActionsComponent,
8995
- AbstractActivityTriggerComponent,
8996
- PopupActivityTriggerComponent,
8997
- InlineActivityTriggerComponent,
8998
- ModalActivityTriggerComponent,
8999
- AddCardActivityComponent,
9000
- InlineStringEditorComponent,
9001
- AbstractDialogComponent,
9002
- AbstractConfirmDialogComponent], imports: [CommonModule,
9003
- MatButtonModule,
9004
- MatDialogModule,
9005
- MatTabsModule,
9006
- PortalModule,
9007
- RouterModule,
9008
- MatIconModule,
9009
- DirectivesModule,
9010
- FlexModule,
9011
- GridModule,
9012
- ComponentsModule,
9013
- FormsModule,
9014
- MatInputModule,
9015
- MatFormFieldModule,
9016
- A11yModule], exports: [ActivityContainerComponent,
9017
- ActivityOutletComponent,
9018
- ActivityTitleComponent,
9019
- InPlaceInteractionContextComponent,
9020
- AddItemInteractionContextComponent,
9021
- ActivityActionsComponent,
9022
- PopupInteractionContextComponent,
9023
- InteractionContextTriggerFor,
9024
- StringInputActivity,
9025
- SelectInputActivity,
9026
- ActivityBodyComponent,
9027
- PopupActivityTriggerComponent,
9028
- InlineActivityTriggerComponent,
9029
- ModalActivityTriggerComponent,
9030
- AddCardActivityComponent,
9031
- InlineStringEditorComponent] });
9032
- InteractionModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: InteractionModule, providers: [
9033
- InteractionService
9034
- // {
9035
- // provide: MAT_TABS_CONFIG, useValue: { animationDuration: "2s" }
9036
- // }
9037
- ], imports: [CommonModule,
9038
- MatButtonModule,
9039
- MatDialogModule,
9040
- MatTabsModule,
9041
- PortalModule,
9042
- RouterModule,
9043
- MatIconModule,
9044
- DirectivesModule,
9045
- FlexModule,
9046
- GridModule,
9047
- ComponentsModule,
9048
- FormsModule,
9049
- MatInputModule,
9050
- MatFormFieldModule,
9051
- A11yModule] });
9052
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: InteractionModule, decorators: [{
9053
- type: NgModule,
9054
- args: [{
9055
- imports: [
9056
- CommonModule,
9057
- MatButtonModule,
9058
- MatDialogModule,
9059
- MatTabsModule,
9060
- PortalModule,
9061
- RouterModule,
9062
- MatIconModule,
9063
- DirectivesModule,
9064
- FlexModule,
9065
- GridModule,
9066
- ComponentsModule,
9067
- FormsModule,
9068
- MatInputModule,
9069
- MatFormFieldModule,
9070
- A11yModule
9071
- ],
9072
- declarations: [
9073
- ActivityContainerComponent,
9074
- ConfirmationDialogComponent,
9075
- ConfirmThenDialogComponent,
9076
- ConfirmThenExecuteDialogComponent,
9077
- AlertDialogComponent,
9078
- ActivityOutletComponent,
9079
- InPlaceInteractionContextComponent,
9080
- AddItemInteractionContextComponent,
9081
- ActivityActionsComponent,
9082
- PopupInteractionContextComponent,
9083
- StringInputActivity,
9084
- SelectInputActivity,
9085
- InputActivity,
9086
- InteractionContextTriggerFor,
9087
- Activity,
9088
- ActivityTitleComponent,
9089
- ActivityBodyComponent,
9090
- ActivityActionsComponent,
9091
- AbstractActivityTriggerComponent,
9092
- PopupActivityTriggerComponent,
9093
- InlineActivityTriggerComponent,
9094
- ModalActivityTriggerComponent,
9095
- AddCardActivityComponent,
9096
- InlineStringEditorComponent,
9097
- AbstractDialogComponent,
9098
- AbstractConfirmDialogComponent,
9099
- ],
9100
- exports: [
9101
- ActivityContainerComponent,
9102
- ActivityOutletComponent,
9103
- ActivityTitleComponent,
9104
- InPlaceInteractionContextComponent,
9105
- AddItemInteractionContextComponent,
9106
- ActivityActionsComponent,
9107
- PopupInteractionContextComponent,
9108
- InteractionContextTriggerFor,
9109
- StringInputActivity,
9110
- SelectInputActivity,
9111
- ActivityBodyComponent,
9112
- PopupActivityTriggerComponent,
9113
- InlineActivityTriggerComponent,
9114
- ModalActivityTriggerComponent,
9115
- AddCardActivityComponent,
9116
- InlineStringEditorComponent,
9117
- ],
9118
- providers: [
9119
- InteractionService
9120
- // {
9121
- // provide: MAT_TABS_CONFIG, useValue: { animationDuration: "2s" }
9122
- // }
9123
- ]
9124
- }]
9125
- }] });
9126
-
9127
- const PARAMETER_DEFINITION_KEY = Symbol('parameterDefinition');
9128
- class ParameterDefinition {
9129
- constructor(propertyName, options, urlFormat) {
9130
- this.propertyName = propertyName;
9131
- this.urlFormat = urlFormat;
9132
- this.options = Opts.get(options);
9133
- this.remember = this.options.getOptional('remember', false);
9134
- this.defaultValue = this.options.getOptional('defaultValue', null);
9135
- }
9136
- get name() {
9137
- return this.options.getOptional('as', this.propertyName);
9138
- }
9139
- // @Trace()
9140
- get isRouteParameter() {
9141
- return !!this.urlFormat;
9142
- }
9143
- createBackingModel() {
9144
- const model = this.backingModelFactory();
9145
- model[PARAMETER_DEFINITION_KEY] = this;
9146
- return model;
9147
- }
9148
- getOptionValue(key) {
9149
- return this.options.getOptional(key, null);
9150
- }
9151
- // @Trace()
9152
- sanitise(value, visit, placeHistory, injector, isPopState) {
9153
- return __awaiter(this, void 0, void 0, function* () {
9154
- // console.log(`sanitise(${this.propertyName})`)
9155
- value = yield this.sanitiseMissing(visit, placeHistory, value);
9156
- value = yield this.runCustomSanitiser(value, visit, placeHistory, injector, isPopState);
9157
- return value;
9158
- });
9159
- }
9160
- runCustomSanitiser(value, visit, placeHistory, injector, isPopState) {
9161
- return __awaiter(this, void 0, void 0, function* () {
9162
- const customSanitiser = this.prepareCustomSanitiser(injector);
9163
- return customSanitiser ? customSanitiser.sanitise(value, visit, injector) : value;
9164
- });
9165
- }
9166
- sanitiseMissing(visit, placeHistory, value) {
9167
- if (this.isMissingFrom(visit)) {
9168
- const returningFromSomewhereElse = !placeHistory.lastVisitIncluded(visit.placeDefinition);
9169
- if (returningFromSomewhereElse) {
9170
- const lastKnownVisit = placeHistory.getMostRecentVisitFor(visit.placeDefinition);
9171
- if (this.remember && lastKnownVisit) {
9172
- value = lastKnownVisit.getParameterValue(this);
9173
- }
9174
- }
9175
- }
9176
- return this.isEmptyValue(value) ? this.defaultValue : value;
9177
- }
9178
- prepareCustomSanitiser(injector) {
9179
- const customSanitiser = this.options.getOptional('sanitiser', null);
9180
- if (isFunction(customSanitiser)) {
9181
- return injector.get(customSanitiser);
9182
- }
9183
- if (isObject(customSanitiser)) {
9184
- return isFunction(customSanitiser['sanitise']) ?
9185
- customSanitiser :
9186
- lang$1.illegalState(`expected @VisitParameter({sanitiser: ...}) for ${this.propertyName} to be a constructor or instance of ParameterSanitiser, got: ` + customSanitiser);
9187
- }
9188
- return undefined;
9189
- }
9190
- isMissingFrom(visit) {
9191
- return !visit.hasParameter(this);
9192
- }
9193
- }
9194
- (function (ParameterDefinition) {
9195
- class RouteId extends ParameterDefinition {
9196
- constructor() {
9197
- super(...arguments);
9198
- this.isRouteId = true;
9199
- this.isArray = false;
9200
- this.backingModelFactory = () => new MutableValueModel();
9201
- }
9202
- isEmptyValue(value) {
9203
- return isNil(value);
9204
- }
9205
- hasChanged(a, b) {
9206
- return a !== b;
9207
- }
9208
- }
9209
- ParameterDefinition.RouteId = RouteId;
9210
- class ValueParameter extends ParameterDefinition {
9211
- constructor() {
9212
- super(...arguments);
9213
- this.isRouteId = false;
9214
- this.isArray = false;
9215
- this.backingModelFactory = () => new MutableValueModel();
9216
- }
9217
- isEmptyValue(value) {
9218
- return isNil(value);
9219
- }
9220
- hasChanged(a, b) {
9221
- return a !== b;
9222
- }
9223
- }
9224
- ParameterDefinition.ValueParameter = ValueParameter;
9225
- class ArrayParameter extends ParameterDefinition {
9226
- constructor(parameterName, options, urlFormat) {
9227
- super(parameterName, options, urlFormat);
9228
- this.isRouteId = false;
9229
- this.isArray = true;
9230
- this.backingModelFactory = () => new MutableListModel();
9231
- }
9232
- isEmptyValue(value) {
9233
- return isNil(value) || value.length < 1;
9234
- }
9235
- hasChanged(a, b) {
9236
- return !isEqual(a, b);
9237
- }
9238
- }
9239
- ParameterDefinition.ArrayParameter = ArrayParameter;
9240
- function get(model) {
9241
- const parameterDefinition = model[PARAMETER_DEFINITION_KEY];
9242
- if (!parameterDefinition) {
9243
- lang$1.illegalArgument('model hasn\'t been annotated with @VisitParameter, @VisitParameterList or @RouteId');
9244
- }
9245
- return parameterDefinition;
9246
- }
9247
- ParameterDefinition.get = get;
9248
- })(ParameterDefinition || (ParameterDefinition = {}));
9249
-
9250
- class PlaceDefinition {
9251
- constructor(component, path, authenticate, role, data, routeParameters, children, redirectToFirstChild) {
9252
- this.component = component;
9253
- this.path = path;
9254
- this.authenticate = authenticate;
9255
- this.role = role;
9256
- this.data = data;
9257
- this.routeParameters = routeParameters;
9258
- this.children = children;
9259
- this.redirectToFirstChild = redirectToFirstChild;
9260
- }
9261
- hasRouteId() {
9262
- return !!this.getRouteIdParameterDef();
9263
- }
9264
- getRouteIdParameterDef() {
9265
- return this.routeParameters.find(p => p.isRouteId);
9266
- }
9267
- getRouteParameterDefs(includeRouteId = false) {
9268
- return this.getVisitParameterDefs({ includeRouteId, includeRouteParameters: true });
9269
- }
9270
- getVisitParameterDefs(include) {
9271
- const opts = Opts.get(include);
9272
- // includes
9273
- const includeRouteId = !include || opts.getOptional('includeRouteId', false);
9274
- const includeRouteParameters = !include || opts.getOptional('includeRouteParameters', false);
9275
- const includeNonRouteParameters = !include || opts.getOptional('includeNonRouteParameters', false);
9276
- return this.routeParameters.filter(p => {
9277
- return (includeRouteId && p.isRouteId)
9278
- || (includeRouteParameters && p.isRouteParameter && !p.isRouteId) // route id is included in the line above
9279
- || (includeNonRouteParameters && !p.isRouteParameter);
9280
- });
9281
- }
9282
- getPlaceData(key, defaultValue) {
9283
- return this.data ?
9284
- isNil(this.data[key]) ? defaultValue : this.data[key] :
9285
- defaultValue;
9286
- }
9287
- searchPlaceData(keys, defaultValue) {
9288
- if (this.data) {
9289
- const found = keys.find(key => !isNil(this.data[key]));
9290
- return found ? this.data[found] : defaultValue;
9291
- }
9292
- else {
9293
- return defaultValue;
9294
- }
9295
- }
9296
- getRouteIdFrom(visit) {
9297
- const routeIdParameterDef = this.getRouteIdParameterDef();
9298
- return routeIdParameterDef ? visit.getParameterValue(routeIdParameterDef) : null;
9299
- }
9300
- getFormattedRouteId(visit) {
9301
- // Note: RouteIds are always present in the url and are just empty strings when not defined. This is
9302
- // mandated by the fact that redirects from <path> to <path>/:id always include the id parameter as
9303
- // an empty string.
9304
- return visit.hasRouteId() ? this.getRouteIdParameterDef().urlFormat.format(visit.getRouteId()) : "";
9305
- }
9306
- // @Trace()
9307
- getFormattedRouteParameters(visit, includeRouteId = false) {
9308
- const result = {};
9309
- this.getVisitParameterDefs({
9310
- includeRouteId, includeRouteParameters: true
9311
- }).forEach(def => {
9312
- const value = visit.getParameterValue(def);
9313
- if (!def.isEmptyValue(value)) {
9314
- if (def.isArray) {
9315
- assert.isArray(value);
9316
- result[def.name] = value.map(v => def.urlFormat.format(v));
9317
- }
9318
- else {
9319
- assert.isFalsey(Array.isArray(value));
9320
- result[def.name] = def.urlFormat.format(value);
9321
- }
9322
- }
9323
- });
9324
- return result;
9325
- }
9326
- getNonRouteParameters(visit) {
9327
- const result = {};
9328
- this.getVisitParameterDefs({ includeNonRouteParameters: true }).forEach(def => {
9329
- const value = visit.getParameterValue(def);
9330
- if (!def.isEmptyValue(value)) {
9331
- result[def.name] = value;
9332
- }
9333
- });
9334
- return result;
9335
- }
9336
- // @Trace()
9337
- parseRouteParams(params) {
9338
- const result = {};
9339
- this.getVisitParameterDefs({
9340
- includeRouteId: true,
9341
- includeRouteParameters: true,
9342
- includeNonRouteParameters: false
9343
- }).forEach(def => {
9344
- // params will return null for non existent names
9345
- if (params.has(def.name)) {
9346
- if (def.isArray) {
9347
- // const values = params.getAll(def.name); // TODO: EEEK getAll is returning ["1,2,3,4"] when we gave it ["1","2","3","4"].
9348
- const values = params.get(def.name).split(',').map(s => s.trim());
9349
- result[def.name] = values.map(v => def.urlFormat.parse(v));
9350
- }
9351
- else {
9352
- const value = params.get(def.name);
9353
- if (def.isRouteId) { // TODO: Move this to parameter def so it's a strategy pattern
9354
- // because our id routes redirect if the id isn't present we always have a id
9355
- // parameter in our params. This will bugger our remember and defaultvalue sanitisation
9356
- // as it'll see that the id is present (event thought its a blank string).
9357
- if (!isEmpty(value)) {
9358
- result[def.name] = def.urlFormat.parse(value);
9359
- }
9360
- }
9361
- else {
9362
- result[def.name] = def.urlFormat.parse(value);
9363
- }
9364
- }
9365
- }
9366
- });
9367
- return result;
9368
- }
9369
- }
9370
- __decorate([
9371
- Memoize(),
9372
- __metadata("design:type", Function),
9373
- __metadata("design:paramtypes", []),
9374
- __metadata("design:returntype", ParameterDefinition)
9375
- ], PlaceDefinition.prototype, "getRouteIdParameterDef", null);
9376
- __decorate([
9377
- Memoize(),
9378
- __metadata("design:type", Function),
9379
- __metadata("design:paramtypes", [Object]),
9380
- __metadata("design:returntype", Array)
9381
- ], PlaceDefinition.prototype, "getRouteParameterDefs", null);
9382
- __decorate([
9383
- Memoize(),
9384
- __metadata("design:type", Function),
9385
- __metadata("design:paramtypes", [Object]),
9386
- __metadata("design:returntype", Array)
9387
- ], PlaceDefinition.prototype, "getVisitParameterDefs", null);
9388
-
9389
- // RAKE: making this Symbol(...) broke things.
9390
- const DEFINITION_META_DATA_KEY = 'PLACE_DEFINITION_OPTIONS';
9391
- // this one seems ok.
9392
- const ROUTE_PARAMETER_LIST_KEY = Symbol('place:route:parameters');
9393
- class ParameterChangeInterceptor {
9394
- constructor(parameterDef, model, callback, options) {
9395
- }
9396
- canProceed(nextState, interactionContext) {
9397
- return __awaiter(this, void 0, void 0, function* () {
9398
- return true;
9399
- });
9400
- }
9401
- }
9402
- class PlaceComponent extends DisposableComponent {
9403
- constructor() {
9404
- super();
9405
- this._placeReadyCallbacks = [];
9406
- this.visitModel = new MutableValueModel();
9407
- this._inVisitUpdate = new Guard();
9408
- this._active = new MutableValueModel(false);
9409
- this._parameterChangeInterceptors = [];
9410
- const { chain, valueOf, before, when, after, observe, switchOn } = Dsl.disposeWith(this);
9411
- when(this._active).becomesTruthy(() => this._notifyPlaceReady());
9412
- this.childPlaces = this.placeDefinition.children.map(d => d.component);
9413
- }
9414
- initialiseVisit(visit, notifyVisitChanged) {
9415
- assert.isNil(this.visitModel.value);
9416
- const { when } = Dsl.disposeWith(this);
9417
- this.visitModel.value = visit;
9418
- DebugContext.getOrCreate(this.visitModel).tag(`${this.placeDefinition.component.name}.visitModel`);
9419
- // we track if the any of the bindings updated the route. If so we remember it and update the
9420
- // route in one go at the end.
9421
- this.placeDefinition
9422
- .getVisitParameterDefs()
9423
- .forEach(parameterDef => this.installAndInitialiseBinding(visit, parameterDef));
9424
- when(this.visitModel).changes((current, previous) => {
9425
- notifyVisitChanged(current, previous);
9426
- }, { unless: this._inVisitUpdate });
9427
- // TODO: this needs to do a replace url option so that the new url isn't put in the history.... for
9428
- // now we're not doing it as it's a fair bit of effort and will only affect people if they're
9429
- // cutting and pasting urls to each other.
9430
- // // the binding process can update the visit (e.g. if a selection model has already selected during
9431
- // // component construction) and there was no value specified in the route
9432
- // if (visit.hasRoutingChangedFrom(this.visitModel.value)) {
9433
- // notifyVisitChanged(this.visitModel.value, visit)
9434
- // }
9435
- }
9436
- updateVisit(visit) {
9437
- assert.isTruthy(this.isInitialised());
9438
- assert.notNil(visit);
9439
- this._inVisitUpdate.whileTrue(() => {
9440
- this.visitModel.value = visit;
9441
- });
9442
- }
9443
- isInitialised() {
9444
- return !!this.visitModel.value;
9445
- }
9446
- // @Trace()
9447
- /**
9448
- * Initialised the component bindings. If any binding has an initial model value (e.g. a selection model
9449
- * initialised during the constructor) and the route has nothing, then the visit will be udpated and this
9450
- * method will return ture to nofiy the the visit has changed.
9451
- */
9452
- installAndInitialiseBinding(initialVisit, parameterDef) {
9453
- const model = this[parameterDef.propertyName];
9454
- DebugContext.tag(model, `${this.placeDefinition.component.name}.${parameterDef.propertyName}`);
9455
- const binding = this.registerDisposable(new Binding(this.visitModel, model, {
9456
- toRight(visit) {
9457
- const value = visit.getParameterValue(parameterDef);
9458
- // console.log('push to component', { name: parameterDef.name, value, visit });
9459
- return value;
9460
- },
9461
- toLeft(value, currentVisit) {
9462
- // console.log('push to route', { name: parameterDef.name, value, currentVisit });
9463
- return currentVisit.replace(parameterDef, value);
9464
- }
9465
- }));
9466
- // Now we need to initialise the binding direction. If we have a value in the Url then we should always push
9467
- // that to the view. If we don't and the view already has a value (e.g. a selection model has already initialised in the
9468
- // component constructor) then we should push that to the route.
9469
- const isInVisit = !isNil(initialVisit.getParameterValue(parameterDef));
9470
- const isInModel = !isNil(model.value);
9471
- if (!isInVisit && isInModel) {
9472
- binding.writeLeft(); // push it to the route
9473
- }
9474
- else {
9475
- binding.writeRight(); // push it to the model
9476
- }
9477
- }
9478
- get placeDefinition() {
9479
- const definition = PlaceComponent.getDefinition(this.constructor);
9480
- if (!definition) {
9481
- lang.illegalState(`${this.constructor.name} extends PlaceComponent but doesn't have @Place({..}) decorator.`);
9482
- }
9483
- return definition;
9484
- }
9485
- get active() {
9486
- return this._active.readonly;
9487
- }
9488
- /**
9489
- * Called by the router to see if this component can deactivate. This isn't called for route parameter changes.
9490
- * @param interactionContext
9491
- */
9492
- _canLeavePlace(interactionContext) {
9493
- return __awaiter(this, void 0, void 0, function* () {
9494
- return this.canDeactivate ? this.canDeactivate(interactionContext) : true;
9495
- });
9496
- }
9497
- /**
9498
- * Called by the router to see if this component can deactivate. This isn't called for route parameter changes.
9499
- * @param interactionContext
9500
- * @param nextState
9501
- */
9502
- _canChangeRouteParameters(interactionContext, nextState) {
9503
- return __awaiter(this, void 0, void 0, function* () {
9504
- if (this._parameterChangeInterceptors.length > 0) {
9505
- const visit = nextState.createVisitFor(this.placeDefinition);
9506
- for (let i = 0; i < this._parameterChangeInterceptors.length; i++) {
9507
- const interceptor = this._parameterChangeInterceptors[i];
9508
- const keepGoing = yield interceptor.canProceed(visit, interactionContext);
9509
- if (!keepGoing) {
9510
- return false;
9511
- }
9512
- }
9513
- }
9514
- return true;
9515
- });
9516
- }
9517
- /**
9518
- * Called by the router when the place is ready to interact after any animations have run.
9519
- */
9520
- _notifyActive(active) {
9521
- this._active.value = active;
9522
- }
9523
- /**
9524
- * Called by the router when the place is ready to interact after any animations have run.
9525
- */
9526
- _notifyPlaceReady() {
9527
- if (this.onPlaceReady.length === 1) {
9528
- this._placeReadyCallbacks.forEach(callback => callback());
9529
- }
9530
- else {
9531
- console.warn('Overriding PlaceComponent.onPlaceReady has been deprecated. Use PlaceComponent.onPlaceReady(() => {... do stuff...}) instead.');
9532
- this.onPlaceReady(undefined);
9533
- }
9534
- }
9535
- onPlaceReady(callback) {
9536
- this._placeReadyCallbacks.push(callback);
9537
- }
9538
- interceptVisitParameterChange(model, callback, options) {
9539
- const parameterDef = ParameterDefinition.get(model);
9540
- this._parameterChangeInterceptors.push(new ParameterChangeInterceptor(parameterDef, model, callback, options));
9541
- }
9542
- }
9543
- PlaceComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: PlaceComponent, deps: [], target: i0.ɵɵFactoryTarget.Directive });
9544
- PlaceComponent.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "14.1.2", type: PlaceComponent, usesInheritance: true, ngImport: i0 });
9545
- __decorate([
9546
- Memoize(),
9547
- __metadata("design:type", PlaceDefinition),
9548
- __metadata("design:paramtypes", [])
9549
- ], PlaceComponent.prototype, "placeDefinition", null);
9550
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: PlaceComponent, decorators: [{
9551
- type: Directive
9552
- }], ctorParameters: function () { return []; }, propDecorators: { placeDefinition: [] } });
9553
- (function (PlaceComponent) {
9554
- function isPlaceComponentConstructor(target) {
9555
- return lang.constructorChain(target).includes(PlaceComponent);
9556
- }
9557
- PlaceComponent.isPlaceComponentConstructor = isPlaceComponentConstructor;
9558
- function getRouteParameters(klass) {
9559
- return Klass.get(klass).getMetadataList(ROUTE_PARAMETER_LIST_KEY);
9560
- }
9561
- PlaceComponent.getRouteParameters = getRouteParameters;
9562
- function getDefinition(snapshotOrConstructor) {
9563
- if (snapshotOrConstructor instanceof ActivatedRouteSnapshot) {
9564
- const component = snapshotOrConstructor.component;
9565
- if (!isPlaceComponentConstructor(component)) {
9566
- throw new Error(`ActivatedRouteSnapshot component is not a PlaceComponent, got ${component}`);
9522
+ layout: InputActivity.Layout.INLINE,
9523
+ validators: self.editorModel.validators.value,
9524
+ save(value, inputContext) {
9525
+ return __awaiter(this, void 0, void 0, function* () {
9526
+ yield self.editorModel.saveCallback(value, inputContext);
9527
+ });
9567
9528
  }
9568
- return Reflect.getMetadata(DEFINITION_META_DATA_KEY, component);
9529
+ };
9530
+ }
9531
+ cancelEdit() {
9532
+ if (this.isEditing()) {
9533
+ this.interactionContext.cancelActiveActivity();
9569
9534
  }
9570
- else {
9571
- return Reflect.getMetadata(DEFINITION_META_DATA_KEY, snapshotOrConstructor);
9535
+ }
9536
+ startEdit() {
9537
+ if (!this.isEditing() && this.editCommand.enabled$.value) {
9538
+ this.editCommand.execute();
9572
9539
  }
9573
9540
  }
9574
- PlaceComponent.getDefinition = getDefinition;
9575
- function injectDefinition(klass, definition) {
9576
- Reflect.defineMetadata(DEFINITION_META_DATA_KEY, definition, klass);
9541
+ isEditing() {
9542
+ return this.interactionContext.isActive();
9577
9543
  }
9578
- PlaceComponent.injectDefinition = injectDefinition;
9579
- })(PlaceComponent || (PlaceComponent = {}));
9544
+ isEmpty() {
9545
+ return this.empty.value;
9546
+ }
9547
+ }
9548
+ InlineStringEditorComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: InlineStringEditorComponent, deps: [{ token: InteractionService }], target: i0.ɵɵFactoryTarget.Component });
9549
+ InlineStringEditorComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "14.1.2", type: InlineStringEditorComponent, selector: "aup-inline-string-editor", inputs: { editorModel: "editorModel", facesModel: "facesModel", faces: "faces", label: "label", placeHolder: "placeHolder", placeHolderModel: "placeHolderModel" }, viewQueries: [{ propertyName: "interactionContext", first: true, predicate: InPlaceInteractionContextComponent, descendants: true }], usesInheritance: true, ngImport: i0, template: "<div class=\"container\" *ngIf=\"!editorModel.isEditing()\">\n <mat-form-field appearance=\"standard\" floatLabel=\"always\" (click)=\"startEdit()\"\n [class.editable]=\"editingEnabled.value\" [class.empty]=\"isEmpty()\">\n <mat-label *ngIf=\"label\">{{label}}</mat-label>\n <input matInput\n placeholder=\"{{placeHolder}}\"\n [ngModel]=\"editorModel.valueModel.value\"\n [disabled]=\"true\"\n >\n <!-- <mat-hint *ngIf=\"showHint\">{{hint}}</mat-hint>-->\n <!-- <mat-error *ngIf=\"hasErrors\">{{firstError}}</mat-error>-->\n <!-- <aup-icon *ngIf=\"iconPrefix\" matPrefix [icon]=\"iconPrefix\"></aup-icon>-->\n </mat-form-field>\n <aup-command *ngIf=\"editCommand.enabled$.value\" [command]=\"editCommand\" [faceModel]=\"editFaceModel\"></aup-command>\n</div>\n<aup-in-place-interaction-context [animateFirstActivity]=\"false\"></aup-in-place-interaction-context>\n", dependencies: [{ kind: "directive", type: i1$1.NgIf, selector: "[ngIf]", inputs: ["ngIf", "ngIfThen", "ngIfElse"] }, { kind: "component", type: CommandComponent, selector: "aup-command", inputs: ["command", "faceModel", "face", "busyFaceModel", "busyFace", "alignFace"] }, { kind: "directive", type: i2$4.DefaultValueAccessor, selector: "input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]" }, { kind: "directive", type: i2$4.NgControlStatus, selector: "[formControlName],[ngModel],[formControl]" }, { kind: "directive", type: i2$4.NgModel, selector: "[ngModel]:not([formControlName]):not([formControl])", inputs: ["name", "disabled", "ngModel", "ngModelOptions"], outputs: ["ngModelChange"], exportAs: ["ngModel"] }, { kind: "component", type: i3$1.MatFormField, selector: "mat-form-field", inputs: ["color", "appearance", "hideRequiredMarker", "hintLabel", "floatLabel"], exportAs: ["matFormField"] }, { kind: "directive", type: i3$1.MatLabel, selector: "mat-label" }, { kind: "directive", type: i4$1.MatInput, selector: "input[matInput], textarea[matInput], select[matNativeControl], input[matNativeControl], textarea[matNativeControl]", inputs: ["disabled", "id", "placeholder", "name", "required", "type", "errorStateMatcher", "aria-describedby", "value", "readonly"], exportAs: ["matInput"] }, { kind: "component", type: InPlaceInteractionContextComponent, selector: "aup-in-place-interaction-context", inputs: ["animateFirstActivity", "syncWithRoutes"] }] });
9550
+ __decorate([
9551
+ TrackExternal(),
9552
+ __metadata("design:type", InlineEditorModel)
9553
+ ], InlineStringEditorComponent.prototype, "editorModel", void 0);
9554
+ __decorate([
9555
+ TrackExternal(),
9556
+ __metadata("design:type", ValueModel)
9557
+ ], InlineStringEditorComponent.prototype, "facesModel", void 0);
9558
+ __decorate([
9559
+ StoreInValueModel('facesModel'),
9560
+ __metadata("design:type", Object)
9561
+ ], InlineStringEditorComponent.prototype, "faces", void 0);
9562
+ __decorate([
9563
+ StoreInValueModel('placeHolderModel'),
9564
+ __metadata("design:type", String)
9565
+ ], InlineStringEditorComponent.prototype, "placeHolder", void 0);
9566
+ __decorate([
9567
+ TrackExternal(),
9568
+ __metadata("design:type", ValueModel)
9569
+ ], InlineStringEditorComponent.prototype, "placeHolderModel", void 0);
9570
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: InlineStringEditorComponent, decorators: [{
9571
+ type: Component,
9572
+ args: [{ selector: 'aup-inline-string-editor', template: "<div class=\"container\" *ngIf=\"!editorModel.isEditing()\">\n <mat-form-field appearance=\"standard\" floatLabel=\"always\" (click)=\"startEdit()\"\n [class.editable]=\"editingEnabled.value\" [class.empty]=\"isEmpty()\">\n <mat-label *ngIf=\"label\">{{label}}</mat-label>\n <input matInput\n placeholder=\"{{placeHolder}}\"\n [ngModel]=\"editorModel.valueModel.value\"\n [disabled]=\"true\"\n >\n <!-- <mat-hint *ngIf=\"showHint\">{{hint}}</mat-hint>-->\n <!-- <mat-error *ngIf=\"hasErrors\">{{firstError}}</mat-error>-->\n <!-- <aup-icon *ngIf=\"iconPrefix\" matPrefix [icon]=\"iconPrefix\"></aup-icon>-->\n </mat-form-field>\n <aup-command *ngIf=\"editCommand.enabled$.value\" [command]=\"editCommand\" [faceModel]=\"editFaceModel\"></aup-command>\n</div>\n<aup-in-place-interaction-context [animateFirstActivity]=\"false\"></aup-in-place-interaction-context>\n" }]
9573
+ }], ctorParameters: function () { return [{ type: InteractionService }]; }, propDecorators: { editorModel: [{
9574
+ type: Input
9575
+ }], facesModel: [{
9576
+ type: Input
9577
+ }], faces: [{
9578
+ type: Input
9579
+ }], interactionContext: [{
9580
+ type: ViewChild,
9581
+ args: [InPlaceInteractionContextComponent]
9582
+ }], label: [{
9583
+ type: Input
9584
+ }], placeHolder: [{
9585
+ type: Input
9586
+ }], placeHolderModel: [{
9587
+ type: Input
9588
+ }] } });
9589
+ (function (InlineStringEditorComponent) {
9590
+ InlineStringEditorComponent.DEFAULT_FACES = {
9591
+ edit: {
9592
+ icon: () => 'mat:edit'
9593
+ },
9594
+ save: {
9595
+ icon: () => 'mat:check'
9596
+ },
9597
+ cancel: {
9598
+ icon: () => 'mat:clear'
9599
+ }
9600
+ };
9601
+ })(InlineStringEditorComponent || (InlineStringEditorComponent = {}));
9602
+
9603
+ class InteractionModule {
9604
+ }
9605
+ InteractionModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: InteractionModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
9606
+ InteractionModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "14.1.2", ngImport: i0, type: InteractionModule, declarations: [ActivityContainerComponent,
9607
+ ConfirmationDialogComponent,
9608
+ ConfirmThenDialogComponent,
9609
+ ConfirmThenExecuteDialogComponent,
9610
+ AlertDialogComponent,
9611
+ ActivityOutletComponent,
9612
+ InPlaceInteractionContextComponent,
9613
+ AddItemInteractionContextComponent,
9614
+ ActivityActionsComponent,
9615
+ PopupInteractionContextComponent,
9616
+ StringInputActivity,
9617
+ SelectInputActivity,
9618
+ InputActivity,
9619
+ InteractionContextTriggerFor,
9620
+ Activity,
9621
+ ActivityTitleComponent,
9622
+ ActivityBodyComponent,
9623
+ ActivityActionsComponent,
9624
+ AbstractActivityTriggerComponent,
9625
+ PopupActivityTriggerComponent,
9626
+ InlineActivityTriggerComponent,
9627
+ ModalActivityTriggerComponent,
9628
+ AddCardActivityComponent,
9629
+ InlineStringEditorComponent,
9630
+ AbstractDialogComponent,
9631
+ AbstractConfirmDialogComponent], imports: [CommonModule,
9632
+ MatButtonModule,
9633
+ MatDialogModule,
9634
+ MatTabsModule,
9635
+ PortalModule,
9636
+ RouterModule,
9637
+ MatIconModule,
9638
+ DirectivesModule,
9639
+ FlexModule,
9640
+ GridModule,
9641
+ ComponentsModule,
9642
+ FormsModule,
9643
+ MatInputModule,
9644
+ MatFormFieldModule,
9645
+ A11yModule], exports: [ActivityContainerComponent,
9646
+ ActivityOutletComponent,
9647
+ ActivityTitleComponent,
9648
+ InPlaceInteractionContextComponent,
9649
+ AddItemInteractionContextComponent,
9650
+ ActivityActionsComponent,
9651
+ PopupInteractionContextComponent,
9652
+ InteractionContextTriggerFor,
9653
+ StringInputActivity,
9654
+ SelectInputActivity,
9655
+ ActivityBodyComponent,
9656
+ PopupActivityTriggerComponent,
9657
+ InlineActivityTriggerComponent,
9658
+ ModalActivityTriggerComponent,
9659
+ AddCardActivityComponent,
9660
+ InlineStringEditorComponent] });
9661
+ InteractionModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: InteractionModule, providers: [
9662
+ InteractionService
9663
+ // {
9664
+ // provide: MAT_TABS_CONFIG, useValue: { animationDuration: "2s" }
9665
+ // }
9666
+ ], imports: [CommonModule,
9667
+ MatButtonModule,
9668
+ MatDialogModule,
9669
+ MatTabsModule,
9670
+ PortalModule,
9671
+ RouterModule,
9672
+ MatIconModule,
9673
+ DirectivesModule,
9674
+ FlexModule,
9675
+ GridModule,
9676
+ ComponentsModule,
9677
+ FormsModule,
9678
+ MatInputModule,
9679
+ MatFormFieldModule,
9680
+ A11yModule] });
9681
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: InteractionModule, decorators: [{
9682
+ type: NgModule,
9683
+ args: [{
9684
+ imports: [
9685
+ CommonModule,
9686
+ MatButtonModule,
9687
+ MatDialogModule,
9688
+ MatTabsModule,
9689
+ PortalModule,
9690
+ RouterModule,
9691
+ MatIconModule,
9692
+ DirectivesModule,
9693
+ FlexModule,
9694
+ GridModule,
9695
+ ComponentsModule,
9696
+ FormsModule,
9697
+ MatInputModule,
9698
+ MatFormFieldModule,
9699
+ A11yModule
9700
+ ],
9701
+ declarations: [
9702
+ ActivityContainerComponent,
9703
+ ConfirmationDialogComponent,
9704
+ ConfirmThenDialogComponent,
9705
+ ConfirmThenExecuteDialogComponent,
9706
+ AlertDialogComponent,
9707
+ ActivityOutletComponent,
9708
+ InPlaceInteractionContextComponent,
9709
+ AddItemInteractionContextComponent,
9710
+ ActivityActionsComponent,
9711
+ PopupInteractionContextComponent,
9712
+ StringInputActivity,
9713
+ SelectInputActivity,
9714
+ InputActivity,
9715
+ InteractionContextTriggerFor,
9716
+ Activity,
9717
+ ActivityTitleComponent,
9718
+ ActivityBodyComponent,
9719
+ ActivityActionsComponent,
9720
+ AbstractActivityTriggerComponent,
9721
+ PopupActivityTriggerComponent,
9722
+ InlineActivityTriggerComponent,
9723
+ ModalActivityTriggerComponent,
9724
+ AddCardActivityComponent,
9725
+ InlineStringEditorComponent,
9726
+ AbstractDialogComponent,
9727
+ AbstractConfirmDialogComponent,
9728
+ ],
9729
+ exports: [
9730
+ ActivityContainerComponent,
9731
+ ActivityOutletComponent,
9732
+ ActivityTitleComponent,
9733
+ InPlaceInteractionContextComponent,
9734
+ AddItemInteractionContextComponent,
9735
+ ActivityActionsComponent,
9736
+ PopupInteractionContextComponent,
9737
+ InteractionContextTriggerFor,
9738
+ StringInputActivity,
9739
+ SelectInputActivity,
9740
+ ActivityBodyComponent,
9741
+ PopupActivityTriggerComponent,
9742
+ InlineActivityTriggerComponent,
9743
+ ModalActivityTriggerComponent,
9744
+ AddCardActivityComponent,
9745
+ InlineStringEditorComponent,
9746
+ ],
9747
+ providers: [
9748
+ InteractionService
9749
+ // {
9750
+ // provide: MAT_TABS_CONFIG, useValue: { animationDuration: "2s" }
9751
+ // }
9752
+ ]
9753
+ }]
9754
+ }] });
9580
9755
 
9581
9756
  const AUP_PLACE_CONFIG = new InjectionToken('AUP_PLACE_CONFIG');
9582
9757
 
@@ -9648,7 +9823,7 @@ class PlaceOutletComponent extends DisposableComponent {
9648
9823
  this._activatedRouteModel = new MutableValueModel();
9649
9824
  this._activePlaceModel = new MutableValueModel();
9650
9825
  this.initialPlaceIndex = null;
9651
- this._isPushingVisitToRoute = new MutableValueModel(false);
9826
+ this._isPushingVisitToRouter = new MutableValueModel(false);
9652
9827
  this.isVeryFirstLoad = true;
9653
9828
  const { chain, valueOf, before, when, after, observe, switchOn } = Dsl.disposeWith(this);
9654
9829
  this.parentOutletModel = new MutableValueModel(parentOutlet);
@@ -9675,7 +9850,7 @@ class PlaceOutletComponent extends DisposableComponent {
9675
9850
  this.animationEnabled = valueOf.all(this.animateModel, this.animationSupported).areTruthy();
9676
9851
  // Extract our visit model from the place router.
9677
9852
  this._activePlaceDefinition = chain(this._activePlaceModel).pluck('placeDefinition');
9678
- this.routerVisitModel = chain(placeRouter.state$).map(state => state.getVisitFor(this._activePlaceDefinition.value), { dependsOn: this._activePlaceDefinition });
9853
+ this.currentVisitSegment$ = chain(placeRouter.activeVisit$).map(visit => visit.getSegmentFor(this._activePlaceDefinition.value), { dependsOn: this._activePlaceDefinition });
9679
9854
  this.navigationInProgress = chain(this.placeRouter.navigationInProgress$);
9680
9855
  when(this.navigationInProgress).becomesFalsey(() => {
9681
9856
  this.checkStateAndInitialise();
@@ -9706,15 +9881,6 @@ class PlaceOutletComponent extends DisposableComponent {
9706
9881
  return this.authorised.value;
9707
9882
  }
9708
9883
  // @Trace()
9709
- navigate(visit) {
9710
- // const place = this.placesInAnimationOrder.query().findMatching(p => visit.placeDefinition.component === p);
9711
- // if (!place) {
9712
- // lang.illegalState()
9713
- // }
9714
- this.placeRouter.navigate(visit, {
9715
- relativeTo: this.parentOutlet ? this.parentOutlet.activatedRouteModel.value : null
9716
- });
9717
- }
9718
9884
  get parentOutlet() {
9719
9885
  return this.parentOutletModel.value;
9720
9886
  }
@@ -9752,7 +9918,7 @@ class PlaceOutletComponent extends DisposableComponent {
9752
9918
  }
9753
9919
  // @Trace()
9754
9920
  checkStateAndInitialise() {
9755
- const routerVisit = this.routerVisitModel.value;
9921
+ const routerVisit = this.currentVisitSegment$.value;
9756
9922
  const activePlace = this.activePlaceModel.value;
9757
9923
  if (routerVisit && activePlace && !activePlace.isInitialised()) {
9758
9924
  if (routerVisit.placeDefinition !== activePlace.placeDefinition) {
@@ -9765,8 +9931,8 @@ class PlaceOutletComponent extends DisposableComponent {
9765
9931
  initialisePlace(routerVisit, activePlace) {
9766
9932
  const visitModel = new MutableValueModel(routerVisit);
9767
9933
  DebugContext.tag(visitModel, `PlaceOutletComponent[${activePlace.constructor.name})].visitModel`);
9768
- activePlace.initialiseVisit(routerVisit, (current, previous) => {
9769
- this.pushVisitChangeToRoute(previous, current);
9934
+ activePlace.initialiseVisit(routerVisit, (is, was) => {
9935
+ this.notifyComponentVisitSegmentChanged(is, was);
9770
9936
  });
9771
9937
  const finishPlaceLoad = () => {
9772
9938
  this._activePlaceModel.value._notifyActive(true);
@@ -9782,30 +9948,40 @@ class PlaceOutletComponent extends DisposableComponent {
9782
9948
  this.onAnimationFinishedJob = finishPlaceLoad;
9783
9949
  }
9784
9950
  const { when, chain, valueOf } = Dsl.disposeWith(activePlace);
9785
- when(this.routerVisitModel)
9951
+ when(this.currentVisitSegment$)
9786
9952
  .changes(visit => {
9787
9953
  // console.log("routerVisitModel.change", { routerVisitModel: this.routerVisitModel.value })
9788
9954
  this.pushVisitChangeToComponent(activePlace, visit);
9789
9955
  }, {
9790
- unless: valueOf.any(this._isPushingVisitToRoute, this.routerVisitModel.isNil()).areTruthy()
9956
+ unless: valueOf.any(this._isPushingVisitToRouter, this.currentVisitSegment$.isNil()).areTruthy()
9791
9957
  });
9958
+ // chain(this.currentVisitSegment$).subscribe(it => {
9959
+ // if (it) {
9960
+ // console.log("PlaceOutlet segment updated", it.toDebugString(), {
9961
+ // isPushing: this._isPushingVisitToRouter.value,
9962
+ // segment: this.currentVisitSegment$.value?.toDebugString()
9963
+ // })
9964
+ // }
9965
+ // })
9792
9966
  }
9793
- pushVisitChangeToComponent(activePlace, visit) {
9794
- activePlace.updateVisit(visit);
9967
+ pushVisitChangeToComponent(activePlace, segment) {
9968
+ // console.log("PlaceOutlet.pushVisitChangeToComponent", segment.toDebugString());
9969
+ activePlace.updateVisit(segment);
9795
9970
  }
9796
- pushVisitChangeToRoute(previous, current) {
9971
+ notifyComponentVisitSegmentChanged(is, was) {
9797
9972
  return __awaiter(this, void 0, void 0, function* () {
9798
9973
  try {
9799
- this._isPushingVisitToRoute.value = true;
9800
- yield this.placeRouter.pushVisitChangesToRoute(previous, current);
9974
+ this._isPushingVisitToRouter.value = true;
9975
+ yield this.placeRouter.notifyVisitSegmentChanged(is, was);
9801
9976
  }
9802
9977
  finally {
9803
- this._isPushingVisitToRoute.value = false;
9978
+ this._isPushingVisitToRouter.value = false;
9804
9979
  }
9805
9980
  // sanitisers may have adjusted other values in the visit to we check and write it back.
9806
- const routerVisit = this.routerVisitModel.value; // this is occasionally null... need to investigate if that's a normal state or not.
9807
- if (routerVisit && current.hasRoutingChangedFrom(routerVisit)) {
9808
- this.pushVisitChangeToComponent(this.activePlaceModel.value, routerVisit);
9981
+ const andBecame = this.currentVisitSegment$.value; // this is occasionally null... need to investigate if that's a normal state or not.
9982
+ // console.log("PlaceOutlet.notifyComponentVisitSegmentChanged", { is, was, andBecame })
9983
+ if (andBecame && andBecame.hasChangedFrom(is)) {
9984
+ this.pushVisitChangeToComponent(this.activePlaceModel.value, andBecame);
9809
9985
  }
9810
9986
  });
9811
9987
  }
@@ -9883,19 +10059,20 @@ class AbstractPlaceNavigationComponent extends DisposableComponent {
9883
10059
  super();
9884
10060
  this.placeRouter = placeRouter;
9885
10061
  this._activePlaceComponent = this.registerDisposable(new DelegatingValueModel());
10062
+ this.placeFaces = new Map();
9886
10063
  this.trackByPlaceDef = (index, data) => data.place;
9887
10064
  const { chain, valueOf, before, when, after, observe, switchOn } = Dsl.disposeWith(this);
9888
10065
  this.placeDefinitions = chain(this.placesModel)
9889
10066
  .map(c => PlaceComponent.getDefinition(c))
9890
10067
  .select(d => {
9891
10068
  const guard = placeRouter.accessGuard$.value;
9892
- return guard.isAuthorised(d);
10069
+ return guard.isAuthorised(d) || placeRouter.activeVisit$.value.isPlaceActive(d);
9893
10070
  }, {
9894
10071
  postponeWhile: placeRouter.navigationInProgress$,
9895
- dependsOn: [placeRouter.accessGuard$, placeRouter.state$]
10072
+ dependsOn: [placeRouter.accessGuard$, placeRouter.activeVisit$]
9896
10073
  });
9897
10074
  this.commandFactory = Command.createFactory((placeDefinition) => {
9898
- this.placeOutlet.navigate(new Visit(placeDefinition));
10075
+ this.placeRouter.navigate(placeDefinition.component);
9899
10076
  });
9900
10077
  when(this.placeOutletModel).changes(outlet => this.handlePlaceOutLetChanged(outlet), { initialValue: "triggerChange" });
9901
10078
  this.activePlaceDefinition = chain(this._activePlaceComponent).pluck('placeDefinition');
@@ -9917,6 +10094,14 @@ class AbstractPlaceNavigationComponent extends DisposableComponent {
9917
10094
  this._activePlaceComponent.setDelegate(outlet ? outlet.activePlaceModel : null);
9918
10095
  }
9919
10096
  getNavigationFace(placeDef) {
10097
+ let face = this.placeFaces.get(placeDef);
10098
+ if (!face) {
10099
+ face = this.createCommandFaceFor(placeDef);
10100
+ this.placeFaces.set(placeDef, face);
10101
+ }
10102
+ return face;
10103
+ }
10104
+ createCommandFaceFor(placeDef) {
9920
10105
  const navItem = placeDef.getPlaceData('nav');
9921
10106
  return {
9922
10107
  text: () => navItem ? navItem.title() : placeDef.searchPlaceData(['navTitle', 'title']),
@@ -9945,12 +10130,6 @@ __decorate([
9945
10130
  TrackExternal(),
9946
10131
  __metadata("design:type", ValueModel)
9947
10132
  ], AbstractPlaceNavigationComponent.prototype, "placeOutletModel", void 0);
9948
- __decorate([
9949
- Memoize(),
9950
- __metadata("design:type", Function),
9951
- __metadata("design:paramtypes", [PlaceDefinition]),
9952
- __metadata("design:returntype", Object)
9953
- ], AbstractPlaceNavigationComponent.prototype, "getNavigationFace", null);
9954
10133
  i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.1.2", ngImport: i0, type: AbstractPlaceNavigationComponent, decorators: [{
9955
10134
  type: Component,
9956
10135
  args: [{
@@ -9964,7 +10143,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.1.2", ngImpor
9964
10143
  type: Input
9965
10144
  }], placeOutletModel: [{
9966
10145
  type: Input
9967
- }], getNavigationFace: [] } });
10146
+ }] } });
9968
10147
 
9969
10148
  class ListPlaceNavComponent extends AbstractPlaceNavigationComponent {
9970
10149
  constructor(router) {
@@ -10365,7 +10544,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.1.2", ngImpor
10365
10544
  }]
10366
10545
  }], ctorParameters: function () { return []; } });
10367
10546
 
10368
- class VisitSanitiser {
10547
+ class VisitSegmentSanitiser {
10369
10548
  constructor(navigationSession, activatedRoute, router, placeHistory, injector) {
10370
10549
  this.navigationSession = navigationSession;
10371
10550
  this.activatedRoute = activatedRoute;
@@ -10374,19 +10553,19 @@ class VisitSanitiser {
10374
10553
  this.injector = injector;
10375
10554
  }
10376
10555
  // @Trace()
10377
- sanitise(visit) {
10556
+ sanitise(segment) {
10378
10557
  return __awaiter(this, void 0, void 0, function* () {
10379
- const placeDef = visit.placeDefinition;
10558
+ const placeDef = segment.placeDefinition;
10380
10559
  if (placeDef.hasRouteId()) {
10381
10560
  const routeIdDef = placeDef.getRouteIdParameterDef();
10382
- const routeId = visit.getRouteId();
10383
- const sanitisedValue = yield routeIdDef.sanitise(routeId, visit, this.placeHistory, this.injector, this.navigationSession.isPopState);
10561
+ const routeId = segment.getRouteId();
10562
+ const sanitisedValue = yield routeIdDef.sanitise(routeId, segment, this.placeHistory, this.injector, this.navigationSession.isPopState);
10384
10563
  // console.log({routeId, sanitisedValue});
10385
10564
  // ###------- EARLY EXIT --------###
10386
10565
  if (routeIdDef.hasChanged(routeId, sanitisedValue)) {
10387
10566
  // if the route id has changed we redirect immediately as other
10388
10567
  // parameter sanitisers might use it.
10389
- return visit.replace(routeIdDef, sanitisedValue);
10568
+ return segment.replace(routeIdDef, sanitisedValue);
10390
10569
  }
10391
10570
  }
10392
10571
  // if we didn't replace the routeId we continue the url present parameters.
@@ -10394,16 +10573,16 @@ class VisitSanitiser {
10394
10573
  includeRouteParameters: true,
10395
10574
  includeNonRouteParameters: true
10396
10575
  });
10397
- let sanitisedVisit = visit;
10576
+ let sanitisedSegment = segment;
10398
10577
  for (let i = 0; i < parameterDefs.length; i++) {
10399
10578
  const def = parameterDefs[i];
10400
- const value = visit.getParameterValue(def);
10401
- const sanitisedValue = yield def.sanitise(value, sanitisedVisit, this.placeHistory, this.injector, this.navigationSession.isPopState);
10579
+ const value = segment.getParameterValue(def);
10580
+ const sanitisedValue = yield def.sanitise(value, sanitisedSegment, this.placeHistory, this.injector, this.navigationSession.isPopState);
10402
10581
  if (def.hasChanged(value, sanitisedValue)) {
10403
- sanitisedVisit = sanitisedVisit.replace(def, sanitisedValue);
10582
+ sanitisedSegment = sanitisedSegment.replace(def, sanitisedValue);
10404
10583
  }
10405
10584
  }
10406
- return sanitisedVisit.hasChangedFrom(visit) ? sanitisedVisit : visit;
10585
+ return sanitisedSegment.hasChangedFrom(segment) ? sanitisedSegment : segment;
10407
10586
  });
10408
10587
  }
10409
10588
  }
@@ -10417,28 +10596,26 @@ class PlaceGuard {
10417
10596
  this.interactionService = interactionService;
10418
10597
  this.injector = injector;
10419
10598
  }
10599
+ get accessGuard() {
10600
+ return this.placeRouter.accessGuard$.value;
10601
+ }
10420
10602
  // @Trace()
10421
10603
  canActivate(activatedRoute, state) {
10422
10604
  return __awaiter(this, void 0, void 0, function* () {
10423
10605
  if (PlaceComponent.isPlaceComponentConstructor(activatedRoute.component)) {
10424
10606
  const placeDefinition = PlaceComponent.getDefinition(activatedRoute.component);
10425
- const accessGuard = this.placeRouter.accessGuard$.value;
10426
10607
  if (placeDefinition.authenticate) {
10427
- const authenticated = yield accessGuard.isAuthenticated();
10608
+ const authenticated = yield this.accessGuard.isAuthenticated();
10428
10609
  if (!authenticated) {
10429
- const redirectLocation = this.placeRouter.getAuthenticationFailureRedirect(activatedRoute, state);
10430
- const nextPlaceDef = this.getPlaceDefinition(redirectLocation);
10431
- if (nextPlaceDef.authenticate) {
10432
- lang.illegalState(`onAuthenticationFailure hook returned place ${nextPlaceDef.component.name} that requires authentication.`);
10610
+ const redirect = this.placeRouter.getAuthenticationFailureRedirect(activatedRoute, state);
10611
+ // const nextPlaceDef = this.getPlaceDefinition(redirect);
10612
+ if (redirect.requiresAuthentication()) {
10613
+ lang.illegalState(`onAuthenticationFailure hook returned place ${redirect.toDebugString()} that requires authentication.`);
10433
10614
  }
10434
- return this.createUrlTree(redirectLocation);
10615
+ return this.createUrlTree(redirect);
10435
10616
  }
10436
- if (!accessGuard.isAuthorised(placeDefinition)) {
10437
- const redirectOptions = this.placeRouter.getAuthorisationFailureRedirectOptions(activatedRoute.component);
10438
- const nextRedirect = redirectOptions.find(it => accessGuard.isAuthorised(this.getPlaceDefinition(it)));
10439
- if (!nextRedirect) {
10440
- lang.illegalState(`onAuthorisationFailure hook didn't return any authorised locations: ${redirectOptions.map(it => this.getPlaceDefinition(it).component.name).join(', ')}`);
10441
- }
10617
+ if (!this.accessGuard.isAuthorised(placeDefinition)) {
10618
+ const nextRedirect = this.findBestAuthenticatedAlternative(placeDefinition, activatedRoute);
10442
10619
  return this.createUrlTree(nextRedirect);
10443
10620
  }
10444
10621
  }
@@ -10448,17 +10625,16 @@ class PlaceGuard {
10448
10625
  const params = new ConsolidatedParameterMap(activatedRoute.url, activatedRoute.paramMap);
10449
10626
  // console.log("RouteParams", params)
10450
10627
  const parsedParams = placeDefinition.parseRouteParams(params);
10451
- const initialVisit = navigationSession.getVisitFor(placeDefinition) || new Visit(placeDefinition, parsedParams);
10452
- const sanitiser = new VisitSanitiser(navigationSession, activatedRoute, this.router, this.placeHistory, this.injector);
10628
+ const initialVisit = navigationSession.getVisitSegmentFor(placeDefinition) || new VisitSegment(placeDefinition, parsedParams);
10629
+ const sanitiser = new VisitSegmentSanitiser(navigationSession, activatedRoute, this.router, this.placeHistory, this.injector);
10453
10630
  const sanitisedVisit = yield sanitiser.sanitise(initialVisit.mergeRouteParameters(parsedParams));
10454
10631
  // Save the visit with any updated parameters. We need to save it so we remember any non route parameters
10455
- navigationSession.storeVisit(sanitisedVisit);
10632
+ navigationSession.updateVisitSegment(sanitisedVisit);
10456
10633
  const destUrlSnapshot = this.urlService.parseUrl(state.url);
10457
10634
  if (initialVisit.hasRoutingChangedFrom(sanitisedVisit)) {
10458
- // Regenerate the url
10459
- const urlSnapshot = destUrlSnapshot.updateVisitSegments(sanitisedVisit);
10460
- console.log('##### Place Guard Redirect', urlSnapshot);
10461
- return urlSnapshot;
10635
+ // Regenerate the url and update our visit segment in the session
10636
+ // console.log('##### Place Guard Redirect', destUrlSnapshot.updateVisitSegment(sanitisedVisit));
10637
+ return destUrlSnapshot.updateVisitSegment(sanitisedVisit);
10462
10638
  }
10463
10639
  else {
10464
10640
  // Our visit parameters are all sorted, now check if we should redirect to our child.
@@ -10467,8 +10643,8 @@ class PlaceGuard {
10467
10643
  lang.illegalState(`redirectToFirstChild set to true, but there were no children `);
10468
10644
  }
10469
10645
  for (let child of placeDefinition.children) {
10470
- if (!child.authenticate || accessGuard.isAuthorised(child)) {
10471
- return destUrlSnapshot.appendVisit(new Visit(child));
10646
+ if (!child.authenticate || this.accessGuard.isAuthorised(child)) {
10647
+ return destUrlSnapshot.appendSegment(new VisitSegment(child));
10472
10648
  }
10473
10649
  }
10474
10650
  // hmm, what should I do here, we didn't have an authorised child
@@ -10484,6 +10660,25 @@ class PlaceGuard {
10484
10660
  }
10485
10661
  });
10486
10662
  }
10663
+ findBestAuthenticatedAlternative(placeDefinition, activatedRoute) {
10664
+ let currentPlace = placeDefinition;
10665
+ while (!currentPlace.isRoot()) {
10666
+ currentPlace = currentPlace.parent;
10667
+ const permittedChild = currentPlace.findChild(c => this.accessGuard.isAuthorised(c));
10668
+ if (permittedChild) {
10669
+ return Visit.goto(permittedChild.component);
10670
+ }
10671
+ }
10672
+ // Couldn't find an authorised ancestor so we check if there are router level defined alternatives
10673
+ const alternativeRoutes = this.placeRouter.getAuthorisationFailureRedirectOptions(activatedRoute.component);
10674
+ if (alternativeRoutes.length < 1) {
10675
+ return lang.illegalState(`onAuthorisationFailure hook didn't return any alternate places`);
10676
+ }
10677
+ else {
10678
+ const nextRedirect = alternativeRoutes.find(it => it.isAuthorised(this.accessGuard));
10679
+ return nextRedirect !== null && nextRedirect !== void 0 ? nextRedirect : lang.illegalState(`onAuthorisationFailure hook didn't return any authorised locations`);
10680
+ }
10681
+ }
10487
10682
  // @Trace()
10488
10683
  canDeactivate(component, currentRoute, currentState, nextState) {
10489
10684
  return __awaiter(this, void 0, void 0, function* () {
@@ -10499,13 +10694,14 @@ class PlaceGuard {
10499
10694
  });
10500
10695
  }
10501
10696
  getPlaceDefinition(result) {
10502
- return result instanceof Visit ?
10697
+ return result instanceof VisitSegment ?
10503
10698
  result.placeDefinition :
10504
- PlaceComponent.getDefinition(result);
10699
+ result instanceof PlaceDefinition ?
10700
+ result :
10701
+ PlaceComponent.getDefinition(result);
10505
10702
  }
10506
- createUrlTree(result) {
10507
- const visit = result instanceof Visit ? result : new Visit(PlaceComponent.getDefinition(result), {});
10508
- return this.urlService.createUrlSnapshot(visit).urlTree;
10703
+ createUrlTree(visit) {
10704
+ return this.urlService.createUrlSnapshot(visit.segments).urlTree;
10509
10705
  }
10510
10706
  // @Trace()
10511
10707
  cleanInteractionState(route, state, next) {
@@ -10716,5 +10912,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "14.1.2", ngImpor
10716
10912
  * Generated bundle index. Do not edit.
10717
10913
  */
10718
10914
 
10719
- export { ACTIVITY_DATA, ALERT_CONFIG, AUP_PLACE_CONFIG, AUP_UNAUTHORISED_PLACE_NOTICE_COMPONENT, AbstractActivityTriggerComponent, AbstractCardContainerComponent, AbstractConfirmDialogComponent, AbstractDialogComponent, AbstractInputComponent, AbstractInteractionContext, AbstractListInputComponent, AbstractPlaceNavigationComponent, AbstractPopStateNavigation, AbstractPopupMenuComponent, AbstractTableComponent, AbstractTableModel, AbstractValueInputComponent, Activity, ActivityActionsComponent, ActivityBodyComponent, ActivityContainerComponent, ActivityOutletComponent, ActivityRef, ActivityTitleComponent, AddCardActivityComponent, AddItemInteractionContextComponent, Alert, AlertDialogComponent, AngularUiPowerupsModule, AutocompleteInputComponent, Bounds, BusyOverlayComponent, CELL_EDITOR_PORTAL, CELL_RENDERER_PORTAL, CardContainerComponent, CardStackComponent, CellEditorPortalRef, CellHeaderPortalRef, CellPortalRef, CellRendererPortalRef, CheckboxInputComponent, ColumnListModel, ColumnModel, ColumnTemplateDirective, ColumnTextSearchFormatter, CommandComponent, CommandContainer, CommandDirective, CommandFace, CommandFaceComponent, ComponentCellRendererPortalRef, ComponentsModule, ConfirmThenDialogComponent, ConfirmThenExecuteDialogComponent, ConfirmationDialogComponent, ConsolidatedParameterMap, CustomTemplateColumnModel, CustomValueColumnModel, DEFINITION_META_DATA_KEY, DIALOG_INTERACTION_SERVICE_DEFAULTS, DecoratedTreeNode, DefaultCellRendererComponent, DefaultHeaderCellRendererComponent, DialogInteractionContext, DialogInteractionContextFactory, Dimension, DirectivesModule, DisposableComponent, EditRowControls, EditSession, EditorControlColumnModel, EmptyStateComponent, EnableCellTextSearch, EventCleanUpSession, FlattenedTreeListModel, FlexComponent, FocusBinding, FocusBindingDirective, FocusBindingFactory, FocusContainerComponent, FocusableComponent, Formatter, GarbageCollectorDirective, HEADER_CELL_RENDERER_PORTAL, HighlightPipe, HighlightTextModelDirective, HorizontalAlignment, IconComponent, InPlaceInteractionContextComponent, InlineActivityTriggerComponent, InlineEditorModel, InlineStringEditorComponent, InputActivity, InteractionContextTriggerFor, InteractionModule, InteractionService, InteractionServiceRoutingAdapter, Keys, LEFT_RIGHT_PLACE_ANIMATION, LabelledValueComponent, ListPlaceNavComponent, ListPropertyColumnModel, LoadingContainerComponent, MarkdownComponent, MarkdownService, ModalActivityTriggerComponent, ModalInteractionContextFactory, MoreMenuComponent, MultipleSelectInputComponent, Navigating, NavigatingDuringInteraction, NavigationContext, NavigationSession, NoopAuthGuard, NoopComponent, NotAuthorisedNoticeComponent, NumberInputComponent, POPUP_CONTAINER, PORTAL_EDITOR_COMPONENT, PORTAL_RENDERER_COMPONENT, PaginatorComponent, ParameterDefinition, PasswordInputComponent, Place, PlaceAccessGuard, PlaceComponent, PlaceComponentDeactivationHandler, PlaceDefinition, PlaceGuard, PlaceHistory, PlaceModule, PlaceOutletComponent, PlaceRouter, Point, PopStateDuringInteractionNavigation, PopStateNavigation, PopupActivityTriggerComponent, PopupAwareComponent, PopupInteractionContextComponent, PopupMenuComponent, PopupMenuRendererComponent, PropertyColumnModel, ROUTE_PARAMETER_LIST_KEY, RemoveLastInteractionFromUrlNavigationSession, ResizeAwareComponent, RouteId, ScrollContainerComponent, SectionHeaderComponent, SelectInputActivity, SelectInputComponent, SelectionCellComponent, SelectionColumnModel, SelectionHeaderCellComponent, SeparatorComponent, SidePlaceNavigationComponent, StringInputActivity, StringInputComponent, SwitchCaseComponent, SwitchCaseDefaultDirective, SwitchCaseOption, SwitchCaseWhenDirective, SynchroniseInteractionContextIdsWithRoute, TabbedPlaceNavigationComponent, TableBodyComponent, TableCellComponent, TableComponent, TableFilterModel, TableHeaderCellComponent, TableModel, TableRowMenuComponent, TemplateCellRendererPortalRef, TextInputComponent, ToolBarComponent, TrackBy, TreeExpansionModel, TreeInheritanceIconComponent, TreeLabelCellRendererComponent, TreeLabelColumnModel, TreeTableComponent, TreeTableModel, UrlService, UrlSnapshot, VerticalFocusContainerComponent, VisibilityService, Visit, VisitParameter, VisitParameterList, VisitSanitiser, WaitUntilLeavingInteractionTransitionCancelled, WaitUntilLinkTriggeredNavigationInteractionCancellationTypeDetermined, WaitUntilPopStateDuringCanDeactivateInteractionFinishes, leftRightPlaceAnimation, markdownPillExtension, slideDownOnEnterAnimation, slideRightOnEnterAnimation, treeNodeDecorator };
10915
+ export { ACTIVITY_DATA, ALERT_CONFIG, AUP_PLACE_CONFIG, AUP_UNAUTHORISED_PLACE_NOTICE_COMPONENT, AbstractActivityTriggerComponent, AbstractCardContainerComponent, AbstractConfirmDialogComponent, AbstractDialogComponent, AbstractInputComponent, AbstractInteractionContext, AbstractListInputComponent, AbstractPlaceNavigationComponent, AbstractPopStateNavigation, AbstractPopupMenuComponent, AbstractTableComponent, AbstractTableModel, AbstractValueInputComponent, Activity, ActivityActionsComponent, ActivityBodyComponent, ActivityContainerComponent, ActivityOutletComponent, ActivityRef, ActivityTitleComponent, AddCardActivityComponent, AddItemInteractionContextComponent, Alert, AlertDialogComponent, AngularUiPowerupsModule, AutocompleteInputComponent, Bounds, BusyOverlayComponent, CELL_EDITOR_PORTAL, CELL_RENDERER_PORTAL, CardContainerComponent, CardStackComponent, CellEditorPortalRef, CellHeaderPortalRef, CellPortalRef, CellRendererPortalRef, CheckboxInputComponent, ColumnListModel, ColumnModel, ColumnTemplateDirective, ColumnTextSearchFormatter, CommandComponent, CommandContainer, CommandDirective, CommandFace, CommandFaceComponent, ComponentCellRendererPortalRef, ComponentsModule, ConfirmThenDialogComponent, ConfirmThenExecuteDialogComponent, ConfirmationDialogComponent, ConsolidatedParameterMap, CustomTemplateColumnModel, CustomValueColumnModel, DEFINITION_META_DATA_KEY, DIALOG_INTERACTION_SERVICE_DEFAULTS, DecoratedTreeNode, DefaultCellRendererComponent, DefaultHeaderCellRendererComponent, DialogInteractionContext, DialogInteractionContextFactory, Dimension, DirectivesModule, DisposableComponent, EditRowControls, EditSession, EditorControlColumnModel, EmptyStateComponent, EnableCellTextSearch, EventCleanUpSession, FlattenedTreeListModel, FlexComponent, FocusBinding, FocusBindingDirective, FocusBindingFactory, FocusContainerComponent, FocusableComponent, Formatter, GarbageCollectorDirective, HEADER_CELL_RENDERER_PORTAL, HighlightPipe, HighlightTextModelDirective, HorizontalAlignment, IconComponent, InPlaceInteractionContextComponent, InlineActivityTriggerComponent, InlineEditorModel, InlineStringEditorComponent, InputActivity, InteractionContextTriggerFor, InteractionModule, InteractionService, InteractionServiceRoutingAdapter, Keys, LEFT_RIGHT_PLACE_ANIMATION, LabelledValueComponent, ListPlaceNavComponent, ListPropertyColumnModel, LoadingContainerComponent, MarkdownComponent, MarkdownService, ModalActivityTriggerComponent, ModalInteractionContextFactory, MoreMenuComponent, MultipleSelectInputComponent, Navigating, NavigatingDuringInteraction, NavigationContext, NavigationSession, NoopAuthGuard, NoopComponent, NotAuthorisedNoticeComponent, NumberInputComponent, POPUP_CONTAINER, PORTAL_EDITOR_COMPONENT, PORTAL_RENDERER_COMPONENT, PaginatorComponent, ParameterDefinition, PasswordInputComponent, Place, PlaceAccessGuard, PlaceComponent, PlaceComponentDeactivationHandler, PlaceDefinition, PlaceGuard, PlaceHistory, PlaceModule, PlaceOutletComponent, PlaceRouter, Point, PopStateDuringInteractionNavigation, PopStateNavigation, PopupActivityTriggerComponent, PopupAwareComponent, PopupInteractionContextComponent, PopupMenuComponent, PopupMenuRendererComponent, PropertyColumnModel, ROUTE_PARAMETER_LIST_KEY, RemoveLastInteractionFromUrlNavigationSession, ResizeAwareComponent, RouteId, ScrollContainerComponent, SectionHeaderComponent, SelectInputActivity, SelectInputComponent, SelectionCellComponent, SelectionColumnModel, SelectionHeaderCellComponent, SeparatorComponent, SidePlaceNavigationComponent, StringInputActivity, StringInputComponent, SwitchCaseComponent, SwitchCaseDefaultDirective, SwitchCaseOption, SwitchCaseWhenDirective, SynchroniseInteractionContextIdsWithRoute, TabbedPlaceNavigationComponent, TableBodyComponent, TableCellComponent, TableComponent, TableFilterModel, TableHeaderCellComponent, TableModel, TableRowMenuComponent, TemplateCellRendererPortalRef, TextInputComponent, ToolBarComponent, TrackBy, TreeExpansionModel, TreeInheritanceIconComponent, TreeLabelCellRendererComponent, TreeLabelColumnModel, TreeTableComponent, TreeTableModel, UrlService, UrlSnapshot, VerticalFocusContainerComponent, VisibilityService, Visit, VisitParameter, VisitParameterList, VisitSegment, VisitSegmentSanitiser, WaitUntilLeavingInteractionTransitionCancelled, WaitUntilLinkTriggeredNavigationInteractionCancellationTypeDetermined, WaitUntilPopStateDuringCanDeactivateInteractionFinishes, leftRightPlaceAnimation, markdownPillExtension, slideDownOnEnterAnimation, slideRightOnEnterAnimation, treeNodeDecorator };
10720
10916
  //# sourceMappingURL=coolon-angular-ui-powerups.mjs.map