@mmstack/router-core 20.5.1 → 20.5.3

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.
@@ -1,5 +1,5 @@
1
1
  import * as i0 from '@angular/core';
2
- import { InjectionToken, inject, computed, Injectable, input, booleanAttribute, output, untracked, effect, HostListener, Directive, isSignal, linkedSignal } from '@angular/core';
2
+ import { InjectionToken, inject, computed, Injectable, input, booleanAttribute, output, untracked, effect, HostListener, Directive, isSignal, EnvironmentInjector, runInInjectionContext, linkedSignal } from '@angular/core';
3
3
  import * as i1 from '@angular/router';
4
4
  import { EventType, Router, PRIMARY_OUTLET, createUrlTreeFromSnapshot, UrlTree, RouterLink, RouterLinkWithHref, ActivatedRoute } from '@angular/router';
5
5
  import { mutable, mapArray, until, elementVisibility, toWritable } from '@mmstack/primitives';
@@ -11,7 +11,7 @@ import { Title } from '@angular/platform-browser';
11
11
  /**
12
12
  * @internal
13
13
  */
14
- const token$1 = new InjectionToken('MMSTACK_BREADCRUMB_CONFIG');
14
+ const token$2 = new InjectionToken('@mmstack/router-core:breadcrumb-config');
15
15
  /**
16
16
  * Provides configuration for the breadcrumb system.
17
17
  * @param config - A partial `BreadcrumbConfig` object with the desired settings. *
@@ -43,7 +43,7 @@ const token$1 = new InjectionToken('MMSTACK_BREADCRUMB_CONFIG');
43
43
  */
