@micha.bigler/ui-core-micha 4.18.0 → 4.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # Changelog
2
2
 
3
+ ## 4.20.0 - UCM-AUTH-15
4
+
5
+ `SignUpContent` and `SignUpPage` accept an optional `preferredSignupMode`: when the server offers that mode it is shown
6
+ first and preselected, otherwise it is ignored and the server order applies (a QR link still selects the QR mode).
7
+ Visible change in every app: the submit button of open self-signup (`self_signup_open`) now reads "Konto anlegen" /
8
+ "Create account" (new key `Auth.SIGNUP_SUBMIT_OPEN`); access-code, e-mail-domain and QR signup keep "Einladung
9
+ anfordern" / "Request invitation".
10
+
11
+ ## 4.19.0 - UCM-CHAT-8
12
+
13
+ `ChatWorkspace` starts the status, catalogue and both chat-list requests together on mount and on every scope change,
14
+ instead of waiting for the status first; when the status is not `available` (or fails) the other answers are discarded
15
+ and the unavailable or error state is shown as before. New optional prop `preloadedChats` (`{ scope, results, next }`):
16
+ an active list the app already loaded for the same `scope` replaces the active-list request at the start; the archived
17
+ list is still requested, and later reloads are unchanged. Every consumer now sends catalogue and list requests also when
18
+ the assistant is not configured.
19
+
3
20
  ## 4.18.0 - UCM-BILL-10
4
21
 
5
22
  `AccountPage` accepts an optional `billingOperator({ user, account }) => boolean` and passes it as the operator rule to
package/README.md CHANGED
@@ -54,7 +54,10 @@ project, import or payment work. Existing pages and the dialog `OnboardingProvid
54
54
  ignored until it settles. `primaryForm` names a form in the content that the primary button submits natively.
55
55
  - `SignUpContent` — the sign-up form of `SignUpPage` (all modes, Turnstile, QR token via `registrationContextToken`).
56
56
  `onSubmitted(email)` switches it to the confirmation instruction; remount it (new `key`) to let the person change the
57
- email. `showProviders` adds Google/Microsoft above the form.
57
+ email. `showProviders` adds Google/Microsoft above the form. `preferredSignupMode` (also on `SignUpPage`, e.g.
58
+ `'self_signup_open'`) shows that mode first and selected when the server offers it; otherwise it is ignored and the
59
+ server order applies. Open self-signup submits with "Konto anlegen" (`Auth.SIGNUP_SUBMIT_OPEN`); the other modes
60
+ keep "Einladung anfordern".
58
61
  - `SignupConfirmContent` — the password form of `SignupConfirmPage`. Pass `token` (from the emailed
59
62
  `/signup/confirm/?token=…` link, which your app routes) and `onSuccess()`; there is no automatic sign-in, show
60
63
  `LoginContent` next.
@@ -169,7 +172,10 @@ above the composer. Without `composerLayout` the composer is unchanged. `ChatCom
169
172
 
170
173
  `ChatWorkspace` (from `@micha.bigler/ui-core-micha/chat`) takes optional props for apps that put UI around the surface;
171
174
  without them it behaves as before. Each is described in `CHANGELOG.md` under the release that added it.
