@jskit-ai/shell-web 0.2.55 → 0.2.57

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.
@@ -0,0 +1,117 @@
1
+ import { nextTick, onBeforeUnmount, onMounted, watch } from "vue";
2
+ import { PAGE_TITLE_ID } from "../navigation/shellNavigationRuntime.js";
3
+ import { ICON_BUTTON_WIDTH, contentWidth, wholeTitleWidth, widthInRow } from "../support/appBarWidths.js";
4
+ import { resolveFoldedPageActions } from "../support/pageActions.js";
5
+
6
+ /**
7
+ * The width a top app bar's row leaves its page actions and overflow button beside the whole title: the row's width
8
+ * less each of its other items, where an item that grows (the title's box, a spacer) needs only the whole title, or
9
+ * nothing when it is empty.
10
+ * @param {HTMLElement} row
11
+ * @param {HTMLElement} target The actions' box.
12
+ * @param {Element | null} menuButton
13
+ */
14
+ function actionsRoom(row, target, menuButton) {
15
+ const title = document.getElementById(PAGE_TITLE_ID);
16
+ let room = contentWidth(row);
17
+ for (const child of row.children) {
18
+ if (child === target || (menuButton && child.contains(menuButton))) {
19
+ continue;
20
+ }
21
+ room -= widthInRow(child);
22
+ if (Number.parseFloat(window.getComputedStyle(child).flexGrow) > 0) {
23
+ if (title && child.contains(title)) {
24
+ room += contentWidth(child) - wholeTitleWidth(title);
25
+ } else if (child.childElementCount === 0 && !child.textContent.trim()) {
26
+ room += child.getBoundingClientRect().width;
27
+ }
28
+ }
29
+ }
30
+ return room;
31
+ }
32
+
33
+ /** @param {Element} element */
34
+ function widthOfChildren(element) {
35
+ return [...element.children].reduce((total, child) => total + widthInRow(child), 0);
36
+ }
37
+
38
+ /**
39
+ * Folds a medium or expanded top app bar's page actions that don't fit beside its whole title into its overflow menu,
40
+ * the last first (resolveFoldedPageActions), measured on the bar as drawn, so the overflow button and the bar's own
41
+ * items after the actions always stay on screen. It measures again when the bar's content changes (a new title, an
42
+ * action's label, a page's actions), when the bar is resized and when fonts load. A folded action keeps the width it
43
+ * had in the bar; a compact bar folds by its own rule (`enabled`).
44
+ * @param {object} options
45
+ * @param {import("vue").Ref<boolean>} options.enabled
46
+ * @param {import("../support/pageActions.js").ShellPageActionsRegistry} options.registry The bar's page actions.
47
+ * @param {import("vue").Ref<HTMLElement | null>} options.target The actions' box, an item of the bar's row.
48
+ * @param {() => boolean} options.ownMenu Whether the overflow menu holds the bar's own items now.
49
+ */
50
+ function useShellPageActionsFold({ enabled, registry, target, ownMenu }) {
51
+ const widths = new Map();
52
+ let menuButtonWidth = ICON_BUTTON_WIDTH;
53
+ let row = null;
54
+ let resizeObserver = null;
55
+ let mutationObserver = null;
56
+
57
+ function fit() {
58
+ const targetElement = target.value;
59
+ const foldable = registry.foldable.value;
60
+ if (!enabled.value || !row || !targetElement || foldable.length === 0) {
61
+ registry.fold(0);
62
+ return;
63
+ }
64
+ // What the bar draws now: an action in the bar has its button in its slot.
65
+ let inBar = 0;
66
+ for (const entry of foldable) {
67
+ if (entry.anchor?.childElementCount > 0) {
68
+ const width = widthOfChildren(entry.anchor);
69
+ widths.set(entry.id, width);
70
+ inBar += width;
71
+ }
72
+ }
73
+ for (const id of widths.keys()) {
74
+ if (!foldable.some((entry) => entry.id === id)) {
75
+ widths.delete(id);
76
+ }
77
+ }
78
+ // An action that has never been in the bar has no width yet: every action shows once to be measured.
79
+ if (foldable.some((entry) => !widths.has(entry.id))) {
80
+ registry.fold(0);
81
+ return;
82
+ }
83
+ const menuButton = row.querySelector(".shell-page-actions-overflow");
84
+ if (menuButton) {
85
+ menuButtonWidth = widthInRow(menuButton);
86
+ }
87
+ registry.fold(resolveFoldedPageActions({
88
+ room: actionsRoom(row, targetElement, menuButton),
89
+ fixed: widthOfChildren(targetElement) - inBar,
90
+ actions: foldable.map((entry) => widths.get(entry.id)),
91
+ menuButton: menuButtonWidth,
92
+ menuShown: ownMenu() || registry.menuEntries.value.some((entry) => !foldable.includes(entry))
93
+ }));
94
+ }
95
+
96
+ watch([enabled, () => registry.foldable.value.map((entry) => entry.id).join("\n")], fit, { flush: "post" });
97
+
98
+ onMounted(() => {
99
+ row = target.value.parentElement;
100
+ // The row is as wide as the bar whatever its items do, so a fit in its callback never resizes what it observes.
101
+ resizeObserver = new ResizeObserver(fit);
102
+ resizeObserver.observe(row);
103
+ // A change inside the bar (the title, an action's label, a page's actions, an action folding) can change what fits.
104
+ mutationObserver = new MutationObserver(fit);
105
+ mutationObserver.observe(row, { childList: true, subtree: true, characterData: true });
106
+ document.fonts.addEventListener("loadingdone", fit);
107
+ void nextTick().then(fit);
108
+ });
109
+
110
+ onBeforeUnmount(() => {
111
+ resizeObserver.disconnect();
112
+ mutationObserver.disconnect();
113
+ document.fonts.removeEventListener("loadingdone", fit);
114
+ });
115
+ }
116
+
117
+ export { useShellPageActionsFold };
@@ -0,0 +1,78 @@
1
+ import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";
2
+ import { pageDocument } from "../browser.js";
3
+ import { useWebPlacementRevision, useWebPlacementRuntime } from "../placement/inject.js";
4
+
5
+ // The class each part of ShellLayout carries while it settles: unseen and untouchable while it waits, then shown with
6
+ // its transitions held for one more style pass, so it neither slides nor fades into the place it already has.
7
+ const SETTLING_CLASSES = Object.freeze({
8
+ waiting: "shell-layout--waiting",
9
+ placing: "shell-layout--placing",
10
+ settled: ""
11
+ });
12
+
13
+ // Commits the page's styles and layout as they are now, so a change that follows starts from them.
14
+ function commitLayout() {
15
+ pageDocument()?.documentElement.getBoundingClientRect();
16
+ }
17
+
18
+ /**
19
+ * Whether ShellLayout shows its parts yet. Its navigation (the drawer, the rail, the navigation bar and the app bar's
20
+ * menu control) follows the placement context, and an application can load part of that after the page opens, such as
21
+ * a session's permissions, which it marks pending meanwhile (`mergeContext(value, source, { pending: true })`). Drawn as
22
+ * they arrived, the navigation would push the page aside under a person's pointer. The shell lays its parts out unseen
23
+ * until no part of the context is pending, fits its drawer (`settleNavigation`, which may wait for the page's fonts),
24
+ * and only then shows them, all at once and where they stay. It waits once, as it mounts: later changes to the context
25
+ * redraw the navigation in place. With nothing pending and no font loading it settles right after the render that
26
+ * mounts it, before the page first paints.
27
+ * @param {{ settleNavigation: () => void | Promise<void> }} options
28
+ */
29
+ function useShellSettled({ settleNavigation }) {
30
+ const placementRuntime = useWebPlacementRuntime();
31
+ const revision = useWebPlacementRevision(placementRuntime);
32
+ const mounted = ref(false);
33
+ /** @type {import("vue").Ref<"waiting" | "placing" | "settled">} */
34
+ const phase = ref("waiting");
35
+ const contextPending = computed(() => {
36
+ void revision.value;
37
+ return placementRuntime.isContextPending();
38
+ });
39
+ const settlingClass = computed(() => SETTLING_CLASSES[phase.value]);
40
+ const waiting = computed(() => phase.value === "waiting");
41
+
42
+ watch(() => mounted.value && !contextPending.value, settleWhenReady);
43
+
44
+ onMounted(() => {
45
+ mounted.value = true;
46
+ });
47
+ onBeforeUnmount(() => {
48
+ mounted.value = false;
49
+ });
50
+
51
+ function settleWhenReady(ready) {
52
+ if (ready && phase.value === "waiting") {
53
+ void settle();
54
+ }
55
+ }
56
+
57
+ async function settle() {
58
+ // The navigation the settled context draws is rendered; the drawer fits it, and the layout takes its final
59
+ // places while the parts are still unseen.
60
+ await nextTick();
61
+ await settleNavigation();
62
+ await nextTick();
63
+ commitLayout();
64
+ if (!mounted.value) {
65
+ return;
66
+ }
67
+ phase.value = "placing";
68
+ await nextTick();
69
+ commitLayout();
70
+ if (mounted.value) {
71
+ phase.value = "settled";
72
+ }
73
+ }
74
+
75
+ return { settlingClass, waiting };
76
+ }
77
+
78
+ export { useShellSettled };
@@ -1,19 +1,8 @@
1
1
  import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";
