Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions docs/regulations/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 …").
164 changes: 164 additions & 0 deletions src/features/regulations/editor/draft-files.ts
Original file line number Diff line number Diff line change
@@ -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<string, string>) {
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
}
110 changes: 100 additions & 10 deletions src/features/regulations/editor/editor-page.tsx
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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"
Expand All @@ -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"
Expand Down Expand Up @@ -70,6 +82,7 @@ export function EditorPage({ draft, members }: { draft: Draft; members: Assignme
const [compile, setCompile] = useState<CompileStatus | null>(null)
const [pdf, setPdf] = useState<{ hash: string; bytes: Uint8Array } | null>(null)
const [issues, setIssues] = useState<ValidationIssue[]>([])
const [sources, setSources] = useState<string[] | null>(null)
const refreshCompile = useCallback(async () => {
try {
setCompile(await loadStatus({ data: { draftId: draft.id } }))
Expand All @@ -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)
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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<string | null>(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<Y.Text>("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<Y.Text>("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<Snapshot | null>(null)
const [historyKey, setHistoryKey] = useState(0)
Expand Down Expand Up @@ -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 ? (
<div className="-mr-1.5 ml-auto flex shrink-0 items-center">
<IconButton
label="Nuovo file"
icon={FilePlus}
className="size-7"
onClick={() => setNewFileOpen(true)}
/>
<IconButton
label={path === entry || !entry ? "Il file principale non si elimina" : "Elimina il file"}
icon={Trash2}
className="size-7"
disabled={!path || !entry || path === entry}
onClick={() => setDeleting(path)}
/>
</div>
) : null}
</div>
{path && text && collab.document ? (
<CodeEditor
Expand Down Expand Up @@ -585,6 +660,26 @@ export function EditorPage({ draft, members }: { draft: Draft; members: Assignme
<MembersDialog open={membersOpen} onOpenChange={setMembersOpen} draft={draft} members={members} />
) : null}
<PdfDialog {...viewer.props} />
{!readOnly && sources ? (
<>
<NewFileDialog
open={newFileOpen}
onOpenChange={setNewFileOpen}
files={collab.files}
sources={sources}
entry={entry}
regolamento={isRegolamento(entry ? (textOf(entry)?.toJSON() ?? "") : "")}
onCreate={createFile}
/>
<DeleteFileDialog
path={deleting}
onOpenChange={(open) => {
if (!open) setDeleting(null)
}}
onConfirm={deleteFile}
/>
</>
) : null}
</>
)
}
Expand Down Expand Up @@ -633,8 +728,3 @@ function ConnectionState({ status }: { status: ReturnType<typeof useCollab>["sta
</span>
)
}

/** 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"
}
Loading
Loading