172
- Since 4.3.0: `getSendContext()` (a plain object attached as `context` to every `send` frame, read by
175
+ Since 4.19.0: `preloadedChats` (`{ scope, results, next }`, the active-list response the app already loaded for that
176
+ `scope`): the start then requests only the archived list. It is used once, at the start, and only when its `scope`
177
+ equals the workspace's `scope`; later reloads request both lists as before. The start requests status, catalogue and
178
+ both lists together; when the status is not available their answers are discarded. Since 4.3.0: `getSendContext()` (a plain object attached as `context` to every `send` frame, read by
173
179
  `django-core-micha` 3.3.0), `sendRequest` (`{ id, text }`, sends a message on the host's behalf) and
174
180
  `onSendRequestHandled({ id, sent })`. Since 4.2.0: `activeChatId`, `onActiveChatChange`, `composerPrefill` and
175
181
  `send(text)` / `canSend` in `renderAnswerExtra`.
@@ -60,9 +60,10 @@ const appendDelta = (turns, text) => {
60
60
  * The complete chat surface: chat list, thread, composer and model picker for one user.
61
61
  *
62
62
  * Props: `apiBase` and `wsUrl` (where the app mounted the chat routes), `api` (partial overrides of the REST
63
- * calls; every function not given keeps its default), `scope` (passed when creating a chat), `sx`.
63
+ * calls; every function not given keeps its default), `scope` (passed when creating a chat),
64
+ * `preloadedChats` (optional active-list response `{ scope, results, next }` already loaded for that exact scope), `sx`.
64
65
  */
65
- export function ChatWorkspace({ apiBase, wsUrl, api: apiOverrides, scope, sx, unavailableReasonText, sidePanel, sidePanelLabel, renderAnswerExtra, renderComposerExtra, composerLayout = 'standard', renderComposerContext, onAppFrame, activeChatId, onActiveChatChange, composerPrefill, getSendContext, sendRequest, onSendRequestHandled, layout = 'viewport', compactBelow = 720, tokenBalance = null, usageToTokens, longChatTokens = 40000 }) {
66
+ export function ChatWorkspace({ apiBase, wsUrl, api: apiOverrides, scope, preloadedChats, sx, unavailableReasonText, sidePanel, sidePanelLabel, renderAnswerExtra, renderComposerExtra, composerLayout = 'standard', renderComposerContext, onAppFrame, activeChatId, onActiveChatChange, composerPrefill, getSendContext, sendRequest, onSendRequestHandled, layout = 'viewport', compactBelow = 720, tokenBalance = null, usageToTokens, longChatTokens = 40000 }) {
66
67
  var _a;
67
68
  const { t } = useTranslation();
68
69
  const theme = useTheme();
@@ -165,37 +166,61 @@ export function ChatWorkspace({ apiBase, wsUrl, api: apiOverrides, scope, sx, un
165
166
  // Bumped on every scope change so that a list response of the previous scope is dropped.
166
167
  const scopeVersion = useRef(0);
167
168
  useEffect(() => { scopeVersion.current += 1; setChat(null); setListsLoaded(false); appliedId.current = undefined; unloadableIds.current.clear(); }, [scope]);
168
- const loadLists = useCallback(async () => {
169
+ const loadLists = useCallback(async ({ initial = false, preloaded } = {}) => {
169
170
  const version = scopeVersion.current;
170
171
  // Without a scope the api is called exactly as before the scope existed.
171
- const [active, old] = scope === undefined
172
- ? await Promise.all([api.listChats(), api.listChats({ archived: true })])
173
- : await Promise.all([api.listChats({ scope }), api.listChats({ scope, archived: true })]);
172
+ const activeRequest = preloaded === undefined
173
+ ? (scope === undefined ? api.listChats() : api.listChats({ scope }))
174
+ : Promise.resolve(preloaded);
175
+ const archivedRequest = scope === undefined ? api.listChats({ archived: true }) : api.listChats({ scope, archived: true });
176
+ const [active, old] = await Promise.all([activeRequest, archivedRequest]);
174
177
  if (version !== scopeVersion.current)
175
178
  return undefined;
176
- setChats(active.results || []);
177
- setNextChats(active.next || null);
178
- setArchived(old.results || []);
179
- return [...(active.results || []), ...(old.results || [])];
179
+ if (!initial) {
180
+ setChats(active.results || []);
181
+ setNextChats(active.next || null);
182
+ setArchived(old.results || []);
183
+ }
184
+ return { active, old, all: [...(active.results || []), ...(old.results || [])] };
180
185
  }, [api, scope]);
186
+ // Read through a ref: the preloaded list only matters when a start begins, and an inline object from the app must
187
+ // not restart the start requests on every render.
188
+ const preloadedChatsRef = useRef(preloadedChats);
189
+ preloadedChatsRef.current = preloadedChats;
181
190
  useEffect(() => {
182
191
  let live = true;
183
- const request = scope === undefined ? api.getStatus() : api.getStatus({ scope });
184
- request
185
- .then(async (state) => {
192
+ const offered = preloadedChatsRef.current;
193
+ const preloaded = offered && offered.scope === scope
194
+ ? { results: offered.results, next: offered.next }
195
+ : undefined;
196
+ const statusRequest = Promise.resolve().then(() => (scope === undefined ? api.getStatus() : api.getStatus({ scope })));
197
+ const catalogueRequest = Promise.resolve().then(() => api.getCatalogue());
198
+ const listsRequest = Promise.resolve().then(() => loadLists({ initial: true, preloaded }));
199
+ // These may finish after an unavailable status; attach rejection handlers immediately and never expose their answers.
200
+ catalogueRequest.catch(() => { });
201
+ listsRequest.catch(() => { });
202
+ statusRequest
203
+ .then((state) => {
204
+ if (!live)
205
+ return;
186
206
  if (state.status !== 'available') {
187
- if (live) {
188
- setStatus(state.status);
189
- setUnavailableReason(state.reason || null);
190
- }
207
+ setStatus(state.status);
208
+ setUnavailableReason(state.reason || null);
191
209
  return;
192
210
  }
193
- const [entries] = await Promise.all([api.getCatalogue(), loadLists()]);
194
- if (live) {
195
- setStatus(state.status);
211
+ Promise.all([catalogueRequest, listsRequest]).then(([entries, lists]) => {
212
+ if (!live || lists === undefined)
213
+ return;
214
+ const { active, old } = lists;
196
215
  setCatalogue(entries);
216
+ setChats(active.results || []);
217
+ setNextChats(active.next || null);
218
+ setArchived(old.results || []);
219
+ setStatus(state.status);
197
220
  setListsLoaded(true);
198
- }
221
+ setUnavailableReason(null);
222
+ }).catch(() => { if (live)
223
+ setStatus('error'); });
199
224
  })
200
225
  .catch(() => { if (live)
201
226
  setStatus('error'); });
@@ -238,7 +263,7 @@ export function ChatWorkspace({ apiBase, wsUrl, api: apiOverrides, scope, sx, un
238
263
  loadLists().then((loaded) => {
239
264
  if (!live || loaded === undefined || latestWantedId.current === undefined || String(latestWantedId.current) !== wantedKey)
240
265
  return;
241
- const found = loaded.find((item) => String(item.id) === wantedKey);
266
+ const found = loaded.all.find((item) => String(item.id) === wantedKey);
242
267
  if (!found)
243
268
  unloadableIds.current.add(wantedKey);
244
269
  setChat(found || null);
@@ -32,6 +32,12 @@ export function resolveSignupModes(authMethods) {
32
32
  }
33
33
  return (authMethods === null || authMethods === void 0 ? void 0 : authMethods.signup) ? ['self_signup_access_code'] : [];
34
34
  }
35
+ // An app's preferred mode moves to the front only when the server offers it; the server decides which modes exist.
36
+ export function orderSignupModes(modes, preferredMode) {
37
+ return preferredMode && modes.includes(preferredMode)
38
+ ? [preferredMode, ...modes.filter((entry) => entry !== preferredMode)]
39
+ : modes;
40
+ }
35
41
  /**
36
42
  * The sign-up form shared by SignUpPage and embedded flows: every configured
37
43
  * sign-up mode, Turnstile, the QR registration context and the existing
@@ -39,6 +45,7 @@ export function resolveSignupModes(authMethods) {
39
45
  *
40
46
  * Props:
41
47
  * - `registrationContextToken`: the QR token (SignUpPage passes `?rt`).
48
+ * - `preferredSignupMode`: optional available mode to show and select first.
42
49
  * - `onModeChange(mode)`: reports the selected sign-up mode.
43
50
  * - `onSubmitted(email)`: embedded use. Called after the request succeeded with
44
51
  * the email only; the component then shows the confirmation instruction instead
@@ -49,10 +56,11 @@ export function resolveSignupModes(authMethods) {
49
56
  * the provider callback URL.
50
57
  * The access code, QR token and Turnstile token never leave this component.
51
58
  */
52
- export function SignUpContent({ registrationContextToken = '', onModeChange, onSubmitted, showProviders = false, continuation, }) {
59
+ export function SignUpContent({ registrationContextToken = '', preferredSignupMode, onModeChange, onSubmitted, showProviders = false, continuation, }) {
53
60
  const { t, i18n } = useTranslation();
54
61
  const { authMethods } = useContext(AuthContext) || {};
55
- const signupModes = useMemo(() => resolveSignupModes(authMethods), [authMethods]);
62
+ const serverSignupModes = useMemo(() => resolveSignupModes(authMethods), [authMethods]);
63
+ const signupModes = useMemo(() => orderSignupModes(serverSignupModes, preferredSignupMode), [preferredSignupMode, serverSignupModes]);
56
64
  const initialMode = useMemo(() => {
57
65
  if (registrationContextToken && signupModes.includes('self_signup_qr')) {
58
66
  return 'self_signup_qr';
@@ -151,5 +159,5 @@ export function SignUpContent({ registrationContextToken = '', onModeChange, onS
151
159
  }
152
160
  return (_jsxs(_Fragment, { children: [successKey && (_jsx(Alert, { severity: "success", sx: SIGN_UP_PAGE_ALERT_SX, children: t(successKey, { email }) })), errorKey && (_jsx(Alert, { severity: "error", sx: SIGN_UP_PAGE_ALERT_SX, children: errorKey })), providersVisible && (_jsxs(Box, { sx: { mb: 2 }, children: [_jsx(SocialLoginButtons, { onProviderClick: handleProviderLogin, providers: socialProviders }), providerTransition && (_jsx(Alert, { severity: "info", sx: SIGN_UP_PROVIDER_ALERT_SX, children: t('Auth.PROVIDER_TRANSITION', { provider: PROVIDER_NAMES[providerTransition] || providerTransition }) })), _jsx(Divider, { sx: SIGN_UP_PROVIDER_DIVIDER_SX, children: t('Auth.LOGIN_OR') })] })), signupModes.length > 1 && (_jsx(Stack, { spacing: 1, sx: { mb: 2 }, children: signupModes.map((entry) => (_jsx(Button, { variant: mode === entry ? 'contained' : 'outlined', onClick: () => setMode(entry), disabled: submitting, fullWidth: true, children: t(MODE_LABELS[entry] || entry, entry) }, entry))) })), _jsxs(Box, { component: "form", onSubmit: handleSubmit, sx: { display: 'flex', flexDirection: 'column', gap: 2 }, children: [_jsx(TextField, { label: t('Auth.EMAIL_LABEL'), type: "email", required: true, fullWidth: true, value: email, onChange: (e) => setEmail(e.target.value), disabled: submitting }), mode === 'self_signup_access_code' && (_jsx(TextField, { label: t('Auth.ACCESS_CODE_LABEL'), type: "text", required: true, fullWidth: true, value: accessCode, onChange: (e) => setAccessCode(e.target.value), disabled: submitting })), turnstileRequired && (_jsx(TurnstileWidget, { ref: turnstileWidgetRef, siteKey: authMethods.turnstile_site_key, onToken: setTurnstileToken })), _jsx(Button, { type: "submit", variant: "contained", disabled: submitting || Boolean(providerTransition) || (turnstileRequired && !turnstileToken), children: submitting
153
161
  ? t('Auth.SIGNUP_SUBMITTING')
154
- : t('Auth.SIGNUP_SUBMIT') })] })] }));
162
+ : t(mode === 'self_signup_open' ? 'Auth.SIGNUP_SUBMIT_OPEN' : 'Auth.SIGNUP_SUBMIT') })] })] }));
155
163
  }
@@ -444,6 +444,12 @@ export const authTranslations = {
444
444
  "en": "Request invitation",
445
445
  "sw": "Omba mwaliko"
446
446
  },
447
+ "Auth.SIGNUP_SUBMIT_OPEN": {
448
+ "de": "Konto anlegen",
449
+ "fr": "Créer un compte",
450
+ "en": "Create account",
451
+ "sw": "Fungua akaunti"
452
+ },
447
453
  "Auth.SIGNUP_SUBMITTING": {
448
454
  "de": "Sende…",
449
455
  "fr": "Envoi…",
@@ -5,7 +5,7 @@ import { Box, Button, Typography } from '@mui/material';
5
5
  import { useTranslation } from 'react-i18next';
6
6
  import { NarrowPage } from '../layout/PageLayout';
7
7
  import { AuthContext } from '../auth/AuthContext';
8
- import { SIGN_UP_PAGE_ALERT_SX, SignUpContent, resolveSignupModes, } from '../components/SignUpContent';
8
+ import { SIGN_UP_PAGE_ALERT_SX, SignUpContent, orderSignupModes, resolveSignupModes, } from '../components/SignUpContent';
9
9
  export { SIGN_UP_PAGE_ALERT_SX };
10
10
  const MODE_SUBTITLES = {
11
11
  self_signup_access_code: 'Auth.PAGE_SIGNUP_SUBTITLE_ACCESS_CODE',
@@ -15,12 +15,13 @@ const MODE_SUBTITLES = {
15
15
  };
16
16
  // The form and its sign-up logic live in SignUpContent (UCM-AUTH-14); the page
17
17
  // keeps the route framing, the `?rt` QR token source and the login link.
18
- export function SignUpPage() {
18
+ export function SignUpPage({ preferredSignupMode }) {
19
19
  const navigate = useNavigate();
20
20
  const location = useLocation();
21
21
  const { t } = useTranslation();
22
22
  const { authMethods } = useContext(AuthContext);
23
- const signupModes = useMemo(() => resolveSignupModes(authMethods), [authMethods]);
23
+ const serverSignupModes = useMemo(() => resolveSignupModes(authMethods), [authMethods]);
24
+ const signupModes = useMemo(() => orderSignupModes(serverSignupModes, preferredSignupMode), [preferredSignupMode, serverSignupModes]);
24
25
  const query = new URLSearchParams(location.search);
25
26
  const tokenFromUrl = query.get('rt') || '';
26
27
  const [mode, setMode] = useState(() => (tokenFromUrl && signupModes.includes('self_signup_qr')
@@ -35,5 +36,5 @@ export function SignUpPage() {
35
36
  const handleGoToLogin = () => {
36
37
  navigate('/login');
37
38
  };
38
- return (_jsxs(NarrowPage, { title: t('Auth.LOGIN_SIGNUP_BUTTON'), subtitle: pageSubtitle, children: [_jsx("title", { children: `${t('App.NAME')} – ${t('Auth.LOGIN_SIGNUP_BUTTON')}` }), _jsx(SignUpContent, { registrationContextToken: tokenFromUrl, onModeChange: setMode }), _jsx(Box, { sx: { mt: 3 }, children: _jsxs(Typography, { variant: "body2", children: [t('Auth.SIGNUP_ALREADY_HAVE_ACCOUNT'), ' ', _jsx(Button, { onClick: handleGoToLogin, variant: "text", size: "small", children: t('Auth.SIGNUP_GO_TO_LOGIN') })] }) })] }));
39
+ return (_jsxs(NarrowPage, { title: t('Auth.LOGIN_SIGNUP_BUTTON'), subtitle: pageSubtitle, children: [_jsx("title", { children: `${t('App.NAME')} – ${t('Auth.LOGIN_SIGNUP_BUTTON')}` }), _jsx(SignUpContent, { registrationContextToken: tokenFromUrl, preferredSignupMode: preferredSignupMode, onModeChange: setMode }), _jsx(Box, { sx: { mt: 3 }, children: _jsxs(Typography, { variant: "body2", children: [t('Auth.SIGNUP_ALREADY_HAVE_ACCOUNT'), ' ', _jsx(Button, { onClick: handleGoToLogin, variant: "text", size: "small", children: t('Auth.SIGNUP_GO_TO_LOGIN') })] }) })] }));
39
40
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@micha.bigler/ui-core-micha",
3
- "version": "4.18.0",
3
+ "version": "4.20.0",
4
4
  "main": "dist/index.js",
5
5
  "module": "dist/index.js",
6
6
  "exports": {