2
2
  import { PAGE_TITLE_ID } from "../navigation/shellNavigationRuntime.js";
3
+ import { ICON_BUTTON_WIDTH, contentWidth, wholeTitleWidth } from "../support/appBarWidths.js";
3
4
  import { resolveTopRightItemsInMenu } from "../support/topRightOverflow.js";
4
5
 
5
- // Material 3's icon button: the width of an item, or of the overflow button, that the bar has not drawn yet.
6
- const ICON_BUTTON_WIDTH = 48;
7
-
8
- /**
9
- * The title's whole width: its box when the text fits (ShellLayout sizes the h1 to its text), else the text it clips,
10
- * a pixel more, since scrollWidth is a whole number and a rounding must never make a clipped title fit.
11
- * @param {HTMLElement} title
12
- */
13
- function wholeTitleWidth(title) {
14
- return title.scrollWidth > title.clientWidth ? title.scrollWidth + 1 : title.getBoundingClientRect().width;
15
- }
16
-
17
6
  /**
18
7
  * How many of a compact top app bar's top-right items (from the first, the farthest from the corner) ShellLayout
19
8
  * moves into the bar's overflow menu: as few as leave the page title whole beside the rest
@@ -65,10 +54,7 @@ function useShellTopRightOverflow({ enabled, placements, pageActions, row, headl
65
54
  if (menuButton) {
66
55
  menuButtonWidth = menuButton.getBoundingClientRect().width;
67
56
  }
68
- const style = window.getComputedStyle(headlineElement);
69
- const titleRoom = headlineElement.clientWidth -
70
- Number.parseFloat(style.paddingInlineStart) -
71
- Number.parseFloat(style.paddingInlineEnd);
57
+ const titleRoom = contentWidth(headlineElement);
72
58
  measured.value = resolveTopRightItemsInMenu({
73
59
  room: titleRoom + inBar + (menuButton ? menuButtonWidth : 0),
74
60
  title: wholeTitleWidth(title),
@@ -24,6 +24,9 @@ const NO_WEB_PLACEMENT_RUNTIME = Object.freeze({
24
24
  setContext() {
25
25
  return Object.freeze({});
26
26
  },
27
+ isContextPending() {
28
+ return false;
29
+ },
27
30
  subscribe() {
28
31
  return () => {};
29
32
  },
@@ -56,6 +59,12 @@ function followWebPlacementRuntime(runtime, listener) {
56
59
  });
57
60
  }
58
61
 
62
+ /**
63
+ * The placement context, and its setters. `mergeContext(value, source, { pending: true })` says the source's part of it
64
+ * is still loading, as a session's permissions that arrive after the page opens: a ShellLayout opening meanwhile keeps
65
+ * the page unseen until the source sets its context again without `pending`, so its navigation never arrives under the
66
+ * page. Set it before the layout mounts (in the setup of the component that loads it) and end it on success or failure.
67
+ */
59
68
  function useWebPlacementContext() {
60
69
  const runtime = useWebPlacementRuntime();
61
70
  const context = shallowRef(runtime.getContext());
@@ -64,17 +73,19 @@ function useWebPlacementContext() {
64
73
  context.value = runtime.getContext();
65
74
  });
