diff --git a/docs/regulations/README.md b/docs/regulations/README.md index 2d0b380..d1d2e1e 100644 --- a/docs/regulations/README.md +++ b/docs/regulations/README.md @@ -96,6 +96,14 @@ function, so no IdP token reaches the browser), asked again on every reconnect. for a source hash) and `state` (the draft froze or reopened: the editor drops its provider and Y.Doc and connects again with a new ticket). The server inserts missing node ids about 1.5 s after typing stops. +**Files.** Editors add a file ("Nuovo file") or remove one ("Elimina il file", never the main file) in the Y.Doc +itself, so every member sees it at once and the history keeps it. A new file goes only in a folder of the document's +`sources` globs (`drafts.files` returns them: the RRI's `regolamenti/*.tex`); its name follows the title until edited, +a regolamento starts with `\regolamento{Titolo}`, and "Includilo in RRI.tex" adds `\input` after the main file's last +one, in its style (`\newpage`, `./`, `.tex`). Removing a file also removes the lines that include it. The backend +reports a file outside the globs as a problem (`stray_file`) and refuses to send to approval, rectify or publish with +one. Logic: `editor/draft-files.ts`. + ## Agent mode `regulations.fake.server.ts` answers every procedure with the backend's rules over an in-memory store (seeded by @@ -134,7 +142,6 @@ creation (its fake GitHub merges a pull request after a few seconds), uploads, t ## Known gaps -- The editor lists and switches the source files but doesn't add, rename or remove them; new regolamenti go in an - existing file until it does. +- The editor adds and removes source files but doesn't rename them: a rename is a new file and the old one removed. - The pagination of shared tables stays English (no Regolamenti table pages yet); `DataTable` takes `locale="it"` for its own words ("Azioni", "Apri …"). diff --git a/src/features/regulations/editor/draft-files.ts b/src/features/regulations/editor/draft-files.ts new file mode 100644 index 0000000..bc5eea4 --- /dev/null +++ b/src/features/regulations/editor/draft-files.ts @@ -0,0 +1,164 @@ +/** + * Adding and removing a draft's source files. The backend allows only paths matching the document's `sources` globs + * (documents.json, e.g. `RRI.tex` and `regolamenti/*.tex`): anything else blocks the approval. + */ + +/** Whether `path` matches a documents.json source glob (`*` within one path segment, `**` across segments). */ +export function matchesGlob(path: string, glob: string): boolean { + const pattern = glob + .split("**") + .map((part) => + part + .replace(/[.+^${}()|[\]\\]/g, "\\$&") + .replace(/\*/g, "[^/]*") + .replace(/\?/g, "[^/]") + ) + .join(".*") + return new RegExp(`^${pattern}$`).test(path) +} + +/** A path the document accepts: no globs means anywhere. */ +export function allowedPath(path: string, sources: string[]) { + return sources.length === 0 || sources.some((glob) => matchesGlob(path, glob)) +} + +/** + * The folders a new file can go in: those of the globs with a wildcard in the file name only (`regolamenti/*.tex` → + * `regolamenti/`), in the order of the globs. `""` is the document's own folder. + */ +export function newFileFolders(sources: string[]): string[] { + if (sources.length === 0) return [""] + const folders: string[] = [] + for (const glob of sources) { + const slash = glob.lastIndexOf("/") + const folder = slash === -1 ? "" : glob.slice(0, slash + 1) + if (!/[*?]/.test(glob.slice(slash + 1)) || /[*?]/.test(folder)) continue + if (!folders.includes(folder)) folders.push(folder) + } + return folders +} + +/** A file name from a title, like the RRI's (`condotta_generale`): lowercase letters, digits and underscores. */ +export function fileNameFromTitle(title: string) { + return title + .normalize("NFD") + .replace(/[̀-ͯ]/g, "") + .toLowerCase() + .replace(/[^a-z0-9]+/g, "_") + .replace(/^_+|_+$/g, "") + .slice(0, 60) + .replace(/_+$/, "") +} + +export const FILE_NAME = /^[A-Za-z0-9][A-Za-z0-9_-]*$/ + +/** The new file's path: the folder, the name, `.tex`. */ +export function newFilePath(folder: string, name: string) { + return `${folder}${name.trim().replace(/\.tex$/i, "")}.tex` +} + +/** The main file: the one with `\documentclass`. */ +export function entryFile(files: Record) { + return Object.keys(files).find((file) => /\\documentclass/.test(files[file] ?? "")) ?? null +} + +/** The main file uses the class `polinetwork-regolamento`: each new file is a regolamento of the raccolta. */ +export function isRegolamento(entryText: string) { + return /\\documentclass(\[[^\]]*\])?\{polinetwork-regolamento\}/.test(entryText) +} + +/** A regolamento's new file starts with its `\regolamento`; any other starts empty. */ +export function starterText(entryText: string, title: string) { + return isRegolamento(entryText) && title.trim() ? `\\regolamento{${escapeLatex(title.trim())}}\n\n` : "" +} + +const LATEX_SPECIALS = new Map([ + ["\\", "\\textbackslash{}"], + ["&", "\\&"], + ["%", "\\%"], + ["$", "\\$"], + ["#", "\\#"], + ["_", "\\_"], + ["{", "\\{"], + ["}", "\\}"], + ["~", "\\textasciitilde{}"], + ["^", "\\textasciicircum{}"], +]) + +/** Plain text as LaTeX: the characters LaTeX reads as commands come out as themselves. */ +export function escapeLatex(text: string) { + return text.replace(/[\\&%$#_{}~^]/g, (char) => LATEX_SPECIALS.get(char) ?? char) +} + +/** The `\input`s outside comments (after an unescaped `%` on their line). */ +function activeInputs(text: string) { + return [...text.matchAll(INPUT)].filter((match) => { + const index = match.index ?? 0 + const line = text.slice(text.lastIndexOf("\n", index - 1) + 1, index) + return !/(^|[^\\])(\\\\)*%/.test(line) + }) +} + +const INPUT = /\\(?:input|include)\{([^}]*)\}/g + +/** + * Where to include `path` in the main file: after its last `\input`, in the same style (`./`, `.tex`, a `\newpage` + * before it when the last one has one), or before `\end{document}`. `null` when there's neither. + */ +export function inputInsertion(entryText: string, path: string): { offset: number; text: string } | null { + const last = activeInputs(entryText).at(-1) + if (last?.index !== undefined) { + const target = last[1] + const reference = `${target.startsWith("./") ? "./" : ""}${target.endsWith(".tex") ? path : path.replace(/\.tex$/, "")}` + const lineStart = entryText.lastIndexOf("\n", last.index) + 1 + const indent = /^[ \t]*/.exec(entryText.slice(lineStart))?.[0] ?? "" + const before = entryText.slice(0, lineStart).replace(/\n[ \t]*$/, "") + const newpage = /\\newpage[ \t]*$/.test(before) || /\\clearpage[ \t]*$/.test(before) + const end = last.index + last[0].length + return { + offset: end, + text: `\n\n${newpage ? `${indent}\\newpage\n` : ""}${indent}\\input{${reference}}`, + } + } + const endDocument = entryText.indexOf("\\end{document}") + if (endDocument === -1) return null + return { offset: endDocument, text: `\\input{./${path}}\n\n` } +} + +/** The `\input` lines that include `path`, from the end so the ranges stay valid while deleting them in order. */ +export function inputLinesOf(text: string, path: string): { from: number; to: number }[] { + const bare = path.replace(/\.tex$/, "") + const ranges: { from: number; to: number }[] = [] + for (const match of activeInputs(text)) { + const target = match[1] + .trim() + .replace(/^\.\//, "") + .replace(/\.tex$/, "") + if (target !== bare || match.index === undefined) continue + const lineStart = text.lastIndexOf("\n", match.index) + 1 + const newline = text.indexOf("\n", match.index) + const lineEnd = newline === -1 ? text.length : newline + 1 + // Only a line holding nothing else goes whole, with the `\newpage` line before it and the blank line before + // that (what "Nuovo file" adds); otherwise just the command. + const whole = text.slice(lineStart, lineEnd).trim() === match[0] + if (!whole) { + ranges.push({ from: match.index, to: match.index + match[0].length }) + continue + } + let from = lineStart + const previous = lineBefore(text, from) + if (previous !== null && /^[ \t]*\\(newpage|clearpage)[ \t]*$/.test(text.slice(previous, from - 1))) { + from = previous + const blank = lineBefore(text, from) + if (blank !== null && text.slice(blank, from - 1).trim() === "") from = blank + } + ranges.push({ from, to: lineEnd }) + } + return ranges.reverse() +} + +/** Where the line before the one starting at `lineStart` starts, or `null` on the first line. */ +function lineBefore(text: string, lineStart: number) { + if (lineStart === 0) return null + return text.lastIndexOf("\n", lineStart - 2) + 1 +} diff --git a/src/features/regulations/editor/editor-page.tsx b/src/features/regulations/editor/editor-page.tsx index 982f190..9d1796c 100644 --- a/src/features/regulations/editor/editor-page.tsx +++ b/src/features/regulations/editor/editor-page.tsx @@ -1,9 +1,19 @@ import type { Diagnostic } from "@codemirror/lint" import { getRouteApi, Link, useRouter } from "@tanstack/react-router" import { useServerFn } from "@tanstack/react-start" -import { ChevronDown, CircleAlert, History, MessageSquarePlus, MessagesSquare, Share2, Workflow } from "lucide-react" +import { + ChevronDown, + CircleAlert, + FilePlus, + History, + MessageSquarePlus, + MessagesSquare, + Share2, + Trash2, + Workflow, +} from "lucide-react" import { useCallback, useEffect, useMemo, useRef, useState } from "react" -import type * as Y from "yjs" +import * as Y from "yjs" import { AvatarGroup, @@ -19,7 +29,7 @@ import { SegmentedControl, Spinner, } from "@/components/primitives" -import { PageBar, PageContent } from "@/components/shell" +import { appToast, PageBar, PageContent } from "@/components/shell" import { Button } from "@/components/ui/button" import { useFillHeight } from "@/features/esign/use-fill-height" import { cn } from "@/lib/utils" @@ -41,6 +51,8 @@ import { getCompileStatus, getDraftFiles, getDraftPdf } from "../regulations.fun import { type CodeEditorHandle, CodeEditor, type EditorMode } from "./code-editor" import { type CommentRange, encodePosition, resolveAnchor } from "./comment-marks" import { CommentsPanel, type PendingAnchor, useCommentThreads } from "./comments-panel" +import { entryFile, inputInsertion, inputLinesOf, isRegolamento, starterText } from "./draft-files" +import { DeleteFileDialog, type NewFile, NewFileDialog } from "./file-dialogs" import { HistoryPanel, SnapshotCompare } from "./history-panel" import { PdfPane } from "./pdf-pane" import { EditorSidebar } from "./sidebar" @@ -70,6 +82,7 @@ export function EditorPage({ draft, members }: { draft: Draft; members: Assignme const [compile, setCompile] = useState(null) const [pdf, setPdf] = useState<{ hash: string; bytes: Uint8Array } | null>(null) const [issues, setIssues] = useState([]) + const [sources, setSources] = useState(null) const refreshCompile = useCallback(async () => { try { setCompile(await loadStatus({ data: { draftId: draft.id } })) @@ -79,7 +92,9 @@ export function EditorPage({ draft, members }: { draft: Draft; members: Assignme }, [draft.id, loadStatus]) const refreshIssues = useCallback(async () => { try { - setIssues((await loadFiles({ data: { draftId: draft.id } })).structure.issues) + const result = await loadFiles({ data: { draftId: draft.id } }) + setIssues(result.structure.issues) + setSources(result.sources) } catch (error) { console.error(error) } @@ -173,7 +188,7 @@ export function EditorPage({ draft, members }: { draft: Draft; members: Assignme // The whole document, as the PDF numbers it: `\input` files continue the numbering of the file that inputs them. const parseAll = useCallback(() => { const files = currentFiles() - return parseDocument(files, entryFile(files)).nodes + return parseDocument(files, entryFile(files) ?? "RRI.tex").nodes }, [currentFiles]) const parsed = useMemo(() => { void revision @@ -328,6 +343,49 @@ export function EditorPage({ draft, members }: { draft: Draft; members: Assignme } } + // Files: added and removed in the shared document, so every member sees them at once. + const [newFileOpen, setNewFileOpen] = useState(false) + const [deleting, setDeleting] = useState(null) + const entry = useMemo(() => { + void revision + return entryFile(currentFiles()) + }, [currentFiles, revision]) + function createFile(file: NewFile) { + const document = collab.document + if (!document) return + const map = document.getMap("files") + const entryText = entry ? map.get(entry) : null + // A file created meanwhile by someone else stays theirs: a second Y.Text under its key could replace it. + if (map.has(file.path)) { + appToast.error(`Esiste già ${file.path}.`) + return + } + const insertion = file.include && entryText ? inputInsertion(entryText.toJSON(), file.path) : null + document.transact(() => { + map.set(file.path, new Y.Text(starterText(entryText?.toJSON() ?? "", file.title))) + if (entryText && insertion) entryText.insert(insertion.offset, insertion.text) + }) + setPath(file.path) + if (insertion) appToast.success(`File creato e incluso in ${entry}.`) + else if (file.include) + appToast.success(`File creato, ma non incluso: aggiungi \\input in ${entry ?? "il file principale"} a mano.`) + else appToast.success("File creato.") + } + function deleteFile(target: string) { + const document = collab.document + if (!document || !entry || target === entry) return + const map = document.getMap("files") + document.transact(() => { + for (const [other, otherText] of map.entries()) { + if (other === target) continue + for (const range of inputLinesOf(otherText.toJSON(), target)) + otherText.delete(range.from, range.to - range.from) + } + map.delete(target) + }) + appToast.success("File eliminato.") + } + // History. const [compare, setCompare] = useState(null) const [historyKey, setHistoryKey] = useState(0) @@ -497,6 +555,23 @@ export function EditorPage({ draft, members }: { draft: Draft; members: Assignme onOpen={setPath} className="@min-[1200px]/editor:hidden" /> + {!readOnly && collab.document && collab.synced && sources ? ( +
+ setNewFileOpen(true)} + /> + setDeleting(path)} + /> +
+ ) : null} {path && text && collab.document ? ( ) : null} + {!readOnly && sources ? ( + <> + + { + if (!open) setDeleting(null) + }} + onConfirm={deleteFile} + /> + + ) : null} ) } @@ -633,8 +728,3 @@ function ConnectionState({ status }: { status: ReturnType["sta ) } - -/** The main file: the one with `\documentclass` (the RRI's `RRI.tex`). */ -function entryFile(files: Files) { - return Object.keys(files).find((file) => /\\documentclass/.test(files[file] ?? "")) ?? "RRI.tex" -} diff --git a/src/features/regulations/editor/file-dialogs.tsx b/src/features/regulations/editor/file-dialogs.tsx new file mode 100644 index 0000000..0d33f14 --- /dev/null +++ b/src/features/regulations/editor/file-dialogs.tsx @@ -0,0 +1,189 @@ +import { useEffect, useState } from "react" + +import { + checkboxControl, + ConfirmDialog, + fieldControl, + fieldHintId, + FormDialog, + FormField, + SelectField, +} from "@/components/primitives" +import { Checkbox } from "@/components/ui/checkbox" +import { Input } from "@/components/ui/input" +import { cn } from "@/lib/utils" + +import { allowedPath, FILE_NAME, fileNameFromTitle, newFileFolders, newFilePath } from "./draft-files" + +export type NewFile = { path: string; title: string; include: boolean } + +/** + * "Nuovo file": a source file in one of the folders the document accepts (its `sources` globs), named from its title + * until edited, and included in the main file with `\input` unless unticked. + */ +export function NewFileDialog({ + open, + onOpenChange, + files, + sources, + entry, + regolamento, + onCreate, +}: { + open: boolean + onOpenChange: (open: boolean) => void + files: string[] + sources: string[] + /** The main file, where the `\input` goes; `null` when there's none to include it in. */ + entry: string | null + /** The document is a regolamento: the title becomes the new file's `\regolamento`. */ + regolamento: boolean + onCreate: (file: NewFile) => void +}) { + const folders = newFileFolders(sources) + const [folder, setFolder] = useState(null) + const [title, setTitle] = useState("") + const [typedName, setTypedName] = useState(null) + const [include, setInclude] = useState(true) + const [submitted, setSubmitted] = useState(false) + useEffect(() => { + if (!open) return + setFolder(null) + setTitle("") + setTypedName(null) + setInclude(true) + setSubmitted(false) + }, [open]) + + const chosenFolder = folder ?? folders[0] ?? "" + const name = typedName ?? fileNameFromTitle(title) + const path = newFilePath(chosenFolder, name) + const titleError = submitted && regolamento && !title.trim() ? "Scrivi il titolo del regolamento." : undefined + const nameError = !submitted + ? undefined + : !name.trim() + ? "Scrivi il nome del file." + : !FILE_NAME.test(name.trim().replace(/\.tex$/i, "")) + ? "Usa lettere, cifre, trattini e trattini bassi, iniziando con una lettera o una cifra." + : files.includes(path) + ? "Esiste già un file con questo nome." + : !allowedPath(path, sources) + ? "Il documento non accetta file con questo nome." + : undefined + + function submit() { + setSubmitted(true) + const bare = name.trim().replace(/\.tex$/i, "") + if (regolamento && !title.trim()) return + if (!bare || !FILE_NAME.test(bare) || files.includes(path) || !allowedPath(path, sources)) return + onCreate({ path, title: title.trim(), include: include && entry !== null }) + onOpenChange(false) + } + + return ( + 0} + onSubmit={submit} + > +
+ {folders.length > 1 ? ( + + ({ value, label: value || "Cartella principale" }))} + onChange={setFolder} + /> + + ) : null} + {regolamento ? ( + + setTitle(event.target.value)} + className={fieldControl} + /> + + ) : null} + 0 + ? `Il file sarà ${name.trim() ? path : `${chosenFolder}…`}` + : "Questo documento non accetta nuovi file." + } + > + setTypedName(event.target.value)} + className={cn("font-mono", fieldControl)} + /> + + {entry ? ( + + ) : null} +
+
+ ) +} + +/** "Elimina il file": the file leaves the draft for everyone, with the `\input` lines that include it. */ +export function DeleteFileDialog({ + path, + onOpenChange, + onConfirm, +}: { + path: string | null + onOpenChange: (open: boolean) => void + onConfirm: (path: string) => void +}) { + return ( + { + if (path) onConfirm(path) + }} + /> + ) +} diff --git a/src/features/regulations/regulations.contract.ts b/src/features/regulations/regulations.contract.ts index fd95995..8b6ff4d 100644 --- a/src/features/regulations/regulations.contract.ts +++ b/src/features/regulations/regulations.contract.ts @@ -493,7 +493,12 @@ export const listDraftsInputSchema = z.object({ includeClosed: z.boolean().default(false), }) -export const draftFilesSchema = z.object({ files: filesSchema, structure: structureSchema }) +export const draftFilesSchema = z.object({ + files: filesSchema, + structure: structureSchema, + /** The document's source globs (documents.json `sources`): where a draft may add files. Empty: anywhere. */ + sources: z.array(z.string()), +}) export const transitionInputSchema = z.object({ draftId: draftIdSchema, diff --git a/src/features/regulations/regulations.fake.server.ts b/src/features/regulations/regulations.fake.server.ts index b2ab97f..0ea4556 100644 --- a/src/features/regulations/regulations.fake.server.ts +++ b/src/features/regulations/regulations.fake.server.ts @@ -3,6 +3,7 @@ import { randomBytes } from "node:crypto" import { diffWords } from "diff" import * as Y from "yjs" +import { allowedPath } from "./editor/draft-files" import { type FileNode, parseDocument, plainTitle } from "./latex-structure" import type { RegulationsApi, RegulationsViewer } from "./regulations.api.server" import type { @@ -814,6 +815,45 @@ function insertUpload(document: StoredDocument, pdf: Buffer): StoredVersion { // Structure, as the backend's parser reports it. +/** + * A document's source globs, as documents.json would give them: the entry and `/*.tex` for each folder of its + * latest version (`*.tex` when every file is at the top). + */ +function sourcesOf(documentKey: string): string[] { + const latest = versionsOf(documentKey)[0] + if (!latest) return [] + const dirs = new Set( + Object.keys(latest.files) + .filter((path) => path.includes("/")) + .map((path) => path.slice(0, path.lastIndexOf("/"))) + ) + return dirs.size ? [latest.entry, ...[...dirs].sort().map((dir) => `${dir}/*.tex`)] : ["*.tex"] +} + +/** The text of a draft as the backend checks it: the parser's problems and files outside the document's sources. */ +function draftStructure(draft: { files: Files; entry: string; documentKey: string }): Structure { + const structure = structureOf(draft.files, draft.entry) + const sources = sourcesOf(draft.documentKey) + const stray = sources.length + ? Object.keys(draft.files) + .filter((path) => !allowedPath(path, sources)) + .sort() + : [] + if (!stray.length) return structure + const allowed = sources.map((glob) => `«${glob}»`).join(", ") + const issues: ValidationIssue[] = stray.map((file) => ({ + file, + line: 1, + column: 1, + offset: 0, + endOffset: 0, + severity: "error", + code: "stray_file", + message: `Il file «${file}» non è tra i sorgenti del documento (${allowed}): rinominalo o eliminalo.`, + })) + return { ...structure, parses: false, issues: [...issues, ...structure.issues] } +} + function structureOf(files: Files, entry = ENTRY_FILE): Structure { const root: StructureNode = { id: "documento", @@ -906,7 +946,7 @@ function api(viewer: RegulationsViewer): RegulationsApi { const procedure = procedureOf(draft.documentKey) const editable = procedure.states.find((state) => state.key === draft.state)?.editable ?? false const emanating = draft.emanation !== null && !isFinal(draft.state) - const parses = structureOf(draft.files, draft.entry).parses + const parses = draftStructure(draft).parses const writer = can("regulations:write") if (procedure.key === "documento") { // bozza → pubblicata in one step, "Pubblica", by Presidente or Segretario; nothing to approve or notify. @@ -1003,7 +1043,7 @@ function api(viewer: RegulationsViewer): RegulationsApi { createdAt: draft.createdAt, updatedAt: draft.updatedAt, stateChangedAt: draft.stateChangedAt, - parses: structureOf(draft.files, draft.entry).parses, + parses: draftStructure(draft).parses, } } @@ -1363,7 +1403,7 @@ function api(viewer: RegulationsViewer): RegulationsApi { }, async draftFiles({ draftId }) { const { draft } = visible(draftId) - return { files: draft.files, structure: structureOf(draft.files, draft.entry) } + return { files: draft.files, structure: draftStructure(draft), sources: sourcesOf(draft.documentKey) } }, async createDraft({ documentKey, title, from, kind = "modifica" }) { const document = documentOf(documentKey) diff --git a/tests/regulations-draft-files.test.mjs b/tests/regulations-draft-files.test.mjs new file mode 100644 index 0000000..b779aab --- /dev/null +++ b/tests/regulations-draft-files.test.mjs @@ -0,0 +1,92 @@ +import assert from "node:assert/strict" +import test from "node:test" + +import { + allowedPath, + entryFile, + fileNameFromTitle, + inputInsertion, + inputLinesOf, + isRegolamento, + newFileFolders, + newFilePath, + starterText, +} from "../src/features/regulations/editor/draft-files.ts" + +const RRI_SOURCES = ["RRI.tex", "regolamenti/*.tex"] +const RRI = String.raw`\documentclass{polinetwork-regolamento} +\begin{document} +% inizio dei vari regolamenti di secondo livello + +\newpage +\input{./regolamenti/1_fondamentale.tex} + +\newpage +\input{./regolamenti/conflitti_di_interesse.tex} + +% fine dei vari regolamenti di secondo livello +\end{document} +` + +test("new files go only in the folders of the document's globs", () => { + assert.deepEqual(newFileFolders(RRI_SOURCES), ["regolamenti/"]) + assert.deepEqual(newFileFolders(["*.tex"]), [""]) + assert.deepEqual(newFileFolders(["main.tex", "parti/*.tex", "**/x.tex"]), ["parti/"]) + assert.deepEqual(newFileFolders([]), [""]) + assert.equal(allowedPath("regolamenti/alumni.tex", RRI_SOURCES), true) + assert.equal(allowedPath("alumni.tex", RRI_SOURCES), false) + assert.equal(allowedPath("regolamenti/sub/alumni.tex", RRI_SOURCES), false) + assert.equal(allowedPath("anything/at/all.tex", []), true) +}) + +test("file names come from the title, like the RRI's", () => { + assert.equal(fileNameFromTitle("Regolamento Alumni"), "regolamento_alumni") + assert.equal(fileNameFromTitle(" Attività & Eventi! "), "attivita_eventi") + assert.equal(newFilePath("regolamenti/", "alumni"), "regolamenti/alumni.tex") + assert.equal(newFilePath("regolamenti/", "alumni.tex"), "regolamenti/alumni.tex") +}) + +test("a regolamento's new file starts with its \\regolamento", () => { + assert.equal(entryFile({ "regolamenti/a.tex": "x", "RRI.tex": RRI }), "RRI.tex") + assert.equal(isRegolamento(RRI), true) + assert.equal(starterText(RRI, "Regolamento Alumni"), "\\regolamento{Regolamento Alumni}\n\n") + assert.equal(starterText("\\documentclass{polinetwork}", "Titolo"), "") + assert.equal(starterText(RRI, "Attività & Eventi 100%"), "\\regolamento{Attività \\& Eventi 100\\%}\n\n") +}) + +test("the \\input goes after the last one, in its style", () => { + const insertion = inputInsertion(RRI, "regolamenti/alumni.tex") + assert.ok(insertion) + const next = RRI.slice(0, insertion.offset) + insertion.text + RRI.slice(insertion.offset) + assert.match( + next, + /\\input\{\.\/regolamenti\/conflitti_di_interesse\.tex\}\n\n\\newpage\n\\input\{\.\/regolamenti\/alumni\.tex\}\n\n% fine/ + ) + const bare = "\\begin{document}\n \\input{parti/uno}\n\\end{document}\n" + const other = inputInsertion(bare, "parti/due.tex") + assert.equal(other?.text, "\n\n \\input{parti/due}") + const none = inputInsertion("\\begin{document}\nTesto\n\\end{document}", "a.tex") + assert.equal(none?.text, "\\input{./a.tex}\n\n") + assert.equal(inputInsertion("Testo", "a.tex"), null) + const commented = "\\input{./a.tex}\n% \\input{./archivio.tex} vecchio\n\\end{document}" + assert.equal(inputInsertion(commented, "b.tex")?.offset, "\\input{./a.tex}".length) + assert.deepEqual(inputLinesOf("% \\input{a}\n", "a.tex"), []) +}) + +test("deleting a file removes the lines that include it", () => { + const ranges = inputLinesOf(RRI, "regolamenti/conflitti_di_interesse.tex") + assert.equal(ranges.length, 1) + let text = RRI + for (const range of ranges) text = text.slice(0, range.from) + text.slice(range.to) + assert.ok(!text.includes("conflitti_di_interesse")) + assert.match(text, /1_fondamentale\.tex\}\n\n% fine/) + // Adding then removing a file gives the main file back as it was. + const insertion = inputInsertion(RRI, "regolamenti/alumni.tex") + let added = RRI.slice(0, insertion.offset) + insertion.text + RRI.slice(insertion.offset) + for (const range of inputLinesOf(added, "regolamenti/alumni.tex")) + added = added.slice(0, range.from) + added.slice(range.to) + assert.equal(added, RRI) + assert.ok(text.includes("\\input{./regolamenti/1_fondamentale.tex}")) + const inline = inputLinesOf("Vedi \\input{a} qui\n", "a.tex") + assert.deepEqual(inline, [{ from: 5, to: 14 }]) +})