autosolutions-os 0.2.3 → 0.2.4

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,101 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.4 - 2026-10-14
4
+
5
+ Released with `autosolutions-design-system` 6.4.0: the workspace frame in the
6
+ final design, with 6.3.5's fixes (wide pages scroll sideways again, a phone's
7
+ menu closes on every pick, no search box without a search) and the fixes of
8
+ the full review. The design-system peer range is now `>=6.4.0 <7`: the frame
9
+ passes the bar 6.4.0's `companyPending`, which an older design system would
10
+ put on the bar's element, and it relies on 6.4.0 for links on tabs, refused
11
+ navigations and the rest below.
12
+
13
+ - **A company switch to a company that does not hold this app goes to the
14
+ Hub again.** When `switch_company_for_app` answers with no `appUrl` (the
15
+ new company does not have the app), `useCompanySwitch`, and so
16
+ `OsCompanySwitcher` and `OsWorkspaceFrame`'s plate with `companySwitch`
17
+ `"os"`, reloaded the page in place, where the app showed its "not
18
+ entitled" state. It now goes to the Hub (`HUB_URL`) in the same tab, as
19
+ the apps' own company switchers did before they took this package, and as
20
+ this package's own doc comments already said. The Hub still reloads in
21
+ place, and a returned `appUrl` still reloads when it is this origin and
22
+ navigates otherwise. The decision is `companySwitchLanding` in
23
+ `src/url.ts` (internal), tested in `test/switch.test.ts`.
24
+ - **This app's own rows and tabs are links.** The frame's tabs and this
25
+ app's own rows were buttons, so a Cmd, Ctrl, Shift or middle click did
26
+ nothing useful and there was no link to copy, where the apps' own menus
27
+ were links. They now carry their path as `href` (`hrefFor`, default the
28
+ path itself): a plain click still goes through `onNavigate`, the rest is
29
+ the browser's. A hash router passes `hrefFor={(path) => "#" + path}`; an
30
+ app whose places never reach the address bar (Label Maker's views)
31
+ passes `hrefFor={null}` and keeps buttons.
32
+ - **A navigation the app does not make leaves the frame where the URL is.**
33
+ The frame shows a click at once; when the app's router then refused the
34
+ navigation (an unsaved-changes prompt the person stays on), the frame
35
+ stayed on what was clicked. When `onNavigate` returns a promise (TanStack
36
+ Router's `navigate`), the frame now waits for it and, if the address bar
37
+ did not move, goes back to where the URL is.
38
+ - **os_context() is the signed-in person's, and a failure is asked again.**
39
+ The cached answer was the page's, whoever was signed in: another person
40
+ signing in on the same browser without a reload (in this tab or another)
41
+ saw the last person's company and companies. It is now keyed on the person
42
+ in the stored session, dropped when another person's session arrives from
43
+ another tab, and followed through the app's auth client when the frame is
44
+ given one (`auth`, or `watchOsAuth(auth)`). A failed read was never asked
45
+ again in a mounted frame: the plate, the company switch and every link to
46
+ another app stayed missing until a reload. It is asked again 1, 3, 10, 30
47
+ and 60 seconds on, when the window comes back (focus, online, visible),
48
+ and when the app's location changes (`retryOsContext`); every mounted
49
+ reader gets the answer. `useOsContextState` says whether the answer is
50
+ still being read, read, or failed.
51
+ - **Until the catalogue answers, no tool claims it is not linked.** Other
52
+ apps' Live tools read "Live, not linked from the Hub yet" while
53
+ os_context() was pending or failing. `catalogueLinks(null)` now marks them
54
+ `HINTS.checking` ("Checking your access…").
55
+ - **An in-place switch moves the plate at once.** With `companySwitch` as a
56
+ function, the plate stayed on the old company when the read after the
57
+ switch failed, and a pick of that old company was then ignored, though the
58
+ session acted as the new one. The chosen company is now the acting one on
59
+ the plate, the menu's check and the links as soon as the switch resolves,
60
+ until the core is read again (asked up to three times).
61
+ - **The plate's place is kept while the company is read**
62
+ (`companyPending`), so an app's own bar controls do not jump when it
63
+ arrives; a company's name on the plate has the whole name as its tooltip;
64
+ and in the company menu a mark that does not load keeps its slot, so the
65
+ names stay lined up.
66
+ - **Where a location is.** A tool's tab now claims a location before the
67
+ tool's own row (Key Accounts: the list at `/` and a draft under Requests
68
+ are one place, so a menu the person closed stays closed between them); a
69
+ tab at `/` claims `/` only, not every page of the app (a member without
70
+ Trends on /trends is on no tab, not on the Dashboard); and paths compare
71
+ without regard to case, as the apps' routers serve them (/ops/Boards is the
72
+ Boards page).
73
+ - **`search` and `initialOpen`, as 6.4.0 draws them.** The bar draws a search
74
+ box only when `search.onChange` is given (a placeholder alone draws none).
75
+ A phone's screen needs no `initialOpen={false}`: at 767px and below the
76
+ menu is closed on every location and after every row or tab picked, once
77
+ the page is live; a server-rendered page shows it open until it hydrates.
78
+ The README's look-only frame example now passes a search handler.
79
+
80
+ ### Upgrading
81
+
82
+ - Take 0.2.4 and `autosolutions-design-system` 6.4.0 together, in one
83
+ commit: bump both in `package.json` and the lockfile. Nothing else is
84
+ required.
85
+ - An app whose router reads hashes passes `hrefFor={(path) => "#" + path}`;
86
+ one whose places are not addresses passes `hrefFor={null}`.
87
+ - An app whose navigations can be refused returns its router's promise from
88
+ `onNavigate` (TanStack Router: `onNavigate={(href) => navigate({ to: href })}`).
89
+ - An app that passes `auth={supabase.auth}` gets sign-in changes followed
90
+ live; others are covered through the stored session.
91
+ - An app whose top bar should keep a search box passes `search.onChange`.
92
+ One that passes no handler (or only a placeholder) loses the box, which
93
+ did nothing.
94
+ - `initialOpen={false}` passed for a narrow screen can go; kept, it does no
95
+ harm. Rows marked `menu: false` only so that a pick closes the menu on a
96
+ narrow screen (the Hub's) can drop that flag there: see the design
97
+ system's 6.4.0 notes.
98
+
3
99
  ## 0.2.3 - 2026-10-01
4
100
 
5
101
  With `autosolutions-design-system` 6.3.4, whose frame fixes this release
package/README.md CHANGED
@@ -35,10 +35,16 @@ export function App() {
35
35
  the top bar with the company's mark and switcher, the rail, the OS menu (the 53
36
36
  tools of the menu map: the handoff's 49 plus Shelf simulator, Key accounts, PM
37
37
  Copilot and Candidate hub), the footer with Admin for people who manage something, and the
38
- browser-tab icon. It needs `autosolutions-design-system` 6.3.4 or later
39
- (an optional peer: only this entry point uses it). Take this package's 0.2.3
40
- and the design system's 6.3.4 together, in one commit. An app that renders
41
- `OsWorkspaceFrame` changes nothing else. Code that calls `osFrame().targetFor`
38
+ browser-tab icon. It needs `autosolutions-design-system` 6.4.0 or later
39
+ (an optional peer: only this entry point uses it). Take this package's 0.2.4
40
+ and the design system's 6.4.0 together, in one commit: 0.2.4 sends a company
41
+ switch the app's new company does not hold to the Hub, reads os_context()
42
+ for the person signed in and asks again after a failure, and makes this
43
+ app's own rows and tabs links; 6.4.0 brings the final design and the frame's
44
+ own fixes (wide pages scroll sideways again, a phone's menu closes on every
45
+ pick, no search box without a search, and the rest in its CHANGELOG). An
46
+ app that renders `OsWorkspaceFrame` changes nothing else, but for the
47
+ options below (`hrefFor`, a navigation promise, `auth`). Code that calls `osFrame().targetFor`
42
48
  itself in the Hub (a test of the Hub's rows, say) and means Back to hub passes
43
49
  `back: true`: since 0.2.3 the hub function with no row and no flag is the
44
50
  rail's Hub (see below). The Hub's adoption of 0.2.3 updates its one test that
@@ -67,8 +73,14 @@ import { OsWorkspaceFrame } from "autosolutions-os/frame";
67
73
 
68
74
  It works with any router: it reads `location` and calls `onNavigate(href)` for
69
75
  paths inside the app, and opens other apps itself, in the same tab. The rows
70
- for other apps are links (`<a href>` with `?tenant=`), so a middle-click, a
71
- Cmd or Ctrl click and Copy link work as the browser does them. Browser Back
76
+ for other apps are links (`<a href>` with `?tenant=`), and so are this app's
77
+ own rows and tabs (`href` is the path; `hrefFor` writes it another way, as
78
+ `(path) => "#" + path` for a hash router, or `null` keeps buttons for an app
79
+ whose places never reach the address bar), so a middle-click, a Cmd or Ctrl
80
+ click and Copy link work as the browser does them. Return the router's
81
+ navigation promise from `onNavigate` (as above) and a navigation the app
82
+ refuses (an unsaved-changes prompt the person stays on, which leaves the
83
+ address bar where it was) puts the frame back where the URL is. Browser Back
72
84
  moves the menus because the frame follows `location`, and it calls
73
85
  `onNavigate` only when someone clicks, so there is no loop. Back from another
74
86
  app out of the browser's back/forward cache puts the frame where the URL is,
@@ -106,32 +118,49 @@ why).
106
118
  (`staticLinks()`). Tools with no app follow the map: Pricing researcher and
107
119
  Brand voice copywriter read "Live, not linked from the Hub yet", anything
108
120
  not Live shows its status.
121
+ - os_context() is read once per page and person: another person signing in
122
+ on the same browser, without a reload, reads their own (pass `auth`, the
123
+ app's `supabase.auth`, to have sign-ins followed live in this tab too). A
124
+ read that fails is asked again (1, 3, 10, 30 and 60 seconds on, when the
125
+ window comes back, and when the location changes), and until it answers
126
+ other apps' tools read "Checking your access…" and the plate's place is
127
+ kept, drawn as nothing.
109
128
  - The company plate is `markFor(tenant, "plain")`. A company with no artwork
110
129
  there (one outside the brand bucket's eight, with no stored logo), or whose
111
- artwork fails to load, has its name on the plate instead, and its row in
112
- the company menu drops the broken mark. The chevron appears only for
130
+ artwork fails to load, has its name on the plate instead (its whole name
131
+ in a tooltip), and its row in the company menu keeps the mark's slot,
132
+ empty. The chevron appears only for
113
133
  someone with more than one company, and then the plate and the chevron are
114
134
  one button that opens the company menu: a menu of the companies, the acting
115
135
  one checked, with arrow keys, and focus back on the button when it closes.
116
136
  `companySwitch` says what it does:
117
137
  - `"os"` (the default) switches exactly as `OsCompanySwitcher` does, since
118
138
  both use `useCompanySwitch(os, appKey)`: `switch_company_for_app`, then a
119
- reload or that company's deployment of this app.
139
+ reload or that company's deployment of this app, or the Hub when that
140
+ company does not hold the app (the core returns no `appUrl`).
120
141
  - `"none"` shows the acting company with no chevron, for an app whose
121
142
  company is fixed some other way (PM Copilot's assignment).
122
143
  - a function `(tenant) => Promise<void>` is the app's own in-place switch
123
144
  (e-sales: `switch_tenant`, invalidate, toast). The frame calls it, closes
124
- the menu and does not reload; when it resolves, `refreshOsContext(os)`
125
- brings the plate and the menu's links round to the new company. The
126
- function reports its own failures.
145
+ the menu and does not reload; when it resolves, the plate, the menu's
146
+ check and its links follow the new company at once, and
147
+ `refreshOsContext(os)` reads the core again (asking again if that fails).
148
+ The function reports its own failures.
127
149
  - `actions` go in the top bar before the plate (What's new, a notification
128
150
  bell). `panelFooter` renders in the panel under the open tool's tabs, in the
129
151
  panel's padding, scrolling with them (Create Studio's sessions).
130
152
  - Settings goes to `settingsPath` when the app has a settings page, and to the
131
153
  Hub's settings when it has none.
132
- - `initialOpen={false}` starts the menu closed on the first location (a narrow
133
- screen); after that the frame's own rule applies. `data-*` and `aria-*` props
134
- land on the frame's root.
154
+ - `search` is the top bar's field. It is drawn only when `search.onChange`
155
+ is given: an app with no search passes none and the bar has no box (a
156
+ placeholder alone draws none either).
157
+ - On a phone's screen (767px and below) the design system closes the menu on
158
+ every location and on every row or tab picked, so the page picked gets the
159
+ width, once the page is live (a server-rendered page shows it open until it
160
+ hydrates); a reselect still goes back to its own page. No prop is needed
161
+ for it. `initialOpen={false}` starts the menu closed on the first location,
162
+ which a phone no longer needs it for; after that the frame's own rule
163
+ applies. `data-*` and `aria-*` props land on the frame's root.
135
164
  - Admin appears when `my_admin_scope()` says the person manages something; pass
136
165
  `admin` to decide it yourself.
137
166
  - The Hub passes `hubItems`, its own rows. In any other app the rail's Hub, Back
@@ -165,7 +194,7 @@ const frame = osFrame({ appKey: "ops_hub", tools, links: staticLinks() });
165
194
  const here = pathname + search;
166
195
 
167
196
  <WorkspaceFrame
168
- topBar={<TopBar searchPlaceholder="Search" companySrc={companyMarkUrl("frankbody", "plain")} />}
197
+ topBar={<TopBar searchPlaceholder="Search" searchValue={query} onSearchChange={setQuery} companySrc={companyMarkUrl("frankbody", "plain")} />}
169
198
  functions={frame.functions}
170
199
  sections={frame.sections}
171
200
  footerItems={frame.footerItems}
package/dist/chrome.d.ts CHANGED
@@ -26,9 +26,12 @@ export declare function OsAppSwitcher({ os, appKey, variant, onOpen }: {
26
26
  *
27
27
  * `choose` runs `close` synchronously, and does nothing else, when there is
28
28
  * nothing to do: the company is already current or a switch is in flight.
29
+ * `status` says whether the context is still being read, read, or failed
30
+ * (and is being asked again).
29
31
  */
30
32
  export declare function useCompanySwitch(os: unknown, appKey: string): {
31
- context: import("./context.js").OsContext | null;
33
+ context: import("./contextCache.js").OsContext | null;
34
+ status: import("./contextCache.js").OsContextStatus;
32
35
  current: OsTenant | null;
33
36
  tenants: OsTenant[];
34
37
  busy: boolean;
package/dist/chrome.js CHANGED
@@ -12,7 +12,8 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
12
12
  */
13
13
  import { useEffect, useRef, useState } from "react";
14
14
  import { HUB_URL } from "./config.js";
15
- import { groupApps, invalidateOsContext, labelFor, markFor, useOsContext, withTenantHint, } from "./context.js";
15
+ import { companySwitchLanding } from "./url.js";
16
+ import { groupApps, invalidateOsContext, labelFor, markFor, useOsContext, useOsContextState, withTenantHint, } from "./context.js";
16
17
  function useDismiss(open, close, ref) {
17
18
  useEffect(() => {
18
19
  if (!open)
@@ -69,9 +70,11 @@ export function OsAppSwitcher({ os, appKey, variant = "menu", onOpen }) {
69
70
  *
70
71
  * `choose` runs `close` synchronously, and does nothing else, when there is
71
72
  * nothing to do: the company is already current or a switch is in flight.
73
+ * `status` says whether the context is still being read, read, or failed
74
+ * (and is being asked again).
72
75
  */
73
76
  export function useCompanySwitch(os, appKey) {
74
- const context = useOsContext(os);
77
+ const { context, status } = useOsContextState(os);
75
78
  const [busy, setBusy] = useState(false);
76
79
  const [error, setError] = useState(null);
77
80
  const current = context?.tenant ?? null;
@@ -97,24 +100,15 @@ export function useCompanySwitch(os, appKey) {
97
100
  }
98
101
  invalidateOsContext();
99
102
  const result = (data ?? {});
100
- if (appKey === "hub" || !result.appUrl) {
103
+ const destination = companySwitchLanding(appKey, result, window.location.origin);
104
+ if (destination === null)
101
105
  window.location.reload();
102
- return;
103
- }
104
- const destination = withTenantHint(result.appUrl, result.tenantSlug ?? null);
105
- try {
106
- if (new URL(destination).origin === window.location.origin) {
107
- window.location.reload();
108
- return;
109
- }
110
- }
111
- catch {
112
- /* malformed destination: fall through and let the browser report it */
113
- }
114
- window.location.assign(destination);
106
+ else
107
+ window.location.assign(destination);
115
108
  };
116
109
  return {
117
110
  context,
111
+ status,
118
112
  current,
119
113
  tenants: context?.tenants ?? [],
120
114
  busy,
package/dist/context.d.ts CHANGED
@@ -1,37 +1,10 @@
1
- export type OsTenant = {
2
- id: string;
3
- slug: string;
4
- name: string;
5
- logoUrl: string | null;
6
- logoPlainUrl: string | null;
7
- osRole?: string;
1
+ import { type OsApp, type OsContext, type OsContextStatus, type OsTenant } from "./contextCache.js";
2
+ export { loadOsContext, invalidateOsContext, refreshOsContext, retryOsContext, watchOsAuth, type OsApp, type OsContext, type OsContextStatus, type OsTenant, } from "./contextCache.js";
3
+ /** The context and where it stands, for a component that shows the difference. */
4
+ export declare function useOsContextState(os: unknown): {
5
+ context: OsContext | null;
6
+ status: OsContextStatus;
8
7
  };
9
- export type OsApp = {
10
- key: string;
11
- name: string;
12
- iconUrl: string | null;
13
- url: string | null;
14
- sortOrder: number;
15
- /** Switcher column, e.g. Marketing. Comes from the catalogue, not from code. */
16
- groupKey: string | null;
17
- /** Sub-heading inside the column; null means the untitled first block. */
18
- sectionKey: string | null;
19
- designKey: string | null;
20
- labelUrl: string | null;
21
- };
22
- export type OsContext = {
23
- tenant: OsTenant | null;
24
- tenants: OsTenant[];
25
- apps: OsApp[];
26
- };
27
- export declare function loadOsContext(os: unknown): Promise<OsContext | null>;
28
- /** Forget the cached answer, so the next read reflects a company switch. */
29
- export declare function invalidateOsContext(): void;
30
- /**
31
- * Ask again and hand the answer to every mounted reader: after a company
32
- * switch that does not reload the page. A failed call changes nothing.
33
- */
34
- export declare function refreshOsContext(os: unknown): Promise<OsContext | null>;
35
8
  export declare function useOsContext(os: unknown): OsContext | null;
36
9
  export declare function useTenant(os: unknown): OsTenant | null;
37
10
  export declare function useApps(os: unknown): OsApp[];
package/dist/context.js CHANGED
@@ -1,68 +1,41 @@
1
1
  /**
2
2
  * `os_context()` is the one call every app's chrome makes: who you are acting
3
3
  * as, which companies you can act as, and which apps you hold. One round trip,
4
- * cached for the page.
4
+ * cached for the page and for the person signed in (contextCache.ts).
5
5
  */
6
6
  import { useEffect, useState } from "react";
7
7
  import { appLabelUrl, companyMarkUrl } from "./config.js";
8
- /**
9
- * One fetch per page, but a FAILURE is never cached. A call that races a token
10
- * refresh would otherwise blank both switchers until a full reload.
11
- */
12
- let pending = null;
13
- export function loadOsContext(os) {
14
- if (!pending) {
15
- pending = Promise.resolve(os.rpc("os_context"))
16
- .then(({ data, error }) => {
17
- if (error || !data) {
18
- pending = null;
19
- return null;
20
- }
21
- return data;
22
- })
23
- .catch(() => {
24
- pending = null;
25
- return null;
26
- });
27
- }
28
- return pending;
29
- }
30
- /** Forget the cached answer, so the next read reflects a company switch. */
31
- export function invalidateOsContext() {
32
- pending = null;
33
- }
34
- /* Every mounted useOsContext, so an in-place switch reaches them all. */
35
- const readers = new Set();
36
- /**
37
- * Ask again and hand the answer to every mounted reader: after a company
38
- * switch that does not reload the page. A failed call changes nothing.
39
- */
40
- export async function refreshOsContext(os) {
41
- pending = null;
42
- const value = await loadOsContext(os);
43
- if (value)
44
- readers.forEach((read) => read(value));
45
- return value;
46
- }
47
- export function useOsContext(os) {
48
- const [context, setContext] = useState(null);
8
+ import { loadOsContext, scheduleOsContextRetry, subscribeOsContext, } from "./contextCache.js";
9
+ export { loadOsContext, invalidateOsContext, refreshOsContext, retryOsContext, watchOsAuth, } from "./contextCache.js";
10
+ /** The context and where it stands, for a component that shows the difference. */
11
+ export function useOsContextState(os) {
12
+ const [state, setState] = useState({ context: null, status: "loading" });
49
13
  useEffect(() => {
50
14
  let live = true;
51
- const read = (value) => {
15
+ const read = (context, status) => {
52
16
  if (live)
53
- setContext(value);
17
+ setState((was) => (was.context === context && was.status === status ? was : { context, status }));
54
18
  };
55
- readers.add(read);
19
+ const unsubscribe = subscribeOsContext(read);
56
20
  void loadOsContext(os).then((value) => {
57
- if (live)
58
- setContext(value);
21
+ if (!live)
22
+ return;
23
+ if (value) {
24
+ read(value, "ready");
25
+ return;
26
+ }
27
+ read(null, "failed");
28
+ scheduleOsContextRetry(os);
59
29
  });
60
30
  return () => {
61
31
  live = false;
62
- readers.delete(read);
32
+ unsubscribe();
63
33
  };
64
34
  }, [os]);
65
- return context;
35
+ return state;
36
+ }
37
+ export function useOsContext(os) {
38
+ return useOsContextState(os).context;
66
39
  }
67
40
  export function useTenant(os) {
68
41
  return useOsContext(os)?.tenant ?? null;
@@ -0,0 +1,50 @@
1
+ export type OsTenant = {
2
+ id: string;
3
+ slug: string;
4
+ name: string;
5
+ logoUrl: string | null;
6
+ logoPlainUrl: string | null;
7
+ osRole?: string;
8
+ };
9
+ export type OsApp = {
10
+ key: string;
11
+ name: string;
12
+ iconUrl: string | null;
13
+ url: string | null;
14
+ sortOrder: number;
15
+ /** Switcher column, e.g. Marketing. Comes from the catalogue, not from code. */
16
+ groupKey: string | null;
17
+ /** Sub-heading inside the column; null means the untitled first block. */
18
+ sectionKey: string | null;
19
+ designKey: string | null;
20
+ labelUrl: string | null;
21
+ };
22
+ export type OsContext = {
23
+ tenant: OsTenant | null;
24
+ tenants: OsTenant[];
25
+ apps: OsApp[];
26
+ };
27
+ /**
28
+ * Where a reader's context stands: still being read, read, or failed (and
29
+ * being asked again).
30
+ */
31
+ export type OsContextStatus = "loading" | "ready" | "failed";
32
+ export declare function loadOsContext(os: unknown): Promise<OsContext | null>;
33
+ /** Forget the cached answer, so the next read reflects a company switch. */
34
+ export declare function invalidateOsContext(): void;
35
+ /** Hear every new answer (and a change of person) until the returned function is called. */
36
+ export declare function subscribeOsContext(read: (context: OsContext | null, status: OsContextStatus) => void): () => void;
37
+ /**
38
+ * Ask again and hand the answer to every mounted reader: after a company
39
+ * switch that does not reload the page. A failed call changes nothing.
40
+ */
41
+ export declare function refreshOsContext(os: unknown): Promise<OsContext | null>;
42
+ /** After a failed read: ask again on a timer (1, 3, 10, 30, 60 seconds). */
43
+ export declare function scheduleOsContextRetry(os: unknown): void;
44
+ /**
45
+ * Ask again now if the last read failed (the frame calls it when the app's
46
+ * location changes); otherwise the cached answer. Every mounted reader gets a
47
+ * new answer.
48
+ */
49
+ export declare function retryOsContext(os: unknown): Promise<OsContext | null>;
50
+ export declare function watchOsAuth(auth: unknown): void;
@@ -0,0 +1,224 @@
1
+ /**
2
+ * The os_context() cache, with no React: one read per page and person, a
3
+ * failure never kept and asked again, and every mounted reader told of a new
4
+ * answer. context.ts wraps it in hooks; it is apart so a test (or a worker)
5
+ * can load it without React.
6
+ */
7
+ import { coreProjectRef } from "./config.js";
8
+ /* The person the stored session belongs to: the user id in this origin's
9
+ Supabase session, or undefined when it cannot be told (no window, storage
10
+ blocked). An app that keeps its session in cookies has none here, which
11
+ reads as nobody, the same before and after: the cache then follows sign-in
12
+ changes only through `watchOsAuth`. */
13
+ function storedUser() {
14
+ if (typeof window === "undefined")
15
+ return undefined;
16
+ let raw;
17
+ try {
18
+ raw = window.localStorage.getItem(`sb-${coreProjectRef()}-auth-token`);
19
+ }
20
+ catch {
21
+ return undefined;
22
+ }
23
+ if (!raw)
24
+ return null;
25
+ try {
26
+ const session = JSON.parse(raw);
27
+ if (typeof session.user?.id === "string")
28
+ return session.user.id;
29
+ if (typeof session.access_token === "string") {
30
+ const payload = session.access_token.split(".")[1] ?? "";
31
+ const claims = JSON.parse(atob(payload.replace(/-/g, "+").replace(/_/g, "/")));
32
+ if (typeof claims.sub === "string")
33
+ return claims.sub;
34
+ }
35
+ }
36
+ catch {
37
+ /* not a session we can read */
38
+ }
39
+ return null;
40
+ }
41
+ /**
42
+ * One fetch per page and person, and a FAILURE is never cached. A call that
43
+ * races a token refresh would otherwise blank both switchers until a full
44
+ * reload. The answer is the signed-in person's: when another person signs in
45
+ * on the same browser without a reload (in this tab or another), the next
46
+ * read asks again rather than handing them the last person's companies.
47
+ */
48
+ let pending = null;
49
+ /* Whose answer `pending` is: the stored session's user when it was asked. */
50
+ let pendingFor;
51
+ /* The person `watchOsAuth` last heard about, for apps whose session is not in localStorage. */
52
+ let authUser;
53
+ let failed = false;
54
+ let lastOs = null;
55
+ const who = () => {
56
+ const stored = storedUser();
57
+ return stored ?? authUser ?? stored;
58
+ };
59
+ export function loadOsContext(os) {
60
+ lastOs = os;
61
+ watchWindow();
62
+ const person = who();
63
+ if (pending && person !== undefined && pendingFor !== undefined && person !== pendingFor)
64
+ pending = null;
65
+ if (!pending) {
66
+ pendingFor = person;
67
+ const call = Promise.resolve(os.rpc("os_context"))
68
+ .then(({ data, error }) => {
69
+ if (error || !data)
70
+ throw new Error("os_context");
71
+ if (pending === call)
72
+ failed = false;
73
+ return data;
74
+ })
75
+ .catch(() => {
76
+ if (pending === call) {
77
+ pending = null;
78
+ failed = true;
79
+ }
80
+ return null;
81
+ });
82
+ pending = call;
83
+ }
84
+ return pending;
85
+ }
86
+ /** Forget the cached answer, so the next read reflects a company switch. */
87
+ export function invalidateOsContext() {
88
+ pending = null;
89
+ failed = false;
90
+ attempt = 0;
91
+ if (timer !== null) {
92
+ clearTimeout(timer);
93
+ timer = null;
94
+ }
95
+ }
96
+ /* Every mounted reader (useOsContextState), so an in-place switch, a retry
97
+ and a change of person reach them all. */
98
+ const readers = new Set();
99
+ /** Hear every new answer (and a change of person) until the returned function is called. */
100
+ export function subscribeOsContext(read) {
101
+ readers.add(read);
102
+ return () => { readers.delete(read); };
103
+ }
104
+ const tell = (context, status) => {
105
+ readers.forEach((read) => read(context, status));
106
+ };
107
+ /**
108
+ * Ask again and hand the answer to every mounted reader: after a company
109
+ * switch that does not reload the page. A failed call changes nothing.
110
+ */
111
+ export async function refreshOsContext(os) {
112
+ pending = null;
113
+ const value = await loadOsContext(os);
114
+ if (value)
115
+ tell(value, "ready");
116
+ return value;
117
+ }
118
+ /* After a failed read, ask again: 1, 3, 10, 30 and 60 seconds on, and
119
+ whenever the window comes back (focus, online, visible again) or the app
120
+ moves (retryOsContext). */
121
+ const DELAYS = [1000, 3000, 10000, 30000, 60000];
122
+ let timer = null;
123
+ let attempt = 0;
124
+ function again(os) {
125
+ return loadOsContext(os).then((value) => {
126
+ if (value) {
127
+ attempt = 0;
128
+ if (timer !== null) {
129
+ clearTimeout(timer);
130
+ timer = null;
131
+ }
132
+ tell(value, "ready");
133
+ }
134
+ else {
135
+ scheduleOsContextRetry(os);
136
+ }
137
+ return value;
138
+ });
139
+ }
140
+ /** After a failed read: ask again on a timer (1, 3, 10, 30, 60 seconds). */
141
+ export function scheduleOsContextRetry(os) {
142
+ if (timer !== null || typeof window === "undefined" || attempt >= DELAYS.length)
143
+ return;
144
+ timer = setTimeout(() => {
145
+ timer = null;
146
+ attempt += 1;
147
+ void again(os);
148
+ }, DELAYS[attempt]);
149
+ }
150
+ /**
151
+ * Ask again now if the last read failed (the frame calls it when the app's
152
+ * location changes); otherwise the cached answer. Every mounted reader gets a
153
+ * new answer.
154
+ */
155
+ export function retryOsContext(os) {
156
+ return failed ? again(os) : loadOsContext(os);
157
+ }
158
+ /* A change of person in another tab of this origin rewrites the stored
159
+ session (a storage event here); coming back to the window after a failed
160
+ read asks again. Installed once, in the browser only. */
161
+ let watching = false;
162
+ function watchWindow() {
163
+ if (watching || typeof window === "undefined" || typeof window.addEventListener !== "function")
164
+ return;
165
+ watching = true;
166
+ const wake = () => {
167
+ if (failed && lastOs)
168
+ void again(lastOs);
169
+ };
170
+ window.addEventListener("focus", wake);
171
+ window.addEventListener("online", wake);
172
+ if (typeof document !== "undefined") {
173
+ document.addEventListener("visibilitychange", () => {
174
+ if (document.visibilityState === "visible")
175
+ wake();
176
+ });
177
+ }
178
+ window.addEventListener("storage", (event) => {
179
+ if (event.key !== null && event.key !== `sb-${coreProjectRef()}-auth-token`)
180
+ return;
181
+ personChanged(storedUser());
182
+ });
183
+ }
184
+ function personChanged(person) {
185
+ if (person === undefined || person === pendingFor)
186
+ return;
187
+ invalidateOsContext();
188
+ pendingFor = person;
189
+ if (person === null) {
190
+ tell(null, "loading");
191
+ return;
192
+ }
193
+ if (lastOs)
194
+ void again(lastOs);
195
+ }
196
+ /**
197
+ * Follow sign-ins and sign-outs through the app's Supabase auth client
198
+ * (`supabase.auth`), live, in this tab too, and for an app whose session is
199
+ * not in localStorage (one that keeps it in cookies). OsWorkspaceFrame calls
200
+ * it with its `auth`. A token refresh for the same person changes nothing.
201
+ */
202
+ const watchedAuth = new WeakSet();
203
+ export function watchOsAuth(auth) {
204
+ const client = auth;
205
+ if (!client || typeof client !== "object" || typeof client.onAuthStateChange !== "function" || watchedAuth.has(client))
206
+ return;
207
+ watchedAuth.add(client);
208
+ try {
209
+ client.onAuthStateChange((_event, session) => {
210
+ const person = session?.user?.id ?? null;
211
+ if (authUser === undefined) {
212
+ authUser = person;
213
+ return;
214
+ }
215
+ if (person === authUser)
216
+ return;
217
+ authUser = person;
218
+ personChanged(person);
219
+ });
220
+ }
221
+ catch {
222
+ /* following sign-ins is a nicety: never let it break the page */
223
+ }
224
+ }
package/dist/frame.d.ts CHANGED
@@ -10,10 +10,12 @@
10
10
  * It knows nothing about routers. Hand it the current location (pathname plus
11
11
  * query) and an `onNavigate(href)` that pushes an in-app path. Rows for other
12
12
  * apps are links, which it follows itself in the same tab (a middle-click or
13
- * a modified click opens them where the browser does). Browser Back and
14
- * Forward move the menus because the frame follows `location`, and it only
15
- * calls `onNavigate` when someone clicks. A click on the tab or row it already shows, from a page
16
- * filed under it (a draft under Requests), goes to that tab's own page.
13
+ * a modified click opens them where the browser does); this app's own rows and
14
+ * tabs are links to their paths too (`hrefFor`). Browser Back and Forward
15
+ * move the menus because the frame follows `location`, and it only calls
16
+ * `onNavigate` when someone clicks. A click on the tab or row it already
17
+ * shows, from a page filed under it (a draft under Requests), goes to that
18
+ * tab's own page.
17
19
  */
18
20
  import { type ReactNode } from "react";
19
21
  import type { WorkspaceState } from "autosolutions-design-system";
@@ -27,16 +29,24 @@ import { type OsAppTool, type OsHubSection } from "./nav.js";
27
29
  * whose company is fixed some other way (an assignment, say).
28
30
  * - a function: the app's own in-place switch. The frame calls it with the
29
31
  * chosen company, closes the menu and does not reload; when it resolves,
30
- * the plate and the menu links follow the new company. The function reports
31
- * its own failures (a toast); a rejection only leaves the plate as it was.
32
+ * the plate and the menu links follow the new company at once, and the
33
+ * frame reads the core again (asking again if that read fails). The function
34
+ * reports its own failures (a toast); a rejection only leaves the plate as
35
+ * it was.
32
36
  */
33
37
  export type OsCompanySwitch = "os" | "none" | ((tenant: OsTenant) => Promise<void>);
34
38
  export type OsWorkspaceFrameProps = {
35
39
  /** The client's `os` (public schema) connection. */
36
40
  os: unknown;
37
- /** Used for Sign out when `onSignOut` is not given: signs out, then reloads. */
41
+ /**
42
+ * The app's Supabase auth client (`supabase.auth`). Used for Sign out when
43
+ * `onSignOut` is not given (signs out, then reloads), and followed for
44
+ * sign-ins and sign-outs, so a person who signs in after another, without a
45
+ * reload, sees their own companies.
46
+ */
38
47
  auth?: {
39
48
  signOut: () => Promise<unknown>;
49
+ onAuthStateChange?: (...args: never[]) => unknown;
40
50
  };
41
51
  /** This app's catalogue key; "hub" for the Hub. */
42
52
  appKey: string;
@@ -46,8 +56,28 @@ export type OsWorkspaceFrameProps = {
46
56
  hubItems?: OsHubSection[];
47
57
  /** Where the app is: pathname plus query. */
48
58
  location: string;
49
- /** Push an in-app path. Links to other apps are opened by the frame. */
50
- onNavigate: (href: string) => void;
59
+ /**
60
+ * Push an in-app path. Links to other apps are opened by the frame. Return
61
+ * the router's navigation promise (TanStack Router's `navigate`) and a
62
+ * navigation the app does not make after all (an unsaved-changes prompt
63
+ * the person stays on, which leaves the address bar where it was) puts the
64
+ * frame back where the URL is.
65
+ */
66
+ onNavigate: (href: string) => void | PromiseLike<unknown>;
67
+ /**
68
+ * How this app's own paths are written as links, so its rows and tabs are
69
+ * real links (a middle-click, a modified click and Copy link work, as on
70
+ * the apps' own menus before the frame); a plain click still goes through
71
+ * `onNavigate`. Default: the path as it is, for a router that reads the
72
+ * address bar's path. A hash router passes `(path) => "#" + path`; an app
73
+ * whose places are not addresses at all (state, not routes) passes `null`,
74
+ * and its rows and tabs stay buttons.
75
+ */
76
+ hrefFor?: ((path: string) => string | null) | null;
77
+ /**
78
+ * The top bar's search field. With the design system 6.4.0 it is drawn only
79
+ * when `onChange` is given: without one the bar has no search box.
80
+ */
51
81
  search?: {
52
82
  placeholder?: string;
53
83
  value?: string;
@@ -70,9 +100,13 @@ export type OsWorkspaceFrameProps = {
70
100
  /** Set the browser-tab icon from the current menu glyph. Default true. */
71
101
  favicon?: boolean;
72
102
  /**
73
- * Whether the menu starts open, for the first location only (false on a
74
- * narrow screen, say). After that the frame's own rule applies: open on a
75
- * function with a menu. Default: that rule from the start.
103
+ * Whether the menu starts open, for the first location only. After that the
104
+ * frame's own rule applies: open on a function with a menu. Default: that
105
+ * rule from the start. A phone's screen needs none: with the design system
106
+ * 6.4.0 the menu is closed there on every location and after every pick,
107
+ * once the page is live. A page rendered on the server shows it open on a
108
+ * phone until it hydrates (the server cannot know the screen), and
109
+ * `initialOpen={true}` keeps it open there on purpose.
76
110
  */
77
111
  initialOpen?: boolean;
78
112
  className?: string;
@@ -82,4 +116,4 @@ export type OsWorkspaceFrameProps = {
82
116
  } & {
83
117
  [key: `aria-${string}`]: string | number | boolean | undefined;
84
118
  };
85
- export declare function OsWorkspaceFrame({ os, auth, appKey, tools, hubItems, location, onNavigate, search, actions, companySwitch, panelFooter, onSignOut, settingsPath, homePath, admin, favicon, initialOpen, className, children, ...rest }: OsWorkspaceFrameProps): import("react").JSX.Element;
119
+ export declare function OsWorkspaceFrame({ os, auth, appKey, tools, hubItems, location, onNavigate, hrefFor, search, actions, companySwitch, panelFooter, onSignOut, settingsPath, homePath, admin, favicon, initialOpen, className, children, ...rest }: OsWorkspaceFrameProps): import("react").JSX.Element;
package/dist/frame.js CHANGED
@@ -11,58 +11,107 @@ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-run
11
11
  * It knows nothing about routers. Hand it the current location (pathname plus
12
12
  * query) and an `onNavigate(href)` that pushes an in-app path. Rows for other
13
13
  * apps are links, which it follows itself in the same tab (a middle-click or
14
- * a modified click opens them where the browser does). Browser Back and
15
- * Forward move the menus because the frame follows `location`, and it only
16
- * calls `onNavigate` when someone clicks. A click on the tab or row it already shows, from a page
17
- * filed under it (a draft under Requests), goes to that tab's own page.
14
+ * a modified click opens them where the browser does); this app's own rows and
15
+ * tabs are links to their paths too (`hrefFor`). Browser Back and Forward
16
+ * move the menus because the frame follows `location`, and it only calls
17
+ * `onNavigate` when someone clicks. A click on the tab or row it already
18
+ * shows, from a page filed under it (a draft under Requests), goes to that
19
+ * tab's own page.
18
20
  */
19
- import { useEffect, useMemo, useState } from "react";
21
+ import { useEffect, useMemo, useRef, useState } from "react";
20
22
  import { ActionList, TopBar, WorkspaceFrame } from "autosolutions-design-system";
21
23
  import { useCompanySwitch } from "./chrome.js";
22
- import { markFor, refreshOsContext } from "./context.js";
24
+ import { markFor, refreshOsContext, retryOsContext, watchOsAuth } from "./context.js";
23
25
  import { myAdminScope } from "./identity.js";
24
26
  import { catalogueLinks, osFrame } from "./nav.js";
25
- /* A company's mark in the company menu; nothing, never a broken image, when
26
- its artwork does not load (the row already says the company's name). */
27
+ /* A company's mark in the company menu. When its artwork does not load, the
28
+ slot stays, empty (the row already says the company's name), so the names
29
+ stay lined up; never a broken image. */
27
30
  function CompanyMenuMark({ src }) {
28
31
  const [failed, setFailed] = useState(null);
29
32
  if (failed === src)
30
- return null;
33
+ return _jsx("span", { className: "as-ws__company-mark", "aria-hidden": "true" });
31
34
  return _jsx("img", { className: "as-ws__company-mark", src: src, alt: "", onError: () => { if (failed !== src)
32
35
  setFailed(src); } });
33
36
  }
34
- export function OsWorkspaceFrame({ os, auth, appKey, tools, hubItems, location, onNavigate, search, actions, companySwitch = "os", panelFooter, onSignOut, settingsPath, homePath, admin, favicon = true, initialOpen, className, children, ...rest }) {
37
+ /* This app's own rows and tabs as links to their paths. Rows for other apps
38
+ already carry their address; a locked row is never a link. */
39
+ function linked(sections, hrefFor) {
40
+ const tab = (t) => {
41
+ const href = t.path && !t.disabled ? hrefFor(t.path) : null;
42
+ return href ? { ...t, href } : t;
43
+ };
44
+ const tabs = (list) => (list.length > 0 && "items" in list[0]
45
+ ? list.map((group) => ({ ...group, items: group.items.map(tab) }))
46
+ : list.map(tab));
47
+ const out = {};
48
+ for (const [fn, list] of Object.entries(sections)) {
49
+ out[fn] = list.map((section) => ({
50
+ ...section,
51
+ items: section.items.map((row) => {
52
+ const own = row.path && !row.href && !row.disabled ? hrefFor(row.path) : null;
53
+ return { ...row, ...(own ? { href: own } : {}), ...(row.tabs ? { tabs: tabs(row.tabs) } : {}) };
54
+ }),
55
+ }));
56
+ }
57
+ return out;
58
+ }
59
+ /* Where the address bar is: a navigation the app does not make leaves it. */
60
+ const here = () => (typeof window === "undefined" ? "" : window.location.pathname + window.location.search + window.location.hash);
61
+ export function OsWorkspaceFrame({ os, auth, appKey, tools, hubItems, location, onNavigate, hrefFor, search, actions, companySwitch = "os", panelFooter, onSignOut, settingsPath, homePath, admin, favicon = true, initialOpen, className, children, ...rest }) {
35
62
  /* Only data-* and aria-* reach the frame's root. */
36
63
  const attributes = Object.fromEntries(Object.entries(rest).filter(([key]) => /^(data|aria)-/.test(key)));
37
- const { context, current, tenants, busy: switching, error, choose } = useCompanySwitch(os, appKey);
64
+ const { context, status, current: read, tenants, busy: switching, error, choose } = useCompanySwitch(os, appKey);
38
65
  const [menuOpen, setMenuOpen] = useState(false);
39
66
  const [ownBusy, setOwnBusy] = useState(false);
40
67
  const busy = switching || ownBusy;
68
+ /* An in-place switch (companySwitch as a function) makes the chosen company
69
+ the acting one at once: the plate, the menu's check and the links follow
70
+ it until the core is read again, whether or not that read succeeds, so a
71
+ read that fails never leaves the plate on the company the session has
72
+ left (and a pick of that company is a real switch back). */
73
+ const [acting, setActing] = useState(null);
74
+ const current = acting && acting.over === context ? acting.tenant : read;
75
+ const contextNow = useRef(context);
76
+ contextNow.current = context;
77
+ const live = useRef(true);
78
+ useEffect(() => () => { live.current = false; }, []);
41
79
  /* The core decides who manages something; the footer only reflects it. */
42
80
  const [manages, setManages] = useState(false);
43
81
  useEffect(() => {
44
82
  if (admin !== undefined)
45
83
  return undefined;
46
- let live = true;
84
+ let alive = true;
47
85
  myAdminScope(os)
48
86
  .then((scope) => {
49
- if (live)
87
+ if (alive)
50
88
  setManages(scope.isPlatformAdmin || scope.managesTenants.length > 0);
51
89
  })
52
90
  .catch(() => {
53
91
  /* No Admin row is the safe failure; the admin console checks again anyway. */
54
92
  });
55
93
  return () => {
56
- live = false;
94
+ alive = false;
57
95
  };
58
96
  }, [os, admin]);
97
+ /* Follow sign-ins through the app's auth client, when it hands one. */
98
+ useEffect(() => {
99
+ if (auth && typeof auth.onAuthStateChange === "function")
100
+ watchOsAuth(auth);
101
+ }, [auth]);
102
+ /* A read that failed is asked again when the app moves, as well as on a
103
+ timer and when the window comes back (context.ts). */
104
+ useEffect(() => {
105
+ if (status === "failed")
106
+ void retryOsContext(os);
107
+ }, [location]);
59
108
  const apps = context?.apps;
60
109
  const slug = current?.slug ?? null;
61
110
  const frame = useMemo(() => {
62
- /* Only the catalogue says what this person holds. Until it arrives
63
- nothing is linked and nothing is "not held": other apps' tools read as
64
- not linked, never as a fixed address the person may not hold. */
65
- const { links, locked } = apps ? catalogueLinks(apps, slug) : { links: {}, locked: {} };
111
+ /* Only the catalogue says what this person holds. Until it arrives (or
112
+ while a failed read is asked again) nothing is linked and nothing is
113
+ "not held" or "not linked": other apps' tools read as being checked. */
114
+ const { links, locked } = catalogueLinks(apps ?? null, slug);
66
115
  return osFrame({
67
116
  appKey, links, locked, admin: admin ?? manages, tenantSlug: slug,
68
117
  ...(tools ? { tools } : {}),
@@ -71,21 +120,40 @@ export function OsWorkspaceFrame({ os, auth, appKey, tools, hubItems, location,
71
120
  ...(homePath ? { homePath } : {}),
72
121
  });
73
122
  }, [appKey, apps, admin, manages, slug, tools, hubItems, settingsPath, homePath]);
123
+ const linkTo = hrefFor === undefined ? (path) => path : hrefFor;
124
+ const sections = useMemo(() => (linkTo ? linked(frame.sections, linkTo) : frame.sections), [frame, hrefFor]);
74
125
  /* `false` tells the frame a click went nowhere (Settings on the page
75
- Settings goes to), so it stays where the location puts it. */
126
+ Settings goes to), so it stays where the location puts it. A promise of
127
+ `false`: the app's router did not make the navigation after all (the
128
+ address bar never moved), so the frame goes back where the URL is. */
76
129
  const navigate = (state) => {
77
130
  const target = frame.targetFor(state, location);
78
131
  if (!target)
79
132
  return false;
80
- if (target.external)
133
+ if (target.external) {
81
134
  window.location.assign(target.href);
82
- else
83
- onNavigate(target.href);
135
+ return true;
136
+ }
137
+ const before = here();
138
+ const result = onNavigate(target.href);
139
+ if (result && typeof result.then === "function") {
140
+ return Promise.resolve(result).then(() => here() !== before, () => here() !== before);
141
+ }
84
142
  return true;
85
143
  };
86
144
  const signOut = onSignOut ?? (() => {
87
145
  void auth?.signOut().then(() => window.location.reload());
88
146
  });
147
+ /* After an in-place switch: read the core again, and again if that fails,
148
+ a few times, while the frame is mounted. */
149
+ const readAgain = (tries) => {
150
+ void refreshOsContext(os).then((value) => {
151
+ if (value || tries <= 1 || !live.current)
152
+ return;
153
+ setTimeout(() => { if (live.current)
154
+ readAgain(tries - 1); }, 1500);
155
+ });
156
+ };
89
157
  /* The company menu, offered only when there is somewhere to switch to: a
90
158
  menu of radio items, the acting company checked. */
91
159
  const pick = (tenant) => {
@@ -98,11 +166,17 @@ export function OsWorkspaceFrame({ os, auth, appKey, tools, hubItems, location,
98
166
  return;
99
167
  setOwnBusy(true);
100
168
  companySwitch(tenant)
101
- .then(() => refreshOsContext(os))
169
+ .then(() => {
170
+ if (!live.current)
171
+ return;
172
+ setActing({ tenant, over: contextNow.current });
173
+ readAgain(3);
174
+ })
102
175
  .catch(() => {
103
176
  /* The app's switch says what went wrong; the plate stays as it was. */
104
177
  })
105
- .finally(() => setOwnBusy(false));
178
+ .finally(() => { if (live.current)
179
+ setOwnBusy(false); });
106
180
  };
107
181
  const switchable = companySwitch !== "none" && Boolean(current) && tenants.length > 1;
108
182
  const companyMenu = switchable && current ? (_jsxs(_Fragment, { children: [_jsx(ActionList, { role: "menu", "aria-label": "Switch company", sections: [{
@@ -118,6 +192,8 @@ export function OsWorkspaceFrame({ os, auth, appKey, tools, hubItems, location,
118
192
  }] }), busy && _jsx("div", { className: "as-ws__company-note", role: "status", children: "Switching\u2026" }), error && _jsx("div", { className: "as-ws__company-note as-ws__company-note--error", role: "alert", children: error })] })) : undefined;
119
193
  const topBar = (_jsx(TopBar, { variant: "workspace", searchPlaceholder: search?.placeholder ?? "Search", searchValue: search?.value, onSearchChange: search?.onChange, actions: actions, company: current?.slug ?? null, companySrc: current ? markFor(current, "plain") : undefined,
120
194
  /* Also what the plate shows when the company has no artwork, or it fails to load. */
121
- companyName: current?.name, onSwitchCompany: switchable ? () => setMenuOpen((open) => !open) : undefined, companyMenu: companyMenu, companyMenuOpen: menuOpen, onCompanyMenuClose: () => setMenuOpen(false) }));
122
- return (_jsx(WorkspaceFrame, { className: className, topBar: topBar, functions: frame.functions, sections: frame.sections, footerItems: frame.footerItems, homeFunction: frame.homeFunction, location: { ...frame.locate(location), href: location }, onNavigate: navigate, onSignOut: signOut, favicon: favicon, panelFooter: panelFooter, ...(initialOpen === undefined ? {} : { initialOpen }), ...attributes, children: children }));
195
+ companyName: current?.name,
196
+ /* While the company is read, its place on the bar is kept. */
197
+ companyPending: !current && status === "loading" ? (companySwitch === "none" ? "plate" : true) : undefined, onSwitchCompany: switchable ? () => setMenuOpen((open) => !open) : undefined, companyMenu: companyMenu, companyMenuOpen: menuOpen, onCompanyMenuClose: () => setMenuOpen(false) }));
198
+ return (_jsx(WorkspaceFrame, { className: className, topBar: topBar, functions: frame.functions, sections: sections, footerItems: frame.footerItems, homeFunction: frame.homeFunction, location: { ...frame.locate(location), href: location }, onNavigate: navigate, onSignOut: signOut, favicon: favicon, panelFooter: panelFooter, ...(initialOpen === undefined ? {} : { initialOpen }), ...attributes, children: children }));
123
199
  }
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export { coreUrl, corePublishableKey, coreProjectRef, companyMarkUrl, appLabelUrl, HUB_URL, PARENT_DOMAIN } from "./config.js";
2
2
  export { createOsClient, resetOsClient, type OsClient } from "./client.js";
3
3
  export { adoptSharedSession, publishSessionChanges, sharedSessionCookieName, joinChunks } from "./session.js";
4
- export { loadOsContext, invalidateOsContext, refreshOsContext, useOsContext, useTenant, useApps, groupApps, markFor, labelFor, withTenantHint, type OsContext, type OsTenant, type OsApp, } from "./context.js";
4
+ export { loadOsContext, invalidateOsContext, refreshOsContext, retryOsContext, watchOsAuth, useOsContext, useOsContextState, useTenant, useApps, groupApps, markFor, labelFor, withTenantHint, type OsContext, type OsContextStatus, type OsTenant, type OsApp, } from "./context.js";
5
5
  export { isEntitled, isActiveMember, appRole, appVariant, currentTenant, toolAllowed, myAdminScope, canManageCurrentCompany, type AdminScope, } from "./identity.js";
6
6
  export { OsAppSwitcher, OsAppSwitcherPlate, OsCompanySwitcher, OsBar, useCompanySwitch } from "./chrome.js";
7
7
  export { OsAuthGate, type OsAuthGateProps } from "./gate.js";
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  export { coreUrl, corePublishableKey, coreProjectRef, companyMarkUrl, appLabelUrl, HUB_URL, PARENT_DOMAIN } from "./config.js";
2
2
  export { createOsClient, resetOsClient } from "./client.js";
3
3
  export { adoptSharedSession, publishSessionChanges, sharedSessionCookieName, joinChunks } from "./session.js";
4
- export { loadOsContext, invalidateOsContext, refreshOsContext, useOsContext, useTenant, useApps, groupApps, markFor, labelFor, withTenantHint, } from "./context.js";
4
+ export { loadOsContext, invalidateOsContext, refreshOsContext, retryOsContext, watchOsAuth, useOsContext, useOsContextState, useTenant, useApps, groupApps, markFor, labelFor, withTenantHint, } from "./context.js";
5
5
  export { isEntitled, isActiveMember, appRole, appVariant, currentTenant, toolAllowed, myAdminScope, canManageCurrentCompany, } from "./identity.js";
6
6
  export { OsAppSwitcher, OsAppSwitcherPlate, OsCompanySwitcher, OsBar, useCompanySwitch } from "./chrome.js";
7
7
  export { OsAuthGate } from "./gate.js";
package/dist/nav.d.ts CHANGED
@@ -78,11 +78,16 @@ export declare const HUB_PATHS: {
78
78
  readonly admin: "/admin";
79
79
  readonly settings: "/comms/settings";
80
80
  };
81
- /** Why a row is locked. A tool whose status is In progress or To build says so instead. */
81
+ /**
82
+ * Why a row is locked. A tool whose status is In progress or To build says so
83
+ * instead. `checking` is a Live tool whose app the catalogue decides, while
84
+ * os_context() has not answered yet (or failed, and is being asked again).
85
+ */
82
86
  export declare const HINTS: {
83
87
  readonly locked: "Ask your company admin to switch this on for you";
84
88
  readonly notBuilt: "Not built yet";
85
89
  readonly notLinked: "Live, not linked from the Hub yet";
90
+ readonly checking: "Checking your access…";
86
91
  };
87
92
  /** The rail footer: Admin (for someone who manages something), Settings, then Sign out, always last. */
88
93
  export declare function osFooter({ admin }?: {
@@ -109,11 +114,16 @@ export declare function staticLinks(): Record<string, string>;
109
114
  * A fixed `url` is never consulted here: it is no way round the catalogue.
110
115
  * Tools with no app keep osFrame's own rules. Links are final: osFrame adds
111
116
  * nothing to them.
117
+ *
118
+ * With `apps` null (the catalogue has not answered yet, or the read failed
119
+ * and is being asked again), nothing is linked, and a Live tool with an app
120
+ * reads "Checking your access…" rather than claiming it is not linked or not
121
+ * held; any other keeps the map's own status.
112
122
  */
113
123
  export declare function catalogueLinks(apps: ReadonlyArray<{
114
124
  key: string;
115
125
  url: string | null;
116
- }>, tenantSlug?: string | null): {
126
+ }> | null, tenantSlug?: string | null): {
117
127
  links: Record<string, string>;
118
128
  locked: Record<string, string>;
119
129
  };
package/dist/nav.js CHANGED
@@ -160,11 +160,16 @@ export const HUB_PATHS = {
160
160
  admin: "/admin",
161
161
  settings: "/comms/settings",
162
162
  };
163
- /** Why a row is locked. A tool whose status is In progress or To build says so instead. */
163
+ /**
164
+ * Why a row is locked. A tool whose status is In progress or To build says so
165
+ * instead. `checking` is a Live tool whose app the catalogue decides, while
166
+ * os_context() has not answered yet (or failed, and is being asked again).
167
+ */
164
168
  export const HINTS = {
165
169
  locked: "Ask your company admin to switch this on for you",
166
170
  notBuilt: "Not built yet",
167
171
  notLinked: "Live, not linked from the Hub yet",
172
+ checking: "Checking your access…",
168
173
  };
169
174
  /** The rail footer: Admin (for someone who manages something), Settings, then Sign out, always last. */
170
175
  export function osFooter({ admin = false } = {}) {
@@ -201,6 +206,11 @@ export function staticLinks() {
201
206
  * A fixed `url` is never consulted here: it is no way round the catalogue.
202
207
  * Tools with no app keep osFrame's own rules. Links are final: osFrame adds
203
208
  * nothing to them.
209
+ *
210
+ * With `apps` null (the catalogue has not answered yet, or the read failed
211
+ * and is being asked again), nothing is linked, and a Live tool with an app
212
+ * reads "Checking your access…" rather than claiming it is not linked or not
213
+ * held; any other keeps the map's own status.
204
214
  */
205
215
  export function catalogueLinks(apps, tenantSlug = null) {
206
216
  const links = {};
@@ -208,6 +218,11 @@ export function catalogueLinks(apps, tenantSlug = null) {
208
218
  for (const [tool, link] of Object.entries(OS_TOOL_LINKS)) {
209
219
  if (!link.app)
210
220
  continue;
221
+ if (apps === null) {
222
+ if (STATUS.get(tool) === "Live")
223
+ locked[tool] = HINTS.checking;
224
+ continue;
225
+ }
211
226
  const app = apps.find((candidate) => candidate.key === link.app);
212
227
  if (app?.url)
213
228
  links[tool] = withTenantHint(joinPath(app.url, link.path), tenantSlug);
@@ -234,12 +249,18 @@ function joinPath(base, path) {
234
249
  function trimmed(pathname) {
235
250
  return pathname.replace(/\/+$/, "") || "/";
236
251
  }
237
- /** How specifically `route` claims `location`: [path length, query params], or null when it does not. */
238
- function claim(route, location) {
252
+ /**
253
+ * How specifically `route` claims `location`: [path length, query params], or
254
+ * null when it does not. Paths compare without regard to case, as the routers
255
+ * the apps use match them (TanStack Router, React Router): /ops/Boards is the
256
+ * Boards page. `/` claims every location, as a tool's catch-all, unless
257
+ * `exact`: a tab at `/` is one page, `/` itself.
258
+ */
259
+ function claim(route, location, exact = false) {
239
260
  const wanted = new URL(route, ORIGIN);
240
- const path = trimmed(wanted.pathname);
241
- const here = trimmed(location.pathname);
242
- if (path !== "/" && here !== path && !here.startsWith(`${path}/`))
261
+ const path = trimmed(wanted.pathname).toLowerCase();
262
+ const here = trimmed(location.pathname).toLowerCase();
263
+ if (path === "/" ? exact && here !== "/" : here !== path && !here.startsWith(`${path}/`))
243
264
  return null;
244
265
  let params = 0;
245
266
  for (const [key, value] of wanted.searchParams) {
@@ -256,12 +277,12 @@ function better(a, b) {
256
277
  return true;
257
278
  return a[0] > b[0] || (a[0] === b[0] && a[1] > b[1]);
258
279
  }
259
- function best(routes, location) {
280
+ function best(routes, location, exact = false) {
260
281
  let top = null;
261
282
  for (const route of routes) {
262
283
  if (!route)
263
284
  continue;
264
- const score = claim(route, location);
285
+ const score = claim(route, location, exact);
265
286
  if (better(score, top))
266
287
  top = score;
267
288
  }
@@ -317,7 +338,11 @@ export function osFrame(options) {
317
338
  section.items.push(rowFor({ id: tool.id, label: tool.label ?? tool.id, ...(tool.icon ? { icon: tool.icon } : {}) }, tool));
318
339
  }
319
340
  const footerItems = osFooter({ admin });
320
- /* Every place a location can land, most specific claim wins. */
341
+ /* Every place a location can land, most specific claim wins; on a tie, the
342
+ first. A tool's tabs come before the tool's own row, so where a tab and
343
+ its row claim a location alike (Key Accounts' Requests tab and the tool
344
+ both at /), it is on the tab: the list and a draft under it are one
345
+ place. */
321
346
  const claims = [];
322
347
  if (settingsPath)
323
348
  claims.push({ routes: [settingsPath], spot: { fn: "settings", item: null, tab: null } });
@@ -328,10 +353,10 @@ export function osFrame(options) {
328
353
  for (const row of section.items) {
329
354
  if (row.disabled)
330
355
  continue;
331
- claims.push({ routes: [row.path, ...(row.match ?? [])], spot: { fn, item: row.id, tab: null } });
332
356
  for (const tab of flatTabs(row.tabs)) {
333
- claims.push({ routes: [tab.path, ...(tab.match ?? [])], spot: { fn, item: row.id, tab: tab.id } });
357
+ claims.push({ routes: [tab.path, ...(tab.match ?? [])], spot: { fn, item: row.id, tab: tab.id }, exact: true });
334
358
  }
359
+ claims.push({ routes: [row.path, ...(row.match ?? [])], spot: { fn, item: row.id, tab: null } });
335
360
  }
336
361
  }
337
362
  }
@@ -347,7 +372,7 @@ export function osFrame(options) {
347
372
  let top = null;
348
373
  let found;
349
374
  for (const candidate of claims) {
350
- const score = best(candidate.routes, url);
375
+ const score = best(candidate.routes, url, candidate.exact);
351
376
  if (better(score, top)) {
352
377
  top = score;
353
378
  found = candidate.spot;
package/dist/url.d.ts CHANGED
@@ -1,9 +1,21 @@
1
- /**
2
- * URL helpers with no dependencies, so `autosolutions-os/nav` can use them
3
- * without pulling React or Supabase into an app's bundle.
4
- */
5
1
  /**
6
2
  * Apps show the acting company's branding, so a link carries it as a hint.
7
3
  * Access is still decided by the core; this only saves a round trip.
8
4
  */
9
5
  export declare function withTenantHint(url: string, slug: string | null): string;
6
+ /**
7
+ * Where a company switch lands once the core has made it: `null` reloads the
8
+ * page in place, a URL is a same-tab navigation.
9
+ *
10
+ * - The hub reloads where the person is. `switch_company_for_app` never
11
+ * returns a per-company hub URL, so there is nowhere else it would go.
12
+ * - An app goes to the deployment the core returns (`appUrl`), by a reload
13
+ * when that is this origin.
14
+ * - An app the new company does not hold (no `appUrl`) goes to the hub, as the
15
+ * apps' own company switchers did: a reload would land on the app's
16
+ * "not entitled" state.
17
+ */
18
+ export declare function companySwitchLanding(appKey: string, result: {
19
+ appUrl?: string | null;
20
+ tenantSlug?: string | null;
21
+ }, origin: string): string | null;
package/dist/url.js CHANGED
@@ -1,7 +1,9 @@
1
1
  /**
2
- * URL helpers with no dependencies, so `autosolutions-os/nav` can use them
3
- * without pulling React or Supabase into an app's bundle.
2
+ * URL helpers with no dependencies outside this package, so
3
+ * `autosolutions-os/nav` can use them without pulling React or Supabase into
4
+ * an app's bundle.
4
5
  */
6
+ import { HUB_URL } from "./config.js";
5
7
  /**
6
8
  * Apps show the acting company's branding, so a link carries it as a hint.
7
9
  * Access is still decided by the core; this only saves a round trip.
@@ -18,3 +20,28 @@ export function withTenantHint(url, slug) {
18
20
  return url;
19
21
  }
20
22
  }
23
+ /**
24
+ * Where a company switch lands once the core has made it: `null` reloads the
25
+ * page in place, a URL is a same-tab navigation.
26
+ *
27
+ * - The hub reloads where the person is. `switch_company_for_app` never
28
+ * returns a per-company hub URL, so there is nowhere else it would go.
29
+ * - An app goes to the deployment the core returns (`appUrl`), by a reload
30
+ * when that is this origin.
31
+ * - An app the new company does not hold (no `appUrl`) goes to the hub, as the
32
+ * apps' own company switchers did: a reload would land on the app's
33
+ * "not entitled" state.
34
+ */
35
+ export function companySwitchLanding(appKey, result, origin) {
36
+ if (appKey === "hub")
37
+ return null;
38
+ const destination = result.appUrl ? withTenantHint(result.appUrl, result.tenantSlug ?? null) : HUB_URL;
39
+ try {
40
+ if (new URL(destination).origin === origin)
41
+ return null;
42
+ }
43
+ catch {
44
+ /* malformed destination: navigate anyway and let the browser report it */
45
+ }
46
+ return destination;
47
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "autosolutions-os",
3
- "version": "0.2.3",
3
+ "version": "0.2.4",
4
4
  "description": "One sign-in, one company switcher, one app grid. What every AutoSolutions app imports instead of copying.",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",
@@ -21,7 +21,7 @@
21
21
  },
22
22
  "peerDependencies": {
23
23
  "@supabase/supabase-js": ">=2.40.0",
24
- "autosolutions-design-system": ">=6.3.4 <7",
24
+ "autosolutions-design-system": ">=6.4.0 <7",
25
25
  "react": ">=18"
26
26
  },
27
27
  "peerDependenciesMeta": {