@griddo/ax 12.15.0-beta.1 → 12.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.md +0 -1
  2. package/package.json +4 -7
  3. package/src/GlobalStore.tsx +25 -32
  4. package/src/__tests__/components/Fields/FileField/FileField.test.tsx +6 -33
  5. package/src/__tests__/components/FieldsBehavior/FieldsBehavior.test.tsx +3 -5
  6. package/src/__tests__/modules/GlobalSettings/Llms/Llms.uc.test.tsx +2861 -0
  7. package/src/__tests__/modules/Redirects/Redirects/Redirects.create.test.tsx +0 -19
  8. package/src/__tests__/modules/Redirects/Redirects/Redirects.edit.test.tsx +0 -19
  9. package/src/__tests__/modules/Redirects/Redirects/Redirects.filter.test.tsx +0 -19
  10. package/src/api/domains.tsx +98 -2
  11. package/src/api/global.tsx +1 -24
  12. package/src/api/utils.tsx +12 -22
  13. package/src/components/FieldsBehavior/index.tsx +1 -3
  14. package/src/components/Login/LoginForm/index.tsx +2 -7
  15. package/src/components/Login/index.tsx +1 -13
  16. package/src/components/index.tsx +7 -11
  17. package/src/containers/App/actions.tsx +5 -110
  18. package/src/containers/App/interfaces.tsx +2 -2
  19. package/src/containers/App/reducer.tsx +0 -9
  20. package/src/containers/Users/actions.tsx +24 -28
  21. package/src/{components/CategoryCell/buildCategoryColumns.tsx → helpers/categoryColumns.tsx} +2 -3
  22. package/src/{components/FieldsBehavior/getFieldByPath.tsx → helpers/fields.tsx} +1 -1
  23. package/src/helpers/index.tsx +5 -4
  24. package/src/locales/en-US.ts +0 -7
  25. package/src/locales/es-ES.ts +0 -7
  26. package/src/locales/index.ts +0 -10
  27. package/src/modules/App/Routing/NavMenu/index.tsx +4 -4
  28. package/src/modules/Content/PageItem/index.tsx +8 -6
  29. package/src/modules/GlobalSettings/Llms/AutomaticSelection/index.tsx +317 -0
  30. package/src/modules/GlobalSettings/Llms/DomainList/index.tsx +65 -0
  31. package/src/modules/GlobalSettings/Llms/IndexModelEditor/index.tsx +325 -0
  32. package/src/modules/GlobalSettings/Llms/MirrorExample/index.tsx +61 -0
  33. package/src/modules/GlobalSettings/Llms/MirrorOptions/index.tsx +82 -0
  34. package/src/modules/GlobalSettings/Llms/Outline/index.tsx +183 -0
  35. package/src/modules/GlobalSettings/Llms/PagePicker/index.tsx +105 -0
  36. package/src/modules/GlobalSettings/Llms/Preview/index.tsx +65 -0
  37. package/src/modules/GlobalSettings/Llms/ResolvedPages/index.tsx +191 -0
  38. package/src/modules/GlobalSettings/Llms/SectionEditor/index.tsx +262 -0
  39. package/src/modules/GlobalSettings/Llms/atoms.tsx +37 -0
  40. package/src/modules/GlobalSettings/Llms/index.tsx +383 -0
  41. package/src/modules/GlobalSettings/Llms/style.tsx +541 -0
  42. package/src/modules/GlobalSettings/Llms/utils.tsx +307 -0
  43. package/src/modules/GlobalSettings/index.tsx +7 -0
  44. package/src/modules/Login/index.tsx +2 -12
  45. package/src/modules/StructuredData/StructuredDataList/GlobalPageItem/index.tsx +8 -6
  46. package/src/modules/StructuredData/StructuredDataList/StructuredDataItem/index.tsx +11 -9
  47. package/src/routes/multisite.tsx +8 -1
  48. package/src/routes/publicRoutes.tsx +0 -3
  49. package/src/schemas/pages/GlobalPage.ts +2 -2
  50. package/src/schemas/pages/Page.ts +2 -2
  51. package/src/types/index.tsx +80 -12
  52. package/src/types/llms.tsx +315 -0
  53. package/src/__tests__/GlobalStore.session.test.tsx +0 -98
  54. package/src/__tests__/api/global.test.ts +0 -64
  55. package/src/__tests__/api/session.test.ts +0 -311
  56. package/src/__tests__/api/sessionRenewal.test.ts +0 -705
  57. package/src/__tests__/api/utils.test.ts +0 -373
  58. package/src/__tests__/components/Login/LoginGriddoId.test.tsx +0 -195
  59. package/src/__tests__/components/SsoDenied/SsoDenied.test.tsx +0 -86
  60. package/src/__tests__/containers/App/reducer.griddoId.test.ts +0 -18
  61. package/src/__tests__/containers/App/session.test.ts +0 -397
  62. package/src/__tests__/helpers/griddoId.test.ts +0 -56
  63. package/src/__tests__/locales/loginLocale.test.ts +0 -52
  64. package/src/__tests__/modules/App/Routing/NavMenu.test.tsx +0 -54
  65. package/src/__tests__/modules/Login/Login.test.tsx +0 -151
  66. package/src/__tests__/modules/SsoDenied/SsoDenied.test.tsx +0 -30
  67. package/src/__tests__/routes/publicRoutes.test.ts +0 -36
  68. package/src/api/session.tsx +0 -197
  69. package/src/api/sessionRenewal.tsx +0 -114
  70. package/src/components/Login/LoginGriddoId/index.tsx +0 -46
  71. package/src/components/Login/LoginGriddoId/style.tsx +0 -35
  72. package/src/components/SsoDenied/index.tsx +0 -46
  73. package/src/components/SsoDenied/style.tsx +0 -37
  74. package/src/helpers/griddoId.ts +0 -28
  75. package/src/modules/SsoDenied/index.tsx +0 -9