44
44
  function provideBreadcrumbConfig(config) {
45
45
  return {
46
- provide: token$1,
46
+ provide: token$2,
47
47
  useValue: {
48
48
  ...config,
49
49
  },
@@ -53,7 +53,7 @@ function provideBreadcrumbConfig(config) {
53
53
  * @internal
54
54
  */
55
55
  function injectBreadcrumbConfig() {
56
- return (inject(token$1, {
56
+ return (inject(token$2, {
57
57
  optional: true,
58
58
  }) ?? {});
59
59
  }
@@ -95,8 +95,9 @@ function isNavigationEnd(e) {
95
95
  * }
96
96
  * ```
97
97
  */
98
- function url() {
99
- const router = inject(Router);
98
+ function url(router) {
99
+ if (!router)
100
+ router = inject(Router);
100
101
  return toSignal(router.events.pipe(filter(isNavigationEnd), map((e) => e.urlAfterRedirects)), {
101
102
  initialValue: router.url,
102
103
  });
@@ -515,10 +516,11 @@ function injectSnapshotPathResolver() {
515
516
  /**
516
517
  * Creates and registers a breadcrumb for a specific route.
517
518
  * This function is designed to be used as an Angular Route `ResolveFn`.
518
- * It handles the registration of the breadcrumb with the `BreadcrumbStore`
519
- * and ensures automatic deregistration when the route is destroyed.
520
519
  *
521
- * @param factory A function that returns a `CreateBreadcrumbOptions` object.
520
+ * Accepts a static label (`string`), a static options object, or a factory returning either —
521
+ * use a factory when you need `inject()` for dynamic data.
522
+ *
523
+ * @param factoryOrValue A static label, a static `CreateBreadcrumbOptions`, or a factory returning either.
522
524
  * @see CreateBreadcrumbOptions
523
525
  *
524
526
  * @example
@@ -528,25 +530,34 @@ function injectSnapshotPathResolver() {
528
530
  * path: 'home',
529
531
  * component: HomeComponent,
530
532
  * resolve: {
531
- * breadcrumb: createBreadcrumb(() => ({
532
- * label: 'Home',
533
- * });
533
+ * // shorthand for { label: 'Home' }
534
+ * breadcrumb: createBreadcrumb('Home'),
534
535
  * },
536
+ * },
537
+ * {
535
538
  * path: 'users/:userId',
536
539
  * component: UserProfileComponent,
537
540
  * resolve: {
538
541
  * breadcrumb: createBreadcrumb(() => {
539
542
  * const userStore = inject(UserStore);
540
543
  * return {
541
- * label: () => userStore.user().name ?? 'Loading...
542
- * };
543
- * })
544
+ * label: () => userStore.user().name ?? 'Loading...',
545
+ * };
546
+ * }),
544
547
  * },
545
- * }
548
+ * },
546
549
  * ];
547
550
  * ```
548
551
  */
549
- function createBreadcrumb(factory) {
552
+ function createBreadcrumb(factoryOrValue) {
553
+ const factory = typeof factoryOrValue === 'string'
554
+ ? () => ({ label: factoryOrValue })
555
+ : typeof factoryOrValue === 'function'
556
+ ? () => {
557
+ const result = factoryOrValue();
558
+ return typeof result === 'string' ? { label: result } : result;
559
+ }
560
+ : () => factoryOrValue;
550
561
  return async (route) => {
551
562
  const router = inject(Router);
552
563
  const store = inject(BreadcrumbStore);
@@ -650,6 +661,38 @@ function treeToSerializedUrl(router, urlTree) {
650
661
  return null;
651
662
  return router.serializeUrl(urlTree);
652
663
  }
664
+ /**
665
+ * Returns an imperative function that triggers preloading for an arbitrary link, using
666
+ * the same path resolution and {@link PreloadStrategy} pipeline as the {@link Link}
667
+ * (`mmLink`) directive.
668
+ *
669
+ * Use this when the `Link` directive isn't a fit — for example, preloading a route from
670
+ * an effect when a user opens a menu, hovers a non-link element, or reacts to a signal
671
+ * change — and you don't want to render an `<a [mmLink]>` just to request the preload.
672
+ *
673
+ * Requires {@link PreloadStrategy} to be wired up via `provideRouter(routes, withPreloading(PreloadStrategy))`,
674
+ * just like the directive.
675
+ *
676
+ * @returns A function accepting the same link descriptor shape as `mmLink` (`string`,
677
+ * commands array, `UrlTree`, or `null`). Passing `null` or an unresolvable link is a no-op.
678
+ *
679
+ * @example
680
+ * ```typescript
681
+ * @Component({ ... })
682
+ * export class CommandPaletteComponent {
683
+ * private readonly triggerPreload = injectTriggerPreload();
684
+ *
685
+ * protected readonly highlighted = signal<string | null>(null);
686
+ *
687
+ * constructor() {
688
+ * effect(() => {
689
+ * const target = this.highlighted();
690
+ * if (target) this.triggerPreload(target);
691
+ * });
692
+ * }
693
+ * }
694
+ * ```
695
+ */
653
696
  function injectTriggerPreload() {
654
697
  const req = inject(PreloadRequester);
655
698
  const router = inject(Router);
@@ -793,6 +836,277 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.17", ngImpo
793
836
  ]]
794
837
  }] } });
795
838
 
839
+ /** @internal */
840
+ const token$1 = new InjectionToken('@mmstack/router-core:nav-config');
841
+ /**
842
+ * Provides global configuration for the nav system.
843
+ *
844
+ * @example
845
+ * ```typescript
846
+ * provideNavConfig({
847
+ * activeMatch: { queryParams: 'ignored' },
848
+ * defaults: [
849
+ * { label: 'Home', link: '/' },
850
+ * { label: 'Docs', link: '/docs' },
851
+ * ],
852
+ * }),
853
+ * ```
854
+ */
855
+ function provideNavConfig(config) {
856
+ const fn = typeof config === 'function' ? config : () => ({ ...config });
857
+ return {
858
+ provide: token$1,
859
+ useFactory: fn,
860
+ };
861
+ }
862
+ /** @internal */
863
+ function injectNavConfig() {
864
+ return inject(token$1, { optional: true }) ?? {};
865
+ }
866
+
867
+ /** @internal */
868
+ const NEVER_TRUE = computed(() => false, ...(ngDevMode ? [{ debugName: "NEVER_TRUE" }] : []));
869
+ function wrap(value, fallback) {
870
+ if (value === undefined)
871
+ return fallback ? fallback : computed(() => undefined);
872
+ if (typeof value === 'function')
873
+ return isSignal(value) ? value : computed(value);
874
+ return computed(() => value);
875
+ }
876
+ function isAbsoluteCommandArray(commands) {
877
+ return (commands.length > 0 &&
878
+ typeof commands[0] === 'string' &&
879
+ commands[0].startsWith('/'));
880
+ }
881
+ function resolveLinkTree(input, router, relativeTo) {
882
+ const raw = typeof input === 'function' ? input() : input;
883
+ if (raw === undefined || raw === null)
884
+ return null;
885
+ if (raw instanceof UrlTree)
886
+ return raw;
887
+ if (typeof raw === 'string') {
888
+ if (raw.startsWith('/'))
889
+ return router.parseUrl(raw);
890
+ const parsed = router.parseUrl('/' + raw);
891
+ const primary = parsed.root.children['primary'];
892
+ const segments = primary ? primary.segments.map((s) => s.path) : [];
893
+ return createUrlTreeFromSnapshot(relativeTo, segments, parsed.queryParams, parsed.fragment);
894
+ }
895
+ if (isAbsoluteCommandArray(raw))
896
+ return router.createUrlTree(raw);
897
+ return createUrlTreeFromSnapshot(relativeTo, raw);
898
+ }
899
+ function resolveMeta(input) {
900
+ if (input === undefined)
901
+ return {};
902
+ return typeof input === 'function' ? input() : input;
903
+ }
904
+ /**
905
+ * @internal
906
+ * Recursively builds an {@link InternalNavItem} tree from {@link CreateNavItem} input.
907
+ * Cascades parent `disabled`/`hidden` to descendants and computes `active` against the
908
+ * current router URL using `Router.isActive`.
909
+ */
910
+ function createInternalNavItem(input, router, relativeTo, configActiveMatch, parentDisabled, parentHidden, fallbackId) {
911
+ const label = wrap(input.label);
912
+ const ariaLabel = input.ariaLabel ? wrap(input.ariaLabel) : label;
913
+ const linkTree = computed(() => resolveLinkTree(input.link, router, relativeTo), ...(ngDevMode ? [{ debugName: "linkTree" }] : []));
914
+ const link = computed(() => {
915
+ const tree = linkTree();
916
+ return tree ? router.serializeUrl(tree) : null;
917
+ }, ...(ngDevMode ? [{ debugName: "link" }] : []));
918
+ const ownDisabled = wrap(input.disabled, NEVER_TRUE);
919
+ const ownHidden = wrap(input.hidden, NEVER_TRUE);
920
+ const disabled = computed(() => parentDisabled() || ownDisabled(), ...(ngDevMode ? [{ debugName: "disabled" }] : []));
921
+ const hidden = computed(() => parentHidden() || ownHidden(), ...(ngDevMode ? [{ debugName: "hidden" }] : []));
922
+ const metaInput = input.meta;
923
+ const meta = computed(() => resolveMeta(metaInput), ...(ngDevMode ? [{ debugName: "meta" }] : []));
924
+ const id = input.id !== undefined
925
+ ? wrap(input.id)
926
+ : computed(() => link() ?? fallbackId);
927
+ const childItems = (input.children ?? []).map((childInput, i) => createInternalNavItem(childInput, router, relativeTo, configActiveMatch, disabled, hidden, `${fallbackId}.${i}`));
928
+ const children = computed(() => childItems.filter((c) => !c.hidden()), ...(ngDevMode ? [{ debugName: "children" }] : []));
929
+ const mergedActiveMatch = {
930
+ ...configActiveMatch,
931
+ ...input.activeMatch,
932
+ };
933
+ const trackNavigation = url(router);
934
+ const finalOptions = {
935
+ paths: 'subset',
936
+ fragment: 'ignored',
937
+ matrixParams: 'ignored',
938
+ queryParams: 'subset',
939
+ ...mergedActiveMatch,
940
+ };
941
+ const ownActive = computed(() => {
942
+ trackNavigation();
943
+ const tree = linkTree();
944
+ return tree ? router.isActive(tree, finalOptions) : false;
945
+ }, ...(ngDevMode ? [{ debugName: "ownActive" }] : []));
946
+ const orWithChildren = input.matchesWhenChildActive ?? input.activeMatch === undefined;
947
+ const active = computed(() => ownActive() ||
948
+ (orWithChildren &&
949
+ !!childItems.length &&
950
+ childItems.some((c) => c.active())), ...(ngDevMode ? [{ debugName: "active" }] : []));
951
+ return {
952
+ id,
953
+ label,
954
+ ariaLabel,
955
+ link,
956
+ active,
957
+ disabled,
958
+ hidden,
959
+ meta,
960
+ children,
961
+ };
962
+ }
963
+
964
+ /** @internal */
965
+ const DEFAULT_NAV_SCOPE = Symbol('mmstack.nav.default');
966
+ class NavStore {
967
+ map = mutable(new Map());
968
+ leafRoutes = injectLeafRoutes();
969
+ router = inject(Router);
970
+ config = injectNavConfig();
971
+ injector = inject(EnvironmentInjector);
972
+ defaultsCache = new Map();
973
+ /** @internal */
974
+ register(scope, routePath, items) {
975
+ this.map.inline((m) => {
976
+ let scopeMap = m.get(scope);
977
+ if (!scopeMap) {
978
+ scopeMap = new Map();
979
+ m.set(scope, scopeMap);
980
+ }
981
+ scopeMap.set(routePath, items);
982
+ });
983
+ }
984
+ /** @internal */
985
+ scope(name) {
986
+ return computed(() => {
987
+ const scopeMap = this.map().get(name);
988
+ if (scopeMap) {
989
+ const leaves = this.leafRoutes();
990
+ for (let i = leaves.length - 1; i >= 0; i--) {
991
+ const items = scopeMap.get(leaves[i].path);
992
+ if (items) {
993
+ return items.filter((it) => !it.hidden());
994
+ }
995
+ }
996
+ }
997
+ const defaults = this.getDefaultItems(name);
998
+ if (defaults) {
999
+ return defaults.filter((it) => !it.hidden());
1000
+ }
1001
+ return [];
1002
+ });
1003
+ }
1004
+ getDefaultItems(scope) {
1005
+ const cached = this.defaultsCache.get(scope);
1006
+ if (cached !== undefined)
1007
+ return cached;
1008
+ const built = this.buildDefaultItems(scope);
1009
+ this.defaultsCache.set(scope, built);
1010
+ return built;
1011
+ }
1012
+ buildDefaultItems(scope) {
1013
+ const defaults = this.config.defaults;
1014
+ if (!defaults)
1015
+ return null;
1016
+ let entry;
1017
+ if (Array.isArray(defaults) || typeof defaults === 'function') {
1018
+ if (scope === DEFAULT_NAV_SCOPE)
1019
+ entry = defaults;
1020
+ }
1021
+ else {
1022
+ const key = scope === DEFAULT_NAV_SCOPE ? '' : scope;
1023
+ entry = defaults[key];
1024
+ }
1025
+ if (!entry)
1026
+ return null;
1027
+ const resolved = entry;
1028
+ return untracked(() => runInInjectionContext(this.injector, () => {
1029
+ const inputs = typeof resolved === 'function' ? resolved() : resolved;
1030
+ const rootSnapshot = this.router.routerState.snapshot.root;
1031
+ const prefix = scope === DEFAULT_NAV_SCOPE
1032
+ ? '__defaults__'
1033
+ : `__defaults__:${scope}`;
1034
+ return inputs.map((input, i) => createInternalNavItem(input, this.router, rootSnapshot, this.config.activeMatch, NEVER_TRUE, NEVER_TRUE, `${prefix}#${i}`));
1035
+ }));
1036
+ }
1037
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "20.3.17", ngImport: i0, type: NavStore, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
1038
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "20.3.17", ngImport: i0, type: NavStore, providedIn: 'root' });
1039
+ }
1040
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.17", ngImport: i0, type: NavStore, decorators: [{
1041
+ type: Injectable,
1042
+ args: [{ providedIn: 'root' }]
1043
+ }] });
1044
+ /**
1045
+ * Returns a reactive list of nav items for the requested scope.
1046
+ *
1047
+ * The returned signal reflects the nearest active ancestor route that registered items
1048
+ * for `name` via `createNavItems`. If no active route has registered items for the
1049
+ * scope, falls back to `NavConfig.defaults` (when provided via `provideNavConfig`).
1050
+ * Hidden items are filtered out.
1051
+ *
1052
+ * @typeParam TMeta The shape of `NavItem.meta` for the consuming code. Untyped at the
1053
+ * registration site — this is a consumer-side assertion.
1054
+ *
1055
+ * @example
1056
+ * ```typescript
1057
+ * @Component({
1058
+ * template: `
1059
+ * @for (item of items(); track item) {
1060
+ * <a [href]="item.link()" [class.active]="item.active()">{{ item.label() }}</a>
1061
+ * }
1062
+ * `,
1063
+ * })
1064
+ * export class TopBar {
1065
+ * protected readonly items = injectNavItems();
1066
+ * }
1067
+ * ```
1068
+ */
1069
+ function injectNavItems(name) {
1070
+ const store = inject(NavStore);
1071
+ return store.scope(name ?? DEFAULT_NAV_SCOPE);
1072
+ }
1073
+
1074
+ /**
1075
+ * Registers a set of nav items for the activating route under the given scope.
1076
+ * Mirrors `createBreadcrumb` / `createTitle` — designed to be used in a route's
1077
+ * `resolve` map.
1078
+ *
1079
+ * Multiple scopes can be registered on a single route by giving each its own `name`
1080
+ * (and a unique key in the `resolve` map):
1081
+ *
1082
+ * ```typescript
1083
+ * resolve: {
1084
+ * mainNav: createNavItems([...], { name: 'main' }),
1085
+ * sideNav: createNavItems([...], { name: 'side' }),
1086
+ * }
1087
+ * ```
1088
+ *
1089
+ * Scope override semantics: when multiple routes in the active chain register items
1090
+ * under the same scope, the deepest active registration wins. Navigating away restores
1091
+ * the shallower registration.
1092
+ */
1093
+ function createNavItems(itemsOrFactory, options) {
1094
+ const factory = typeof itemsOrFactory === 'function'
1095
+ ? itemsOrFactory
1096
+ : () => itemsOrFactory;
1097
+ return async (route) => {
1098
+ const router = inject(Router);
1099
+ const store = inject(NavStore);
1100
+ const resolveRoutePath = injectSnapshotPathResolver();
1101
+ const config = injectNavConfig();
1102
+ const routePath = resolveRoutePath(route);
1103
+ const scope = options?.name ?? DEFAULT_NAV_SCOPE;
1104
+ const items = factory().map((input, i) => createInternalNavItem(input, router, route, config.activeMatch, NEVER_TRUE, NEVER_TRUE, `${routePath}#${i}`));
1105
+ store.register(scope, routePath, items);
1106
+ return Promise.resolve();
1107
+ };
1108
+ }
1109
+
796
1110
  /**
797
1111
  * Creates a WritableSignal that synchronizes with a specific URL query parameter,
798
1112
  * enabling two-way binding between the signal's state and the URL.
@@ -902,7 +1216,7 @@ function queryParam(key, route = inject(ActivatedRoute)) {
902
1216
  return toWritable(queryParam, set);
903
1217
  }
904
1218
 
905
- const token = new InjectionToken('MMSTACK_TITLE_CONFIG');
1219
+ const token = new InjectionToken('@mmstack/router-core:title-config');
906
1220
  /**
907
1221
  * used to provide the title configuration, will not be applied unless a `createTitle` resolver is used
908
1222
  */
