@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,325 @@
1
+ import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
2
+
3
+ import { FieldsBehavior, Icon, ToggleField } from "@ax/components";
4
+ import type { ILanguage, LlmsDomainPage, LlmsIndexText, LlmsSettings } from "@ax/types";
5
+
6
+ import Outline, { type IOutlineSelection } from "../Outline";
7
+ import PagePicker from "../PagePicker";
8
+ import Preview from "../Preview";
9
+ import SectionEditor from "../SectionEditor";
10
+ import * as S from "../style";
11
+ import {
12
+ addSectionPage,
13
+ getTemplateOptions,
14
+ type LlmsIndexDraft,
15
+ moveItem,
16
+ newSectionDraft,
17
+ setFooterContent,
18
+ setIndexText,
19
+ updateAutomatic,
20
+ updateSection,
21
+ } from "../utils";
22
+
23
+ /** Qué busca el buscador de páginas abierto: páginas para una sección manual o ramas para una automática. */
24
+ type IPicker = { kind: "pages" | "branches"; key: string };
25
+
26
+ /** El campo de texto que coge el foco al elegir cada elemento del esquema; la Optional no tiene. */
27
+ const FOCUSED_FIELDS: Partial<Record<IOutlineSelection["kind"], string>> = {
28
+ header: "llmsTitle",
29
+ section: "llmsSectionName",
30
+ footer: "llmsFooterContent",
31
+ };
32
+
33
+ /**
34
+ * El LLM Index Model de un dominio abierto: si publica su llms.txt, el esquema del
35
+ * fichero y, a su lado, el elemento elegido para editarlo. El dominio publica un solo
36
+ * fichero, con un solo texto, y separa sites o idiomas, si quiere, con secciones que
37
+ * filtran por ellos (ADR 0018).
38
+ */
39
+ const IndexModelEditor = (props: IProps): JSX.Element => {
40
+ const {
41
+ domainName,
42
+ model,
43
+ settings,
44
+ languages,
45
+ pages,
46
+ arePagesUnread,
47
+ domainId,
48
+ isMirrorEnabled,
49
+ onUpdate,
50
+ onMirrorEnabledChange,
51
+ onPageAdded,
52
+ onBack,
53
+ } = props;
54
+
55
+ const [selected, setSelected] = useState<IOutlineSelection>({ kind: "header" });
56
+ const [picker, setPicker] = useState<IPicker | null>(null);
57
+ const [isPreviewOpen, setIsPreviewOpen] = useState(false);
58
+ // El campo al que dar el foco cuando se pinte lo que el editor acaba de elegir.
59
+ const [focusRequest, setFocusRequest] = useState<{ field: string } | null>(null);
60
+ const bodyRef = useRef<HTMLDivElement>(null);
61
+ const templates = useMemo(getTemplateOptions, []);
62
+
63
+ // Después de pintarlo: lo elegido puede no estar todavía en pantalla cuando se elige.
64
+ useEffect(() => {
65
+ if (focusRequest) bodyRef.current?.querySelector<HTMLElement>(`[name="${focusRequest.field}"]`)?.focus();
66
+ }, [focusRequest]);
67
+
68
+ /** Abre a su lado lo elegido en el esquema y pide el foco para su campo de texto, si lo tiene. */
69
+ const choose = (item: IOutlineSelection) => {
70
+ setSelected(item);
71
+ const field = FOCUSED_FIELDS[item.kind];
72
+ if (field) setFocusRequest({ field });
73
+ };
74
+
75
+ const breadcrumb = (
76
+ <S.Breadcrumb aria-label="Breadcrumb">
77
+ <S.BreadcrumbLink type="button" onClick={onBack}>
78
+ LLMs.txt editor
79
+ </S.BreadcrumbLink>
80
+ <Icon name="right-arrow" size="16" />
81
+ <span aria-current="page">{domainName}</span>
82
+ </S.Breadcrumb>
83
+ );
84
+
85
+ const section = selected.kind === "section" ? model.sections.find((item) => item.key === selected.key) : undefined;
86
+ const { optionalSection } = model;
87
+ // Una sección quitada deja de estar abierta, y se abre el texto del índice.
88
+ const current: IOutlineSelection = selected.kind === "section" && !section ? { kind: "header" } : selected;
89
+
90
+ const setText = (field: keyof LlmsIndexText) => (value: string) =>
91
+ onUpdate((currentModel) => setIndexText(currentModel, field, value));
92
+
93
+ /**
94
+ * El título, el resumen y el detalle del encabezado. El título no es obligatorio: sin
95
+ * él, el LLM Index lleva el nombre del dominio, y el campo dice cuál.
96
+ */
97
+ const renderTextFields = () => (
98
+ <>
99
+ <FieldsBehavior
100
+ title="Title"
101
+ name="llmsTitle"
102
+ fieldType="TextField"
103
+ value={model.texts.title ?? ""}
104
+ onChange={setText("title")}
105
+ placeholder="e.g. Example University"
106
+ helptext={`If left empty, the domain name is used: ${domainName}.`}
107
+ />
108
+ <FieldsBehavior
109
+ title="Summary"
110
+ name="llmsSummary"
111
+ fieldType="TextArea"
112
+ value={model.texts.summary ?? ""}
113
+ onChange={setText("summary")}
114
+ placeholder="e.g. Degrees, masters and research programmes"
115
+ rows={2}
116
+ />
117
+ <FieldsBehavior
118
+ title="Detail"
119
+ name="llmsDetail"
120
+ fieldType="TextArea"
121
+ value={model.texts.detail ?? ""}
122
+ onChange={setText("detail")}
123
+ placeholder="e.g. Admissions open in March; fees are on each programme page"
124
+ rows={4}
125
+ />
126
+ </>
127
+ );
128
+
129
+ const addSection = () => {
130
+ const added = newSectionDraft();
131
+ onUpdate((currentModel) => ({ ...currentModel, sections: [...currentModel.sections, added] }));
132
+ choose({ kind: "section", key: added.key });
133
+ };
134
+
135
+ const moveSection = (from: number, to: number) =>
136
+ onUpdate((currentModel) => ({ ...currentModel, sections: moveItem(currentModel.sections, from, to) }));
137
+
138
+ const removeSection = (key: string) =>
139
+ onUpdate((currentModel) => ({
140
+ ...currentModel,
141
+ sections: currentModel.sections.filter((item) => item.key !== key),
142
+ }));
143
+
144
+ const addPickedPage = (page: LlmsDomainPage) => {
145
+ if (picker === null) return;
146
+ onPageAdded(page);
147
+ onUpdate((currentModel) =>
148
+ updateSection(currentModel, picker.key, (item) =>
149
+ picker.kind === "pages"
150
+ ? addSectionPage(item, page.id)
151
+ : updateAutomatic(item, (automatic) => ({
152
+ ...automatic,
153
+ filters: automatic.filters.map((filter) =>
154
+ filter.axis === "branch" && !filter.values.includes(page.id)
155
+ ? { ...filter, values: [...filter.values, page.id] }
156
+ : filter,
157
+ ),
158
+ })),
159
+ ),
160
+ );
161
+ };
162
+
163
+ const pickedIds = (() => {
164
+ const target = picker && [...model.sections, optionalSection].find((item) => item.key === picker.key);
165
+ if (!target || !picker) return [];
166
+ if (picker.kind === "pages") return target.pages;
167
+
168
+ return target.automatic.filters.flatMap((filter) => (filter.axis === "branch" ? filter.values : []));
169
+ })();
170
+
171
+ const renderInspector = (): ReactNode => {
172
+ if (current.kind === "section" && section) {
173
+ return (
174
+ <SectionEditor
175
+ key={section.key}
176
+ section={section}
177
+ position={model.sections.indexOf(section)}
178
+ languages={languages}
179
+ pages={pages}
180
+ arePagesUnread={arePagesUnread}
181
+ domainId={domainId}
182
+ settings={settings}
183
+ templates={templates}
184
+ onUpdate={(update) => onUpdate((currentModel) => updateSection(currentModel, section.key, update))}
185
+ onRemove={() => removeSection(section.key)}
186
+ onAddPages={() => setPicker({ kind: "pages", key: section.key })}
187
+ onAddBranches={() => setPicker({ kind: "branches", key: section.key })}
188
+ />
189
+ );
190
+ }
191
+ if (current.kind === "optional") {
192
+ return (
193
+ <SectionEditor
194
+ key={optionalSection.key}
195
+ section={optionalSection}
196
+ position={null}
197
+ languages={languages}
198
+ pages={pages}
199
+ arePagesUnread={arePagesUnread}
200
+ domainId={domainId}
201
+ settings={settings}
202
+ templates={templates}
203
+ onUpdate={(update) => onUpdate((currentModel) => updateSection(currentModel, optionalSection.key, update))}
204
+ onAddPages={() => setPicker({ kind: "pages", key: optionalSection.key })}
205
+ onAddBranches={() => setPicker({ kind: "branches", key: optionalSection.key })}
206
+ />
207
+ );
208
+ }
209
+ if (current.kind === "footer") {
210
+ return (
211
+ <S.Inspector aria-label="Footer">
212
+ <S.InspectorHeader>
213
+ <S.InspectorTitle>Footer</S.InspectorTitle>
214
+ </S.InspectorHeader>
215
+ <div>
216
+ <FieldsBehavior
217
+ title="Content"
218
+ name="llmsFooterContent"
219
+ fieldType="TextArea"
220
+ value={model.footer.content ?? ""}
221
+ onChange={(value: string) => onUpdate((currentModel) => setFooterContent(currentModel, value))}
222
+ placeholder={"## Contact\nWrite to info@example.edu"}
223
+ rows={6}
224
+ helptext="To make it a section of its own, start it with a heading such as «## Contact»; otherwise it reads as part of the last section."
225
+ />
226
+ </div>
227
+ <S.Note>It closes the llms.txt, after the Optional section.</S.Note>
228
+ </S.Inspector>
229
+ );
230
+ }
231
+
232
+ return (
233
+ <S.Inspector aria-label="Header">
234
+ <S.InspectorHeader>
235
+ <S.InspectorTitle>Header</S.InspectorTitle>
236
+ </S.InspectorHeader>
237
+ <div>
238
+ {renderTextFields()}
239
+ <FieldsBehavior
240
+ title=""
241
+ name="llmsIncludeGeneratedAt"
242
+ fieldType="UniqueCheck"
243
+ value={model.includeGeneratedAt}
244
+ options={[{ title: "Include the generation date" }]}
245
+ onChange={(value: boolean) => onUpdate((currentModel) => ({ ...currentModel, includeGeneratedAt: value }))}
246
+ />
247
+ </div>
248
+ </S.Inspector>
249
+ );
250
+ };
251
+
252
+ return (
253
+ <>
254
+ {breadcrumb}
255
+ <S.EditorHeader>
256
+ <S.EditorTitle title={domainName}>{domainName}</S.EditorTitle>
257
+ <S.HeaderToggle>
258
+ Publish the llms.txt
259
+ <ToggleField
260
+ name="llmsEnabled"
261
+ value={model.enabled}
262
+ onChange={(value: boolean) => onUpdate((currentModel) => ({ ...currentModel, enabled: value }))}
263
+ />
264
+ </S.HeaderToggle>
265
+ <S.HeaderToggle>
266
+ Write markdown mirrors
267
+ <ToggleField name="markdownEnabled" value={isMirrorEnabled} onChange={onMirrorEnabledChange} />
268
+ </S.HeaderToggle>
269
+ </S.EditorHeader>
270
+ {arePagesUnread && (
271
+ <S.ErrorText>
272
+ The chosen pages could not be loaded: they show by their ID, without their title or whether they will reach
273
+ the llms.txt.
274
+ </S.ErrorText>
275
+ )}
276
+ <S.EditorBody ref={bodyRef}>
277
+ <Outline
278
+ model={model}
279
+ selected={current}
280
+ onSelect={choose}
281
+ onMove={moveSection}
282
+ onAddSection={addSection}
283
+ onPreview={() => setIsPreviewOpen(true)}
284
+ />
285
+ {renderInspector()}
286
+ </S.EditorBody>
287
+ {isPreviewOpen && <Preview domainId={domainId} settings={settings} toggleModal={() => setIsPreviewOpen(false)} />}
288
+ {picker !== null && (
289
+ <PagePicker
290
+ title={picker.kind === "pages" ? "Add pages" : "Add branches"}
291
+ isOpen
292
+ toggleModal={() => setPicker(null)}
293
+ domainId={domainId}
294
+ selectedIds={pickedIds}
295
+ onAdd={addPickedPage}
296
+ />
297
+ )}
298
+ </>
299
+ );
300
+ };
301
+
302
+ interface IProps {
303
+ /** El nombre con que el dominio sale en la lista. */
304
+ domainName: string;
305
+ model: LlmsIndexDraft;
306
+ /** Los ajustes que el editor tiene en pantalla, en la forma del contrato. */
307
+ settings: LlmsSettings;
308
+ /** Los idiomas de la instancia, que el filtro por idioma ofrece todos. */
309
+ languages: ILanguage[];
310
+ /** Lo que la API da de cada página elegida: su título, su dirección y su marca. */
311
+ pages: Record<number, LlmsDomainPage>;
312
+ /** Si no se pudieron pedir: una página que falta en `pages` no se sabe si se encuentra. */
313
+ arePagesUnread: boolean;
314
+ domainId: number;
315
+ /** Si el dominio escribe espejos markdown: lo único del espejo que se decide por dominio. */
316
+ isMirrorEnabled: boolean;
317
+ onUpdate(update: (model: LlmsIndexDraft) => LlmsIndexDraft): void;
318
+ onMirrorEnabledChange(enabled: boolean): void;
319
+ /** Una página recién elegida en el buscador, para enseñarla sin volver a pedirla. */
320
+ onPageAdded(page: LlmsDomainPage): void;
321
+ /** Vuelve a la lista de dominios. */
322
+ onBack(): void;
323
+ }
324
+
325
+ export default IndexModelEditor;
@@ -0,0 +1,61 @@
1
+ import * as S from "../style";
2
+ import type { MirrorCommonOptions } from "../utils";
3
+
4
+ /** La página ficticia del ejemplo y las dos a las que enlaza. */
5
+ const ORIGIN = "https://www.example.edu";
6
+ const PAGE = `${ORIGIN}/degrees/`;
7
+ const HOME = `${ORIGIN}/`;
8
+ const ADMISSIONS = `${ORIGIN}/admissions/`;
9
+
10
+ /**
11
+ * El espejo markdown de la página ficticia con estas opciones, con la forma que le da el
12
+ * render: la cabecera YAML, la sección de navegación, el contenido y, cuando se convierte
13
+ * la página entera, su pie, en ese orden, y los enlaces internos absolutos, al espejo de
14
+ * la otra página o a la página misma.
15
+ */
16
+ const exampleMarkdown = (options: MirrorCommonOptions): string => {
17
+ const link = (url: string) => (options.linkToMarkdown ? `${url}index.md` : url);
18
+ const parts = [
19
+ options.frontMatter &&
20
+ ["---", 'title: "Degrees"', `url: "${PAGE}"`, 'locale: "en"', 'site: "Example University"', "---"].join("\n"),
21
+ options.includeNav &&
22
+ ["## Navigation", "", `- [Home](${link(HOME)})`, `- [Admissions](${link(ADMISSIONS)})`].join("\n"),
23
+ ["# Degrees", "", `Explore our programmes and read how to [apply](${link(ADMISSIONS)}).`].join("\n"),
24
+ !options.mainOnly && "© Example University · All rights reserved",
25
+ ];
26
+
27
+ return parts.filter(Boolean).join("\n\n");
28
+ };
29
+
30
+ /** Las relaciones que la página ficticia anuncia en su `<head>` con estas opciones. */
31
+ const exampleHead = (options: MirrorCommonOptions): string =>
32
+ options.discoveryLinks
33
+ ? [
34
+ `<link rel="alternate" type="text/markdown" href="${PAGE}index.md">`,
35
+ `<link rel="describedby" type="text/plain" href="${ORIGIN}/llms.txt">`,
36
+ ].join("\n")
37
+ : "The page announces no discovery links.";
38
+
39
+ /**
40
+ * Un ejemplo de cómo quedan con las opciones en pantalla el espejo markdown de una
41
+ * página ficticia y lo que anuncia su `<head>`, para entender cada opción antes de
42
+ * guardar. Ilustra: no convierte nada ni pide nada a la API.
43
+ */
44
+ const MirrorExample = (props: IProps): JSX.Element => {
45
+ const { options } = props;
46
+
47
+ return (
48
+ <S.MirrorExample aria-label="Markdown mirror example">
49
+ <S.FieldLabel>Example: {PAGE}index.md</S.FieldLabel>
50
+ <S.ExampleContent data-testid="llms-mirror-example-markdown">{exampleMarkdown(options)}</S.ExampleContent>
51
+ <S.FieldLabel>In the page's head</S.FieldLabel>
52
+ <S.ExampleContent data-testid="llms-mirror-example-head">{exampleHead(options)}</S.ExampleContent>
53
+ </S.MirrorExample>
54
+ );
55
+ };
56
+
57
+ interface IProps {
58
+ options: MirrorCommonOptions;
59
+ }
60
+
61
+ export default MirrorExample;
@@ -0,0 +1,82 @@
1
+ import { FieldsBehavior } from "@ax/components";
2
+
3
+ import MirrorExample from "../MirrorExample";
4
+ import * as S from "../style";
5
+ import type { MirrorCommonOptions } from "../utils";
6
+
7
+ /**
8
+ * Qué conserva el espejo markdown de cada página y cómo quedan sus enlaces internos:
9
+ * unas opciones comunes a todos los dominios, que se editan junto a su lista y se
10
+ * guardan en los ajustes de cada uno. Se editan siempre, la escriba o no cada dominio:
11
+ * eso se decide en el dominio abierto. A su derecha, un ejemplo enseña qué hace cada
12
+ * una. Las imágenes y la forma de los enlaces internos no se enseñan: van siempre con el
13
+ * mismo valor (`toDraft`).
14
+ */
15
+ const MirrorOptions = (props: IProps): JSX.Element => {
16
+ const { options, canSave, onUpdate } = props;
17
+
18
+ const setOption =
19
+ <K extends keyof MirrorCommonOptions>(key: K) =>
20
+ (value: MirrorCommonOptions[K]) =>
21
+ onUpdate((current) => ({ ...current, [key]: value }));
22
+
23
+ return (
24
+ <S.MirrorPanel aria-label="Markdown mirror">
25
+ <S.MirrorBody>
26
+ <div>
27
+ <S.BlockTitle>Markdown mirror</S.BlockTitle>
28
+ {!canSave && (
29
+ <S.ErrorText>
30
+ The markdown mirror options can only be saved once the settings of every domain have been read.
31
+ </S.ErrorText>
32
+ )}
33
+ <FieldsBehavior
34
+ title="Only the page's main content"
35
+ name="markdownMainOnly"
36
+ fieldType="ToggleField"
37
+ value={options.mainOnly}
38
+ onChange={setOption("mainOnly")}
39
+ />
40
+ <FieldsBehavior
41
+ title="Keep the navigation"
42
+ name="markdownIncludeNav"
43
+ fieldType="ToggleField"
44
+ value={options.includeNav}
45
+ onChange={setOption("includeNav")}
46
+ />
47
+ <FieldsBehavior
48
+ title="Metadata header"
49
+ name="markdownFrontMatter"
50
+ fieldType="ToggleField"
51
+ value={options.frontMatter}
52
+ onChange={setOption("frontMatter")}
53
+ />
54
+ <FieldsBehavior
55
+ title="Discovery links in the page head"
56
+ name="markdownDiscoveryLinks"
57
+ fieldType="ToggleField"
58
+ value={options.discoveryLinks}
59
+ onChange={setOption("discoveryLinks")}
60
+ />
61
+ <FieldsBehavior
62
+ title="Internal links point to the other page's markdown mirror"
63
+ name="markdownLinkToMarkdown"
64
+ fieldType="ToggleField"
65
+ value={options.linkToMarkdown}
66
+ onChange={setOption("linkToMarkdown")}
67
+ />
68
+ </div>
69
+ <MirrorExample options={options} />
70
+ </S.MirrorBody>
71
+ </S.MirrorPanel>
72
+ );
73
+ };
74
+
75
+ interface IProps {
76
+ options: MirrorCommonOptions;
77
+ /** Si ya se leyeron los ajustes de todos los dominios: sin ellos, guardar les borraría su índice. */
78
+ canSave: boolean;
79
+ onUpdate(update: (options: MirrorCommonOptions) => MirrorCommonOptions): void;
80
+ }
81
+
82
+ export default MirrorOptions;
@@ -0,0 +1,183 @@
1
+ import { Button, Icon, IconAction, Tooltip } from "@ax/components";
2
+
3
+ import {
4
+ closestCenter,
5
+ DndContext,
6
+ type DragEndEvent,
7
+ KeyboardSensor,
8
+ PointerSensor,
9
+ useSensor,
10
+ useSensors,
11
+ } from "@dnd-kit/core";
12
+ import {
13
+ SortableContext,
14
+ sortableKeyboardCoordinates,
15
+ useSortable,
16
+ verticalListSortingStrategy,
17
+ } from "@dnd-kit/sortable";
18
+ import { CSS } from "@dnd-kit/utilities";
19
+
20
+ import * as S from "../style";
21
+ import { type LlmsIndexDraft, type LlmsSectionDraft, sectionSummary, sectionTitle } from "../utils";
22
+
23
+ /** El elemento del esquema que está abierto al lado para editarse. */
24
+ type IOutlineSelection =
25
+ | { kind: "header" }
26
+ | { kind: "section"; key: string }
27
+ | { kind: "optional" }
28
+ | { kind: "footer" };
29
+
30
+ /**
31
+ * Un elemento del esquema que no se arrastra: su título, su resumen y si está abierto.
32
+ * El encabezado, la Optional y el pie, que ocupan siempre su sitio en el fichero, se marcan como fijos.
33
+ */
34
+ const OutlineEntry = (props: IEntryProps): JSX.Element => {
35
+ const { title, summary, selected, onSelect, testId, fixed = false } = props;
36
+
37
+ return (
38
+ <S.OutlineItem selected={selected} fixed={fixed} data-testid={testId}>
39
+ <S.DragHandle />
40
+ <S.OutlineButton type="button" aria-current={selected || undefined} onClick={onSelect}>
41
+ <S.OutlineTitle fixed={fixed}>{title}</S.OutlineTitle>
42
+ <S.OutlineSummary>{summary}</S.OutlineSummary>
43
+ </S.OutlineButton>
44
+ </S.OutlineItem>
45
+ );
46
+ };
47
+
48
+ /** Una sección en el esquema, con el asa por la que se arrastra para reordenarla. */
49
+ const SortableSection = (props: ISectionProps): JSX.Element => {
50
+ const { section, title, selected, onSelect } = props;
51
+ const { attributes, listeners, setNodeRef, transform, transition } = useSortable({ id: section.key });
52
+
53
+ return (
54
+ <S.OutlineItem
55
+ ref={setNodeRef}
56
+ selected={selected}
57
+ style={{ transform: CSS.Transform.toString(transform), transition }}
58
+ data-testid="llms-outline-section"
59
+ >
60
+ <S.DragHandle {...attributes} {...listeners} aria-label={`Reorder ${title}`}>
61
+ <Icon name="drag" size="16" />
62
+ </S.DragHandle>
63
+ <S.OutlineButton type="button" aria-current={selected || undefined} onClick={onSelect}>
64
+ <S.OutlineTitle>{title}</S.OutlineTitle>
65
+ <S.OutlineSummary>{sectionSummary(section)}</S.OutlineSummary>
66
+ </S.OutlineButton>
67
+ </S.OutlineItem>
68
+ );
69
+ };
70
+
71
+ /**
72
+ * El esquema del LLM Index Model con la forma del fichero: el texto con que abre, sus
73
+ * secciones en orden, con el botón que añade otra justo debajo, la Optional y el pie con
74
+ * que cierra. Cada elemento lleva su resumen, y elegirlo lo abre al lado. Las secciones
75
+ * se reordenan arrastrándolas. En su esquina, el ojo abre la previsualización.
76
+ */
77
+ const Outline = (props: IProps): JSX.Element => {
78
+ const { model, selected, onSelect, onMove, onAddSection, onPreview } = props;
79
+
80
+ const sensors = useSensors(
81
+ useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
82
+ useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
83
+ );
84
+
85
+ const keys = model.sections.map((section) => section.key);
86
+
87
+ const handleDragEnd = ({ active, over }: DragEndEvent) => {
88
+ if (!over || active.id === over.id) return;
89
+ onMove(keys.indexOf(String(active.id)), keys.indexOf(String(over.id)));
90
+ };
91
+
92
+ const isSelected = (kind: IOutlineSelection["kind"], key?: string) =>
93
+ selected.kind === kind && (selected.kind !== "section" || selected.key === key);
94
+
95
+ return (
96
+ <S.Outline aria-label="Index outline">
97
+ <S.OutlineHeader>
98
+ <S.OutlineGroupTitle>LLM index</S.OutlineGroupTitle>
99
+ <Tooltip content="Preview llms.txt" bottom>
100
+ <IconAction icon="view" size="s" onClick={onPreview} />
101
+ </Tooltip>
102
+ </S.OutlineHeader>
103
+ <S.OutlineList>
104
+ <OutlineEntry
105
+ title="Header"
106
+ fixed
107
+ summary={`Title, summary and detail${model.includeGeneratedAt ? " · Generation date" : ""}`}
108
+ selected={isSelected("header")}
109
+ onSelect={() => onSelect({ kind: "header" })}
110
+ testId="llms-outline-header"
111
+ />
112
+ </S.OutlineList>
113
+ <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
114
+ <SortableContext items={keys} strategy={verticalListSortingStrategy}>
115
+ <S.OutlineList>
116
+ {model.sections.map((section) => (
117
+ <SortableSection
118
+ key={section.key}
119
+ section={section}
120
+ title={sectionTitle(section)}
121
+ selected={isSelected("section", section.key)}
122
+ onSelect={() => onSelect({ kind: "section", key: section.key })}
123
+ />
124
+ ))}
125
+ </S.OutlineList>
126
+ </SortableContext>
127
+ </DndContext>
128
+ <S.OutlineActions>
129
+ <Button type="button" buttonStyle="text" icon="add" onClick={onAddSection}>
130
+ Add section
131
+ </Button>
132
+ </S.OutlineActions>
133
+ <S.OutlineList>
134
+ <OutlineEntry
135
+ title={sectionTitle(model.optionalSection)}
136
+ fixed
137
+ summary={sectionSummary(model.optionalSection)}
138
+ selected={isSelected("optional")}
139
+ onSelect={() => onSelect({ kind: "optional" })}
140
+ testId="llms-outline-optional"
141
+ />
142
+ <OutlineEntry
143
+ title="Footer"
144
+ fixed
145
+ summary="Markdown"
146
+ selected={isSelected("footer")}
147
+ onSelect={() => onSelect({ kind: "footer" })}
148
+ testId="llms-outline-footer"
149
+ />
150
+ </S.OutlineList>
151
+ </S.Outline>
152
+ );
153
+ };
154
+
155
+ interface IEntryProps {
156
+ title: string;
157
+ summary: string;
158
+ selected: boolean;
159
+ onSelect(): void;
160
+ testId: string;
161
+ /** Si es el encabezado, la Optional o el pie, que no se mueven. */
162
+ fixed?: boolean;
163
+ }
164
+
165
+ interface ISectionProps {
166
+ section: LlmsSectionDraft;
167
+ title: string;
168
+ selected: boolean;
169
+ onSelect(): void;
170
+ }
171
+
172
+ interface IProps {
173
+ model: LlmsIndexDraft;
174
+ selected: IOutlineSelection;
175
+ onSelect(selection: IOutlineSelection): void;
176
+ onMove(from: number, to: number): void;
177
+ onAddSection(): void;
178
+ /** Abre la previsualización del llms.txt con lo que hay en pantalla. */
179
+ onPreview(): void;
180
+ }
181
+
182
+ export type { IOutlineSelection };
183
+ export default Outline;