@@ -0,0 +1,383 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2
+ import { connect } from "react-redux";
3
+
4
+ import { domains } from "@ax/api";
5
+ import { EmptyState, ErrorToast, GuardModal, Loading, MainWrapper, Nav } from "@ax/components";
6
+ import { appActions } from "@ax/containers/App";
7
+ import { RouteLeavingGuard } from "@ax/guards";
8
+ import { isReqOk } from "@ax/helpers";
9
+ import { useModal } from "@ax/hooks";
10
+ import type {
11
+ ILanguage,
12
+ INavItem,
13
+ IRootState,
14
+ LlmsDomain,
15
+ LlmsDomainPage,
16
+ LlmsPagesResponse,
17
+ LlmsSettings,
18
+ } from "@ax/types";
19
+
20
+ import type { AxiosResponse } from "axios";
21
+ import isEqual from "lodash.isequal";
22
+
23
+ import DomainList from "./DomainList";
24
+ import IndexModelEditor from "./IndexModelEditor";
25
+ import MirrorOptions from "./MirrorOptions";
26
+ import {
27
+ domainLabel,
28
+ hasUnnamedSection,
29
+ type LlmsIndexDraft,
30
+ type LlmsSettingsDraft,
31
+ type MirrorCommonOptions,
32
+ sectionPageIds,
33
+ toDraft,
34
+ toMirrorCommon,
35
+ toSettings,
36
+ } from "./utils";
37
+
38
+ import * as S from "./style";
39
+
40
+ /** Una respuesta que llegó y con estado de éxito; sin red, `sendRequest` no devuelve nada. */
41
+ const isOk = (response: AxiosResponse | undefined): response is AxiosResponse => !!response && isReqOk(response.status);
42
+
43
+ /**
44
+ * Los ajustes de superficie LLM de cada dominio: el LLM Index Model y las opciones del
45
+ * espejo markdown, que se guardan juntos y enteros. Abre con la lista de dominios y,
46
+ * bajo ella, las opciones del espejo comunes a todos: guardarlas las escribe en los
47
+ * ajustes de cada uno. Si un dominio escribe el espejo se decide en él. Al elegir uno enseña el esquema de su fichero con lo elegido
48
+ * editándose al lado. El dominio abierto vive en el estado de la pantalla, no en su
49
+ * dirección, y las dos salidas —la miga de pan y cualquier otra— piden confirmar los
50
+ * cambios sin guardar.
51
+ */
52
+ const Llms = (props: IProps): JSX.Element => {
53
+ const { navItems, currentNavItem, globalLangs, setHistoryPush, handleError } = props;
54
+
55
+ const [domainList, setDomainList] = useState<LlmsDomain[] | null>(null);
56
+ const [isListUnreadable, setIsListUnreadable] = useState(false);
57
+ // `null` si los ajustes de ese dominio no se pudieron leer; sin entrada mientras llegan.
58
+ const [settingsById, setSettingsById] = useState<Record<number, LlmsSettings | null>>({});
59
+ const [domainId, setDomainId] = useState<number | null>(null);
60
+ const [saved, setSaved] = useState<LlmsSettings | null>(null);
61
+ const [draft, setDraft] = useState<LlmsSettingsDraft | null>(null);
62
+ const [pages, setPages] = useState<Record<number, LlmsDomainPage>>({});
63
+ // Si la petición por id de las páginas elegidas falló: entonces no se sabe si se encuentran.
64
+ const [arePagesUnread, setArePagesUnread] = useState(false);
65
+ const [isSaving, setIsSaving] = useState(false);
66
+ // Las opciones del espejo comunes a todos los dominios; `null` hasta saber con qué abren.
67
+ const [mirror, setMirror] = useState<MirrorCommonOptions | null>(null);
68
+ const [isSavingMirror, setIsSavingMirror] = useState(false);
69
+ const [unreadableId, setUnreadableId] = useState<number | null>(null);
70
+ const { isOpen: isGuardOpen, toggleModal: toggleGuard } = useModal();
71
+ // El dominio abierto, para descartar la respuesta tardía de uno que ya se dejó.
72
+ const openedDomain = useRef<number | null>(null);
73
+ // La última vez que se eligió un dominio de la lista: un reintento que llega después de otra elección no abre nada.
74
+ const lastSelection = useRef(0);
75
+
76
+ // Lo que hay en pantalla, en la forma del contrato, frente a lo último que devolvió la API
77
+ // tal como lo abre la pantalla: las opciones fijas del espejo no cuentan como un cambio.
78
+ const settings = useMemo(() => (draft ? toSettings(draft) : null), [draft]);
79
+ const savedOnScreen = useMemo(() => (saved ? toSettings(toDraft(saved)) : null), [saved]);
80
+ const isDirty = settings !== null && savedOnScreen !== null && !isEqual(settings, savedOnScreen);
81
+
82
+ // Las opciones comunes se guardan en los ajustes de cada dominio, así que solo se pueden
83
+ // guardar con los de todos leídos: la API sustituye los ajustes enteros, y enviarle a uno
84
+ // solo las opciones le borraría su índice.
85
+ const readSettings = useMemo(
86
+ () => (domainList ?? []).map((domain) => settingsById[domain.id]),
87
+ [domainList, settingsById],
88
+ );
89
+ const canSaveMirror = readSettings.every((stored) => !!stored);
90
+ // Sin guardar mientras algún dominio con sus ajustes leídos no las tenga así.
91
+ const isMirrorDirty =
92
+ mirror !== null && readSettings.some((stored) => !!stored && !isEqual(toMirrorCommon(stored.markdown), mirror));
93
+
94
+ const reportError = useCallback(
95
+ (response: AxiosResponse | undefined) => handleError(response ?? "The request could not be completed."),
96
+ [handleError],
97
+ );
98
+
99
+ // Las opciones comunes abren con las del primer dominio de la lista cuyos ajustes se
100
+ // pudieron leer, en cuanto se sabe cuál es: cuando han llegado los de los anteriores.
101
+ useEffect(() => {
102
+ if (mirror !== null || domainList === null) return;
103
+ for (const domain of domainList) {
104
+ const stored = settingsById[domain.id];
105
+ if (stored === undefined) return;
106
+ if (stored !== null) {
107
+ setMirror(toMirrorCommon(stored.markdown));
108
+ return;
109
+ }
110
+ }
111
+ }, [mirror, domainList, settingsById]);
112
+
113
+ // biome-ignore lint/correctness/useExhaustiveDependencies: la lista de dominios se pide una vez, al montar
114
+ useEffect(() => {
115
+ const loadDomains = async () => {
116
+ const response = await domains.getDomains();
117
+ if (!isOk(response)) {
118
+ reportError(response);
119
+ setIsListUnreadable(true);
120
+ return;
121
+ }
122
+ const list: LlmsDomain[] = response.data;
123
+ setDomainList(list);
124
+ // Uno a uno: la API no tiene un resumen propio, y una instancia tiene pocos dominios.
125
+ for (const domain of list) {
126
+ domains.getLlmsSettings(domain.id).then((settingsResponse: AxiosResponse | undefined) =>
127
+ setSettingsById((current) => ({
128
+ ...current,
129
+ [domain.id]: isOk(settingsResponse) ? settingsResponse.data : null,
130
+ })),
131
+ );
132
+ }
133
+ };
134
+ loadDomains();
135
+ }, []);
136
+
137
+ /**
138
+ * Abre el modelo de un dominio con sus ajustes y pide por su id las páginas que
139
+ * nombran, para enseñarlas con su título y su marca al día. La que la API ya no da
140
+ * se queda en su sección, señalada. Si la petición falla, no se sabe cuáles se
141
+ * encuentran, y ninguna se señala.
142
+ */
143
+ const openDomain = async (id: number, loaded: LlmsSettings) => {
144
+ openedDomain.current = id;
145
+ setDomainId(id);
146
+ setSaved(loaded);
147
+ setDraft(toDraft(loaded));
148
+ setPages({});
149
+ setArePagesUnread(false);
150
+ setUnreadableId(null);
151
+
152
+ const ids = sectionPageIds(loaded);
153
+ if (ids.length === 0) return;
154
+ const pagesResponse = await domains.getLlmsPages(id, { ids, itemsPerPage: ids.length });
155
+ if (openedDomain.current !== id) return;
156
+ if (!isOk(pagesResponse)) {
157
+ setArePagesUnread(true);
158
+ return;
159
+ }
160
+ const found: LlmsPagesResponse = pagesResponse.data;
161
+ setPages(Object.fromEntries(found.items.map((page) => [page.id, page])));
162
+ };
163
+
164
+ /**
165
+ * Elige un dominio de la lista. Si sus ajustes no llegaron, los vuelve a pedir, y si
166
+ * fallan otra vez no abre nada: abrirlo con los valores por defecto y guardar
167
+ * sustituiría lo guardado. Un reintento que llega cuando el editor ya ha elegido otro
168
+ * dominio no abre nada, para no cambiarle el que tiene abierto.
169
+ */
170
+ const selectDomain = async (id: number) => {
171
+ const selection = ++lastSelection.current;
172
+ const known = settingsById[id];
173
+ if (known) {
174
+ openDomain(id, known);
175
+ return;
176
+ }
177
+ setUnreadableId(null);
178
+ const response = await domains.getLlmsSettings(id);
179
+ if (selection !== lastSelection.current) return;
180
+ if (!isOk(response)) {
181
+ setUnreadableId(id);
182
+ return;
183
+ }
184
+ const loaded: LlmsSettings = response.data;
185
+ setSettingsById((current) => ({ ...current, [id]: loaded }));
186
+ openDomain(id, loaded);
187
+ };
188
+
189
+ const closeDomain = () => {
190
+ openedDomain.current = null;
191
+ setDomainId(null);
192
+ setSaved(null);
193
+ setDraft(null);
194
+ setPages({});
195
+ };
196
+
197
+ const backToList = () => {
198
+ if (isDirty) {
199
+ toggleGuard();
200
+ return;
201
+ }
202
+ closeDomain();
203
+ };
204
+
205
+ const discardChanges = () => {
206
+ toggleGuard();
207
+ closeDomain();
208
+ };
209
+
210
+ // Envía el documento entero —índice y espejo—, porque la API sustituye el guardado
211
+ // sin fusionarlo, y lo que devuelve pasa a ser lo guardado, también en la lista.
212
+ const handleSave = async () => {
213
+ if (settings === null || domainId === null) return;
214
+ setIsSaving(true);
215
+ const response = await domains.updateLlmsSettings(domainId, settings);
216
+ setIsSaving(false);
217
+ if (!isOk(response)) {
218
+ reportError(response);
219
+ return;
220
+ }
221
+ const stored: LlmsSettings = response.data;
222
+ setSaved(stored);
223
+ setSettingsById((current) => ({ ...current, [domainId]: stored }));
224
+ };
225
+
226
+ const updateIndex = useCallback(
227
+ (update: (model: LlmsIndexDraft) => LlmsIndexDraft) =>
228
+ setDraft((current) => (current ? { ...current, index: update(current.index) } : current)),
229
+ [],
230
+ );
231
+
232
+ const setMirrorEnabled = useCallback(
233
+ (enabled: boolean) =>
234
+ setDraft((current) => (current ? { ...current, markdown: { ...current.markdown, enabled } } : current)),
235
+ [],
236
+ );
237
+
238
+ const updateMirror = useCallback(
239
+ (update: (options: MirrorCommonOptions) => MirrorCommonOptions) =>
240
+ setMirror((current) => (current ? update(current) : current)),
241
+ [],
242
+ );
243
+
244
+ /**
245
+ * Escribe las opciones comunes en los ajustes de cada dominio, con su LLM Index Model
246
+ * y si escribe el espejo tal como los tiene guardados. Lo que devuelve cada uno pasa a ser lo guardado, también
247
+ * en la lista. Si alguno falla, se informa, y como ese dominio sigue sin tenerlas, las
248
+ * opciones siguen con cambios sin guardar.
249
+ */
250
+ const handleSaveMirror = async () => {
251
+ if (mirror === null || domainList === null || !canSaveMirror) return;
252
+ setIsSavingMirror(true);
253
+ const responses = await Promise.all(
254
+ domainList.map(async (domain) => {
255
+ const stored = settingsById[domain.id] as LlmsSettings;
256
+ const response = await domains.updateLlmsSettings(domain.id, {
257
+ index: stored.index,
258
+ markdown: { ...mirror, enabled: stored.markdown.enabled },
259
+ });
260
+ return { id: domain.id, response };
261
+ }),
262
+ );
263
+ setIsSavingMirror(false);
264
+ const succeeded = responses.filter(({ response }) => isOk(response));
265
+ setSettingsById((current) => ({
266
+ ...current,
267
+ ...Object.fromEntries(
268
+ succeeded.map(({ id, response }) => [id, (response as AxiosResponse).data as LlmsSettings]),
269
+ ),
270
+ }));
271
+ const failed = responses.find(({ response }) => !isOk(response));
272
+ if (failed) reportError(failed.response);
273
+ };
274
+
275
+ const addPage = useCallback((page: LlmsDomainPage) => setPages((current) => ({ ...current, [page.id]: page })), []);
276
+
277
+ const openDomainItem = domainList?.find((domain) => domain.id === domainId);
278
+ const unreadableDomain = domainList?.find((domain) => domain.id === unreadableId);
279
+
280
+ // En la lista se guardan las opciones comunes del espejo, y con un dominio abierto, el
281
+ // suyo. Una sección sin nombre no se guarda, porque el nombre es obligatorio.
282
+ const rightButtonProps =
283
+ draft !== null
284
+ ? {
285
+ label: isSaving ? "Saving" : isDirty ? "Save" : "Saved",
286
+ disabled: isSaving || !isDirty || hasUnnamedSection(draft.index),
287
+ action: () => handleSave(),
288
+ }
289
+ : mirror !== null
290
+ ? {
291
+ label: isSavingMirror ? "Saving" : isMirrorDirty ? "Save" : "Saved",
292
+ disabled: isSavingMirror || !isMirrorDirty || !canSaveMirror,
293
+ action: () => handleSaveMirror(),
294
+ }
295
+ : undefined;
296
+
297
+ const modalText = (
298
+ <>
299
+ Some LLM settings <strong>are not saved</strong>.{" "}
300
+ </>
301
+ );
302
+
303
+ return (
304
+ <>
305
+ <RouteLeavingGuard
306
+ when={isDirty || isMirrorDirty}
307
+ action={(path: string) => setHistoryPush(path)}
308
+ text={modalText}
309
+ />
310
+ <GuardModal isOpen={isGuardOpen} discardChanges={discardChanges} toggleModal={toggleGuard} />
311
+ <MainWrapper backLink={false} title="SEO Settings" rightButton={rightButtonProps} screen="llms">
312
+ <S.Wrapper>
313
+ <Nav current={currentNavItem} items={navItems} onClick={(path: string) => setHistoryPush(path)} />
314
+ <S.ContentWrapper>
315
+ <ErrorToast />
316
+ {draft && settings && domainId !== null ? (
317
+ <IndexModelEditor
318
+ key={domainId}
319
+ domainName={openDomainItem ? domainLabel(openDomainItem) : `Domain ${domainId}`}
320
+ model={draft.index}
321
+ settings={settings}
322
+ languages={globalLangs}
323
+ pages={pages}
324
+ arePagesUnread={arePagesUnread}
325
+ domainId={domainId}
326
+ isMirrorEnabled={draft.markdown.enabled}
327
+ onUpdate={updateIndex}
328
+ onMirrorEnabledChange={setMirrorEnabled}
329
+ onPageAdded={addPage}
330
+ onBack={backToList}
331
+ />
332
+ ) : (
333
+ <>
334
+ <S.Title>LLMs.txt editor</S.Title>
335
+ <S.Description>
336
+ Model what the llms.txt of each domain says to AI assistants, and how its pages are mirrored as
337
+ markdown.
338
+ </S.Description>
339
+ {unreadableDomain && (
340
+ <S.ErrorText>
341
+ The LLM settings of {domainLabel(unreadableDomain)} could not be read. Try again later.
342
+ </S.ErrorText>
343
+ )}
344
+ {domainList === null && !isListUnreadable && <Loading />}
345
+ {domainList?.length === 0 && <EmptyState message="There are no domains to configure." />}
346
+ {domainList && domainList.length > 0 && (
347
+ <DomainList domains={domainList} settingsById={settingsById} onOpen={selectDomain} />
348
+ )}
349
+ {domainList && domainList.length > 0 && mirror !== null && (
350
+ <MirrorOptions options={mirror} canSave={canSaveMirror} onUpdate={updateMirror} />
351
+ )}
352
+ </>
353
+ )}
354
+ </S.ContentWrapper>
355
+ </S.Wrapper>
356
+ </MainWrapper>
357
+ </>
358
+ );
359
+ };
360
+
361
+ const mapStateToProps = (state: IRootState) => ({
362
+ globalLangs: state.app.globalLangs,
363
+ });
364
+
365
+ const mapDispatchToProps = {
366
+ setHistoryPush: appActions.setHistoryPush,
367
+ handleError: appActions.handleError,
368
+ };
369
+
370
+ interface ILlmsProps {
371
+ navItems: INavItem[];
372
+ currentNavItem: INavItem;
373
+ globalLangs: ILanguage[];
374
+ }
375
+
376
+ interface IDispatchProps {
377
+ setHistoryPush(path: string, isEditor?: boolean): void;
378
+ handleError(response: unknown): void;
379
+ }
380
+
381
+ type IProps = ILlmsProps & IDispatchProps;
382
+
383
+ export default connect(mapStateToProps, mapDispatchToProps)(Llms);