@@ -914,6 +1228,7 @@ function provideTitleConfig(config) {
914
1228
  return {
915
1229
  provide: token,
916
1230
  useValue: {
1231
+ initialTitle: config?.initialTitle ?? '',
917
1232
  parser: prefixFn,
918
1233
  keepLastKnown: config?.keepLastKnownTitle ?? true,
919
1234
  },
@@ -926,25 +1241,28 @@ function injectTitleConfig() {
926
1241
  return (inject(token, {
927
1242
  optional: true,
928
1243
  }) ?? {
1244
+ initialTitle: '',
929
1245
  parser: identity,
930
1246
  keepLastKnown: true,
931
1247
  });
932
1248
  }
933
1249
 
934
1250
  class TitleStore {
935
- title = inject(Title);
936
1251
  map = mutable(new Map());
937
- leafRoutes = injectLeafRoutes();
938
1252
  constructor() {
939
- const reverseLeaves = computed(() => this.leafRoutes().toReversed(), ...(ngDevMode ? [{ debugName: "reverseLeaves" }] : []));
1253
+ const { keepLastKnown, initialTitle } = injectTitleConfig();
1254
+ const leafRoutes = injectLeafRoutes();
1255
+ const title = inject(Title);
1256
+ const fallbackTitle = initialTitle || untracked(() => title.getTitle());
1257
+ const reverseLeaves = computed(() => leafRoutes().toReversed(), ...(ngDevMode ? [{ debugName: "reverseLeaves" }] : []));
940
1258
  const currentResolvedTitles = computed(() => {
941
1259
  const map = this.map();
942
1260
  return reverseLeaves()
943
- .map((leaf) => map.get(leaf.path)?.() ?? leaf.route.title)
944
- .filter((v) => !!v);
1261
+ .map((leaf) => map.get(leaf.path)?.() ?? leaf.route.title ?? null)
1262
+ .filter((v) => v !== null);
945
1263
  }, ...(ngDevMode ? [{ debugName: "currentResolvedTitles" }] : []));
946
1264
  const currentTitle = computed(() => currentResolvedTitles().at(0) ?? '', ...(ngDevMode ? [{ debugName: "currentTitle" }] : []));
947
- const heldTitle = injectTitleConfig().keepLastKnown
1265
+ const heldTitle = keepLastKnown
948
1266
  ? linkedSignal({
949
1267
  source: () => currentTitle(),
950
1268
  computation: (value, prev) => {
@@ -955,7 +1273,7 @@ class TitleStore {
955
1273
  })
956
1274
  : currentTitle;
957
1275
  effect(() => {
958
- this.title.setTitle(heldTitle());
1276
+ title.setTitle(heldTitle() || fallbackTitle);
959
1277
  });
960
1278
  }
961
1279
  register(id, titleFn) {
@@ -974,19 +1292,20 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "20.3.17", ngImpo
974
1292
  *
975
1293
  * Creates a title resolver function that can be used in Angular's router.
976
1294
  *
977
- * @param fn
978
- * A function that returns a string or a Signal<string> representing the title.
1295
+ * @param factoryOrValue
1296
+ * A function that returns a string or a Signal<string> representing the title or just the string directly.
979
1297
  * @param awaitValue
980
1298
  * If `true`, the resolver will wait until the title signal has a value before resolving.
981
1299
  * Defaults to `false`.
982
1300
  */
983
- function createTitle(fn, awaitValue = false) {
1301
+ function createTitle(factoryOrValue, awaitValue = false) {
1302
+ const factory = typeof factoryOrValue === 'string' ? () => factoryOrValue : factoryOrValue;
984
1303
  return async (route) => {
985
1304
  const store = inject(TitleStore);
986
1305
  const resolver = injectSnapshotPathResolver();
987
1306
  const fp = resolver(route);
988
1307
  const { parser } = injectTitleConfig();
989
- const resolved = fn();
1308
+ const resolved = factory();
990
1309
  const titleSignal = typeof resolved === 'string'
991
1310
  ? computed(() => resolved)
992
1311
  : computed(resolved);
@@ -1002,5 +1321,5 @@ function createTitle(fn, awaitValue = false) {
1002
1321
  * Generated bundle index. Do not edit.
1003
1322
  */
1004
1323
 
1005
- export { Link, PreloadStrategy, createBreadcrumb, createTitle, injectBreadcrumbs, injectTriggerPreload, provideBreadcrumbConfig, provideMMLinkDefaultConfig, provideTitleConfig, queryParam, url };
1324
+ export { Link, PreloadStrategy, createBreadcrumb, createNavItems, createTitle, injectBreadcrumbs, injectNavItems, injectTriggerPreload, provideBreadcrumbConfig, provideMMLinkDefaultConfig, provideNavConfig, provideTitleConfig, queryParam, url };
1006
1325
  //# sourceMappingURL=mmstack-router-core.mjs.map