66
75
 
67
- function mergeContext(value = {}, source = "component") {
76
+ function mergeContext(value = {}, source = "component", { pending = false } = {}) {
68
77
  context.value = runtime.setContext(value, {
69
- source
78
+ source,
79
+ pending
70
80
  });
71
81
  return context.value;
72
82
  }
73
83
 
74
- function replaceContext(value = {}, source = "component") {
84
+ function replaceContext(value = {}, source = "component", { pending = false } = {}) {
75
85
  context.value = runtime.setContext(value, {
76
86
  replace: true,
77
- source
87
+ source,
88
+ pending
78
89
  });
79
90
  return context.value;
80
91
  }
@@ -306,6 +306,8 @@ function createWebPlacementRuntime({ components, contextContributors = [], logge
306
306
  let placementDefinitions = Object.freeze([]);
307
307
  let placementTopology = Object.freeze([]);
308
308
  let sharedContext = Object.freeze({});
309
+ // The sources whose context is still loading, as each last said with `setContext(..., { pending })`.
310
+ const pendingContextSources = new Set();
309
311
  let revision = 0;
310
312
 
311
313
  function notify(event = {}) {
@@ -369,8 +371,21 @@ function createWebPlacementRuntime({ components, contextContributors = [], logge
369
371
  return sharedContext;
370
372
  }
371
373
 
372
- function setContext(value = {}, { replace = false, source = "placement-context" } = {}) {
374
+ /**
375
+ * Merges `value` into the context placements read (replaces it with `replace`). `pending` says the source's context
376
+ * is still loading, as permissions a session sends after the page opens: the shell keeps a page it is opening unseen
377
+ * until no source is pending, so its navigation never arrives under the page (ShellLayout). The source's next call
378
+ * without it says its context has arrived, or that it never will; nothing else ends the wait.
379
+ * @param {Record<string, unknown>} [value]
380
+ * @param {{ replace?: boolean, source?: string, pending?: boolean }} [options]
381
+ */
382
+ function setContext(value = {}, { replace = false, source = "placement-context", pending = false } = {}) {
373
383
  const next = isRecord(value) ? { ...value } : {};
384
+ if (pending) {
385
+ pendingContextSources.add(source);
386
+ } else {
387
+ pendingContextSources.delete(source);
388
+ }
374
389
 
375
390
  let nextContext = next;
376
391
  if (!replace) {
@@ -384,6 +399,7 @@ function createWebPlacementRuntime({ components, contextContributors = [], logge
384
399
  debugLog("setContext", {
385
400
  replace,
386
401
  source,
402
+ pending,
387
403
  keys: Object.keys(sharedContext)
388
404
  });
389
405
  notify({
@@ -397,6 +413,11 @@ function createWebPlacementRuntime({ components, contextContributors = [], logge
397
413
  return revision;
398
414
  }
399
415
 
416
+ /** Whether a source of the context said it is still loading (`setContext(..., { pending: true })`). */
417
+ function isContextPending() {
418
+ return pendingContextSources.size > 0;
419
+ }
420
+
400
421
  function getPlacements({ surface = WEB_PLACEMENT_SURFACE_ANY, target = "", layoutClass = "", context = {} } = {}) {
401
422
  const normalizedTarget = normalizePlacementTarget(target, { strict: false });
402
423
  if (!normalizedTarget) {
@@ -518,6 +539,7 @@ function createWebPlacementRuntime({ components, contextContributors = [], logge
518
539
  getPlacements,
519
540
  getContext,
520
541
  setContext,
542
+ isContextPending,
521
543
  subscribe,
522
544
  getRevision
523
545
  });
@@ -0,0 +1,38 @@
1
+ // Material 3's icon button: the width of an item, or of the overflow button, that the bar has not drawn yet.
2
+ const ICON_BUTTON_WIDTH = 48;
3
+
4
+ /**
5
+ * The title's whole width: its text, or what its slot draws, to the next pixel when it fits, else the text it clips,
6
+ * a pixel more, since scrollWidth is a whole number and a rounding must never make a clipped title fit.
7
+ * @param {HTMLElement} title
8
+ */
9
+ function wholeTitleWidth(title) {
10
+ if (title.scrollWidth > title.clientWidth) {
11
+ return title.scrollWidth + 1;
12
+ }
13
+ const range = document.createRange();
14
+ range.selectNodeContents(title);
15
+ return Math.ceil(range.getBoundingClientRect().width);
16
+ }
17
+
18
+ /**
19
+ * An element's width in its row: its box and its inline margins.
20
+ * @param {Element} element
21
+ */
22
+ function widthInRow(element) {
23
+ const style = window.getComputedStyle(element);
24
+ return element.getBoundingClientRect().width +
25
+ Number.parseFloat(style.marginInlineStart) +
26
+ Number.parseFloat(style.marginInlineEnd);
27
+ }
28
+
29
+ /**
30
+ * The width inside an element's padding.
31
+ * @param {HTMLElement} element
32
+ */
33
+ function contentWidth(element) {
34
+ const style = window.getComputedStyle(element);
35
+ return element.clientWidth - Number.parseFloat(style.paddingInlineStart) - Number.parseFloat(style.paddingInlineEnd);
36
+ }
37
+
38
+ export { ICON_BUTTON_WIDTH, contentWidth, wholeTitleWidth, widthInRow };
@@ -1,9 +1,10 @@
1
- import { computed, shallowRef } from "vue";
1
+ import { computed, ref, shallowRef } from "vue";
2
2
 
3
3
  /**
4
4
  * The page actions of the top app bar that owns them (useShellAppBar()), for its overflow menu. A compact bar keeps
5
5
  * one trailing item so the title has the room: the page's primary action (a form's Save), or else the bar's own item
6
- * nearest the corner (the account avatar); every other action and item is in the overflow menu.
6
+ * nearest the corner (the account avatar); every other action and item is in the overflow menu. A wider bar keeps the
7
+ * actions that fit beside the whole title and folds the rest, the last first (ShellPageActionsTarget measures them).
7
8
  */
8
9
  const SHELL_PAGE_ACTIONS_REGISTRY_KEY = "jskit.shell-web.layout.page-actions-registry";
9
10
  // Node.DOCUMENT_POSITION_PRECEDING and DOCUMENT_POSITION_FOLLOWING, without the browser's Node.
@@ -39,6 +40,9 @@ const FOLLOWING = 4;
39
40
  * @typedef {object} ShellPageActionsRegistry
40
41
  * @property {import("vue").ComputedRef<ShellPageActionEntry[]>} menuEntries The overflow menu's actions, in bar order.
41
42
  * @property {import("vue").ComputedRef<boolean>} hasPrimary Whether the bar shows a primary action.
43
+ * @property {import("vue").ComputedRef<ShellPageActionEntry[]>} foldable The actions a bar folds when it has no room
44
+ * for them, in bar order: every one but the primary and the `overflow` ones.
45
+ * @property {(count: number) => void} fold How many foldable actions, from the last, the bar has no room for.
42
46
  * @property {(entry: ShellPageActionEntry) => { placed: () => void, release: () => void }} register
43
47
  * @property {(entry: ShellPageActionEntry) => boolean} inMenu
44
48
  */
@@ -51,6 +55,8 @@ const FOLLOWING = 4;
51
55
  const NO_SHELL_PAGE_ACTIONS_REGISTRY = {
52
56
  menuEntries: computed(() => []),
53
57
  hasPrimary: computed(() => false),
58
+ foldable: computed(() => []),
59
+ fold() {},
54
60
  register: () => ({ placed() {}, release() {} }),
55
61
  inMenu: () => false
56
62
  };
@@ -66,14 +72,24 @@ function documentOrder(left, right) {
66
72
  return position & PRECEDING ? 1 : 0;
67
73
  }
68
74
 
75
+ /** @param {ShellPageActionEntry} entry */
76
+ function isFoldable(entry) {
77
+ return !entry.state.value.primary && !entry.state.value.overflow;
78
+ }
79
+
69
80
  /**
70
- * The actions in the overflow menu, in bar order: those marked `overflow`, and on compact windows every action but
71
- * the primary one.
81
+ * The actions in the overflow menu, in bar order: those marked `overflow`, on compact windows every action but the
82
+ * primary one, and on wider ones the last `folded` of the others, which the bar has no room for.
72
83
  * @param {readonly ShellPageActionEntry[]} entries In bar order.
73
84
  * @param {boolean} compact
85
+ * @param {number} [folded]
74
86
  */
75
- function overflowEntries(entries, compact) {
76
- return entries.filter((entry) => entry.state.value.overflow || (compact && !entry.state.value.primary));
87
+ function overflowEntries(entries, compact, folded = 0) {
88
+ const foldable = entries.filter(isFoldable);
89
+ const foldedEntries = new Set(folded > 0 ? foldable.slice(-folded) : []);
90
+ return entries.filter((entry) =>
91
+ entry.state.value.overflow || (compact ? !entry.state.value.primary : foldedEntries.has(entry))
92
+ );
77
93
  }
78
94
 
79
95
  /**
@@ -84,8 +100,10 @@ function overflowEntries(entries, compact) {
84
100
  */
85
101
  function createShellPageActionsRegistry({ isCompact }) {
86
102
  const entries = shallowRef(/** @type {ShellPageActionEntry[]} */ ([]));
103
+ const folded = ref(0);
87
104
  const ordered = computed(() => [...entries.value].sort(documentOrder));
88
- const menuEntries = computed(() => overflowEntries(ordered.value, isCompact.value));
105
+ const foldable = computed(() => ordered.value.filter(isFoldable));
106
+ const menuEntries = computed(() => overflowEntries(ordered.value, isCompact.value, folded.value));
89
107
  const hasPrimary = computed(() =>
90
108
  ordered.value.some((entry) => entry.state.value.primary && !entry.state.value.overflow)
91
109
  );
@@ -111,17 +129,49 @@ function createShellPageActionsRegistry({ isCompact }) {
111
129
  return menuEntries.value.includes(entry);
112
130
  }
113
131
 
132
+ /** @param {number} count */
133
+ function fold(count) {
134
+ folded.value = count;
135
+ }
136
+
114
137
  return {
115
138
  menuEntries,
116
139
  hasPrimary,
140
+ foldable,
141
+ fold,
117
142
  register,
118
143
  inMenu
119
144
  };
120
145
  }
121
146
 
147
+ /**
148
+ * How many of a medium or expanded top app bar's foldable page actions (in bar order) go into its overflow menu: the
149
+ * fewest, the last first, that leave the rest, the bar's other actions and the overflow button within the room the
150
+ * whole title leaves them; all of them when even that is too wide, and the title is clipped beside what stays.
151
+ * @param {object} options
152
+ * @param {number} options.room The width the actions and the overflow button share beside the whole title.
153
+ * @param {number} options.fixed The width of the actions that stay in the bar whatever room is left (the primary).
154
+ * @param {readonly number[]} options.actions Each foldable action's width with its margins, in bar order.
155
+ * @param {number} options.menuButton The overflow button's width.
156
+ * @param {boolean} options.menuShown Whether the bar shows the overflow button anyway, for the menu's own actions or
157
+ * the bar's own items.
158
+ * @returns {number} How many actions, from the last, are in the menu.
159
+ */
160
+ function resolveFoldedPageActions({ room, fixed, actions, menuButton, menuShown }) {
161
+ let inBar = actions.reduce((total, width) => total + width, fixed);
162
+ for (let folded = 0; folded < actions.length; folded += 1) {
163
+ if (inBar + (menuShown || folded > 0 ? menuButton : 0) <= room) {
164
+ return folded;
165
+ }
166
+ inBar -= actions[actions.length - 1 - folded];
167
+ }
168
+ return actions.length;
169
+ }
170
+
122
171
  export {
123
172
  NO_SHELL_PAGE_ACTIONS_REGISTRY,
124
173
  SHELL_PAGE_ACTIONS_REGISTRY_KEY,
125
174
  createShellPageActionsRegistry,
126
- overflowEntries
175
+ overflowEntries,
176
+ resolveFoldedPageActions
127
177
  };