From de03f6bb9662c1c8ce3ce26c374cfe699c6fe5b9 Mon Sep 17 00:00:00 2001 From: Julian Kiedaisch Date: Sun, 4 Oct 2026 11:27:25 +0000 Subject: [PATCH] feat: F4.8b the documentation mode in the editor Java's third mode button, the sidebar's text and structure field (dropped with its middle under the pointer), items over the network that are moved, resized by Java's rule, typed into on their Y.Text, coloured and set in size and style from Java's menu, deleted; Java's paint per mode, measured in F4.8a. Co-Authored-By: Claude Opus 5.5 --- CHANGES.md | 2 + packages/editor/browser/documentation.spec.ts | 169 ++++++++++++++ packages/editor/src/Editor.tsx | 106 ++++++++- .../src/assets/documentation/add_small.png | Bin 0 -> 1534 bytes .../assets/documentation/add_text_small.png | Bin 0 -> 1592 bytes .../editor/src/assets/modes/dokumodus.png | Bin 0 -> 11521 bytes .../src/assets/modes/dokumodus_aktiv.png | Bin 0 -> 12139 bytes packages/editor/src/canvas/Canvas.tsx | 221 +++++++++++++++--- .../editor/src/canvas/documentationPaint.ts | 79 +++++++ .../editor/src/design/DocumentationMenu.tsx | 158 +++++++++++++ .../src/design/DocumentationSidebar.tsx | 130 +++++++++++ .../editor/src/design/DocumentationText.tsx | 79 +++++++ packages/editor/src/i18n/de.json | 14 ++ packages/editor/src/i18n/en.json | 14 ++ packages/editor/src/simulation/ModeBar.tsx | 23 +- .../editor/test/documentationPaint.test.ts | 69 ++++++ packages/editor/test/i18n.test.ts | 12 + 17 files changed, 1034 insertions(+), 42 deletions(-) create mode 100644 packages/editor/browser/documentation.spec.ts create mode 100644 packages/editor/src/assets/documentation/add_small.png create mode 100644 packages/editor/src/assets/documentation/add_text_small.png create mode 100644 packages/editor/src/assets/modes/dokumodus.png create mode 100644 packages/editor/src/assets/modes/dokumodus_aktiv.png create mode 100644 packages/editor/src/canvas/documentationPaint.ts create mode 100644 packages/editor/src/design/DocumentationMenu.tsx create mode 100644 packages/editor/src/design/DocumentationSidebar.tsx create mode 100644 packages/editor/src/design/DocumentationText.tsx create mode 100644 packages/editor/test/documentationPaint.test.ts diff --git a/CHANGES.md b/CHANGES.md index 4700933..e30723b 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -235,6 +235,7 @@ Swift-Pfade relativ zu `filius-ipad/ios/FiliusPad/TopologyEditor/` (Stand | `src/desktop/GnutellaPanel.tsx`, `src/desktop/DesktopWindow.tsx`, `src/assets/desktop/peertopeer_*.png`, `src/main.tsx` (`filiusDev.writeFile`) | Java `GUIApplicationPeerToPeerAnwendungWindow` (`peertopeeranwendung_msg1`–`31`), Javas Symbole der Reiter, gemessen mit `GnutellaWindowRun` | neu (F4.6g4): Gnutella — vier Reiter mit Javas Symbolen: Netzwerk (Adresse, anfangs Javas 192.168.0.1, rot, solange sie keine ist; „Netz beitreten“, Tabelle der Nachbarn, „Netz verlassen“), Suche (Suchbegriff, „Suchen“, „Stopp!“, Ergebnistabelle mit Wahl, „Herunterladen“, „Liste leeren“), Dateien, Einstellungen (Zahl der Teilnehmer, „Speichern“). Besser als Java: die Tabellen zeigen sofort, was das Programm hält (Javas Ergebnisse zeigen nach einer neuen Suche die alten, bis ein Treffer kommt; seine Dateien nur, was beim letzten Bescheid des Programms da war); jede ganze Zahl wird genommen; was nicht genommen wird, steht unter dem Feld statt in einem Dialog; „Herunterladen“ nur mit gewähltem Ergebnis. Die Dev-Seite schreibt mit `writeFile` eine Datei wie eine andere Person | | `src/simulation/ViewerWindow.tsx`, `src/simulation/DropControl.tsx`, `src/simulation/timeOfDay.ts`, `src/simulation/useSimulation.ts` (`clock`, `dropped`, `drop`), `src/Editor.tsx`, `src/sheet/sheet.css` (`.editor-toolbar`) | Java `SatViewer`, `NatViewer` (`guievents_msg8`–`10`, `27`–`34`, `36`, `sw_switchfirmware_msg1`), `SimulationControl` (`simulation_control_drop_packets`), `GUIKnotenItem` (Klick im Aktionsmodus), gemessen mit `ViewersRun` | neu (F4.6g5): ein Tippen auf einen Switch zeigt seine Tabelle, auf einen Heimrouter seine NAT-Tabelle, in einem verschiebbaren Fenster mit Javas Spalten und Uhrzeiten; „Pakete verwerfen“ wird gehalten (Finger, Maus, Leertaste/Enter), daneben die Zahl und aufklappbar die Liste der verworfenen Frames mit Uhrzeit und Javas Text. Besser als Java: „Tabelle löschen“/„zurücksetzen“ ist ein Knopf (Java: Menü der rechten Maustaste), die Liste klappt weg; die Werkzeugleiste bricht auf schmalen Bildschirmen um | | `src/simulation/CaptureWindow.tsx`, `src/simulation/captureCells.ts`, `src/simulation/useSimulation.ts` (`traces`, `clearCapture`), `src/Editor.tsx`, `src/desktop/desktop.css`, `src/theme/tokens.css` (`--capture-*`), Kataloge (`capture.*`, `menu.showCapture`) | Java `AggregatedExchangeDialog` (`lauscherdialog_msg1`), `AggregatedExchangePanel` (`buttontabcomponent_msg1`), `AggregatedMessageTable` (`nachrichtentabelle_msg7`–`9`), `LauscherTableCellRenderer`, `LayerColorVar`, `Lauscher` (`rp_lauscher_msg1`–`14`), `GUIEvents` (`guievents_msg4`), gemessen mit `ExchangeWindowRun` | neu (F4.7): im Menü eines Geräts je Karte „Datenaustausch anzeigen (Adresse)“; ein Fenster mit einem Reiter je Karte, die Zeilen in Javas Schichtenfarben (dunkle Varianten im dunklen Thema), die gewählte weiß auf schwarz, darunter ihre Details, „Tabellen löschen“, „Als Textdatei exportieren“ (nach dem Reiter benannt), „Automatisches Scrollen“; Wahl und Scrollen je Reiter, behalten, solange das Fenster zu ist; das Fenster geht mit dem Entwurf und kommt mit dem nächsten Start; der Reiter einer entfernten Karte verschwindet. Besser als Java: die drei sind Knöpfe und ein Kästchen statt eines Menüs der rechten Maustaste; ein Frame wird nach seiner Nummer gewählt (Javas Details nehmen den Zeilenindex dafür) | +| `src/design/DocumentationSidebar.tsx`, `src/design/DocumentationText.tsx`, `src/design/DocumentationMenu.tsx`, `src/canvas/documentationPaint.ts`, `src/canvas/Canvas.tsx` (Dokumentationsmodus), `src/simulation/ModeBar.tsx` (dritter Knopf), `src/Editor.tsx`, `src/assets/modes/dokumodus*.png`, `src/assets/documentation/*.png`, Kataloge (`mode.documentation`, `docu.*`) | Java `GUIMainMenu` (`btDokumodus`, `guimainmemu_msg14`, Reihenfolge der Knöpfe), `GUIDocumentationSidebar` (`docusidebar_msg1`, `3`), `GUIContainer` (Ablegen aus der Seitenleiste, Ebenen), `JDocuElement` (Fokus, Ziehen, Menü `guievents_msg13`–`21`, Zeichnen), `GUIDocumentationPanel` (Klick daneben), gemessen mit `DocuRun` | neu (F4.8b): der Dokumentationsmodus — Javas dritter Knopf vorn, er stoppt eine Simulation; die Seitenleiste „Text“/„Gliederungsfläche“ (gezogen landet ein Element mittig unter dem Zeiger, mit Fokus); die Elemente liegen über dem Netz und nehmen den Zeiger: Tippen gibt den Fokus, eine Fläche wird an ihrer Mitte gezogen, ein Text in seinem Fokusband, am Rand ändert sich die Größe nach Javas Regel; der Text wird in ein Feld über ihm getippt (auf `Y.Text`, Escape beendet, Strg+Entf löscht); das Menü mit Schriftgröße, Schriftstil, Javas Farben und Löschen; Entf löscht; Javas Zeichnung je Modus (halbtransparent im Dokumentationsmodus, sonst deckend aufgehellt, Rand, grauer Textrand nur im Dokumentationsmodus, Fokus blau). Besser als Java: Tippen auf die Seitenleiste legt ein Element in die Mitte der Ansicht (Java legt nichts ab); das Menü zeigt Größen, Stile und Farben auf einmal statt in Untermenüs; die Ränder lassen sich bei kleinem Zoom mit dem Finger greifen (mindestens 10 Bildschirmpunkte) | | `src/Editor.tsx`, `src/canvas/Canvas.tsx` (Aktionsmodus) | Java `GUIContainer.setActiveSite/showDesktop/closeDialogs/reopenDialogs`, `GUIKnotenItem` (Klick im Aktionsmodus), `GUIEvents.kontextMenueAktionsmodus` (`guievents_msg3`), `JCablePanel` (`farbeBlinken`) | erweitert (F4.6a): im Aktionsmodus ist der Entwurf gesperrt wie bei Java — keine Palette, kein Blatt, nichts bewegt sich, kein Rückgängig, kein Löschen —, Kabel mit Rahmen leuchten grün, ein Tipp auf einen Rechner öffnet seinen Desktop (Langdruck: „Desktop anzeigen“); offene Desktops überstehen den Entwurf und erscheinen beim nächsten Start wieder, die eines entfernten Rechners nicht | | `browser/simulation.spec.ts`, `test/programs.test.ts` | — | neu (F4.6a): Moduswechsel, Sperren, Geschwindigkeit, Kabelaktivität, Desktop mit Titel, Programmen, Netzwerk-Info, Verschieben und Stapeln, Handy, Englisch; die Programmliste gegen Javas `Desktop_*.txt`; seit F4.6b die Befehlszeile (Ping über drei Router, Verlauf, Chips, Strg+C, Behalten, exit) und der Fehlerfall des Raums; seit F4.6c die Software-Installation (sofort lauffähig, Doppelklick, Abwählen) | | `browser/web.spec.ts`, `browser/fixtures/web-pages.fls`, `test/webPagesFixture.test.ts`, `test/serverLines.test.ts`, `src/simulation/useSimulation.ts` (`views`), `src/Editor.tsx` (Sprache beim Start), `src/desktop/DesktopWindow.tsx` | — | neu (F4.6d): Browser und Webserver in Chromium auf einer eigenen Projektdatei (mit den Befehlen des Dokuments gebaut und bei jedem Lauf verglichen): Adresszeile, Titel, Sandbox, Bilder, Marke, Links im Ordner, beide Formulare bis in die Zeilen des Servers, Fehlerseite, nicht erreichbarer Server, Knopf, Kästchen und Tabelle, die Routerseiten auf Englisch; die Zeilen des Servers gegen Javas Fenster | @@ -248,6 +249,7 @@ Swift-Pfade relativ zu `filius-ipad/ios/FiliusPad/TopologyEditor/` (Stand | `browser/gnutella.spec.ts` | — | neu (F4.6g4): Gnutella in Chromium auf `email_komplett`, im Lauf auf zwei Notebooks installiert — vier Reiter, eine Adresse mit Javas Worten abgelehnt, ein Nachbar beigetreten, eine Datei des anderen gefunden und heruntergeladen (der Reiter Dateien zeigt sie), „Liste leeren“ hebt die Wahl auf, die Zahl der Teilnehmer gespeichert (12, die Java ablehnt; was keine Zahl ist, mit Javas Worten abgelehnt), das Netz verlassen | | `browser/viewers.spec.ts`, `test/timeOfDay.test.ts` | — | neu (F4.6g5): auf `nat_with_mapped_port` die NAT-Tabelle (Portweiterleitung, dann ein Ping, zurückgesetzt), die Switch-Tabelle (gelernt, gelöscht), „Pakete verwerfen“ gehalten, während ein Ping läuft (Antworten verloren, Liste in Javas Worten); auf einem Handy bleibt „Pakete verwerfen“ erreichbar; die Uhrzeit wie Javas `HH:mm:ss(.SSS)` | | `browser/capture.spec.ts`, `test/captureCells.test.ts` | — | neu (F4.7): auf `web-pages.fls` Javas Menü, eine Seite geladen (Zeile je Frame, Javas Farben, Details, Textdatei mit Javas Kopf), die Karten eines Routers, „Tabellen löschen“, „Automatisches Scrollen“ aus, ein Reiter geschlossen, das Fenster über Entwurf und Start, der Reiter eines entfernten Rechners weg; auf einem Handy; die Zellen in beiden Sprachen und Zahlenformaten | +| `browser/documentation.spec.ts`, `test/documentationPaint.test.ts` | — | neu (F4.8b): auf `nat_with_mapped_port` Javas Knopfreihenfolge, eine Fläche gezogen (mittig, grau, Deckkraft 200), verschoben, auf 20 × 20 verkleinert, Farbe aus Javas zwölf; ein Text getippt, groß und kursiv; Escape, Javas Textrand; im Entwurf deckend aufgehellt, nicht wählbar; Entf; Start der Simulation beendet den Modus; Handy; die Zeichenregeln gegen Javas gemessene Pixel | | `src/sheet/ServicePanels.tsx`, `src/sheet/RowsEditor.tsx`, `src/sheet/SheetTabs.tsx`, `src/sheet/DeviceSheet.tsx` (Seiten) | Java `JDHCPKonfiguration` (`jdhcpkonfiguration_msg1`–`15`), `JPortForwardingDialog` (`jportforwarding_msg4`–`7`, `jgatewayconfiguration_msg19`) | neu (F4.5c): Javas Dialoge als Seiten des Blatts mit „Zurück“ — DHCP-Server (Grundeinstellungen, statische Adresszuweisung; beim Rechner, gesperrt während DHCP die Karte einrichtet, und auf dem LAN-Reiter des Heimrouters), Portfreigaben (Heimrouter); jedes Feld beim Verlassen übernommen statt mit Javas OK-Knopf. Die Zeilentabellen (Weiterleitung, Zuordnungen, Portfreigaben) teilen sich `RowsEditor`: eine neue Zeile, sobald alle Felder gültig sind, Zeile wählen, bearbeiten, löschen. Javas Tooltip zu „Manuelle Einstellungen“ als Text unter dem Kästchen (ein Finger hat kein Überfahren) | | `src/sheet/RouterSheets.tsx`, `src/sheet/NameField.tsx`, `src/canvas/Canvas.tsx` (`highlightedLink`), `src/theme/tokens.css` (`--canvas-cable-active`) | Java `JVermittlungsrechnerKonfiguration`, `JGatewayConfiguration`, `JWeiterleitungsTabelle` (Wörter `jvermittlungsrechnerkonfiguration_msg6`–`26`, `jweiterleitungstabelle_msg3`–`6`), `JCablePanel.farbeBlinken`, `Kabel.setAktiv` | neu (F4.5b): Blatt des Vermittlungsrechners — Reiter Allgemein (Name, Gateway, Automatisches Routing, IP-Weiterleitung nur angezeigt), je Karte (Reiter mit ihrer Adresse, „Verbunden mit …“, Adresse, Maske, MAC) und Weiterleitungstabelle (alle Einträge oder nur die manuellen, Javas Zeilen grau, eine neue Zeile, die mit vier gültigen Feldern übernommen wird, Zelle bearbeiten, Eintrag löschen; bei RIP gesperrt); Blatt des Heimrouters mit Allgemein, LAN, WAN (DHCP sperrt die WAN-Adresse). Das Kabel der offenen Karte leuchtet grün wie bei Java. Javas „Eintrag Löschen“ klein geschrieben | diff --git a/packages/editor/browser/documentation.spec.ts b/packages/editor/browser/documentation.spec.ts new file mode 100644 index 0000000..56f91fe --- /dev/null +++ b/packages/editor/browser/documentation.spec.ts @@ -0,0 +1,169 @@ +// The documentation mode in Chromium (F4.8b), on FILIUS' example +// nat_with_mapped_port, which has documentation: Java's third mode button; +// the sidebar's rectangle dragged onto the surface (its middle under the +// pointer), moved, resized to Java's smallest size, coloured from Java's +// list; the sidebar's text tapped into the view, typed into, made large and +// italic; Java's paint in the documentation mode and in the design; Delete; +// a simulation started ends the mode; and a phone. + +import { expect, test, type Page } from '@playwright/test'; +import { drag, drawing, openEditor, serveEditor } from './editorPage.js'; + +let server: { readonly base: string; readonly close: () => Promise }; + +test.beforeAll(async () => { + server = await serveEditor(); +}); + +test.afterAll(async () => { + await server.close(); +}); + +const newDoc = async (page: Page, before: ReadonlySet) => { + await expect.poll(async () => (await drawing(page)).docs.filter((item) => !before.has(item.id)).length).toBe(1); + return (await drawing(page)).docs.find((item) => !before.has(item.id))!; +}; +const docOf = async (page: Page, id: string) => (await drawing(page)).docs.find((item) => item.id === id); +const fill = (page: Page, id: string) => page.locator(`g[data-doc="${id}"] .doc-rectangle`).evaluate((rect) => getComputedStyle(rect).fill); + +async function longPress(page: Page, at: { x: number; y: number }) { + await page.mouse.move(at.x, at.y); + await page.mouse.down(); + await page.waitForTimeout(700); + await page.mouse.up(); +} + +test('makes, moves, resizes, colours and types documentation as Java does, and paints it per mode', async ({ page }) => { + test.setTimeout(120_000); + await openEditor(page, server.base, 'nat_with_mapped_port.fls'); + const canvas = page.locator('svg.filius-canvas'); + const existing = new Set((await drawing(page)).docs.map((item) => item.id)); + expect(existing.size).toBeGreaterThan(0); + + // Java's order: documentation, design, simulation. + expect(await page.locator('.editor-toolbar button[name$="Mode"]').evaluateAll((buttons) => buttons.map((each) => each.getAttribute('name')))).toEqual([ + 'documentationMode', + 'designMode', + 'simulationMode', + ]); + await page.getByRole('button', { name: 'Wechselt in den Dokumentationsmodus' }).click(); + await expect(canvas).toHaveAttribute('data-mode', 'documentation'); + await expect(page.getByRole('navigation', { name: 'Komponenten' })).toHaveCount(0); + const sidebar = page.getByRole('navigation', { name: 'Dokumentation' }); + await expect(sidebar.getByRole('button')).toHaveText(['Text', 'Gliederungsfläche']); + + // A rectangle dragged onto the surface: 100 × 50, its middle where it was dropped, grey, with the focus. + const surface = (await canvas.boundingBox())!; + const drop = { x: surface.x + surface.width * 0.6, y: surface.y + surface.height * 0.3 }; + const button = (await sidebar.getByRole('button', { name: 'Gliederungsfläche' }).boundingBox())!; + await drag(page, { x: button.x + button.width / 2, y: button.y + button.height / 2 }, drop); + const rectangle = await newDoc(page, existing); + expect([rectangle.kind, rectangle.width, rectangle.height]).toEqual(['rectangle', 100, 50]); + const focusBox = (await page.locator(`g[data-doc="${rectangle.id}"] .doc-focus`).boundingBox())!; + expect(Math.abs(focusBox.x + focusBox.width / 2 - drop.x)).toBeLessThan(2); + expect(Math.abs(focusBox.y + focusBox.height / 2 - drop.y)).toBeLessThan(2); + // Java's paint in the documentation mode: grey at an opacity of 200. + expect(await fill(page, rectangle.id)).toBe('rgba(204, 204, 204, 0.784)'); + + // Moved by its middle, resized by its corner to Java's smallest (20 × 20). + await drag(page, drop, { x: drop.x + 40, y: drop.y + 30 }); + await expect.poll(async () => (await docOf(page, rectangle.id))!.x - rectangle.x).toBeGreaterThan(20); + const moved = (await docOf(page, rectangle.id))!; + const corner = (await page.locator(`g[data-doc="${rectangle.id}"] .doc-focus`).boundingBox())!; + await drag(page, { x: corner.x + corner.width - 2, y: corner.y + corner.height - 2 }, { x: corner.x - 50, y: corner.y - 50 }); + await expect + .poll(async () => { + const item = (await docOf(page, rectangle.id))!; + return [item.x, item.y, item.width, item.height]; + }) + .toEqual([moved.x, moved.y, 20, 20]); + + // Its menu: only the colour (Java's twelve) and „Löschen“; a colour chosen. + const small = (await page.locator(`g[data-doc="${rectangle.id}"] .doc-focus`).boundingBox())!; + await longPress(page, { x: small.x + small.width / 2, y: small.y + small.height / 2 }); + const menu = page.getByRole('menu'); + await expect(menu.getByRole('group')).toHaveCount(1); + await expect(menu.getByRole('group', { name: 'Farbe' }).getByRole('menuitemradio')).toHaveCount(12); + await expect(menu.getByRole('menuitemradio', { name: 'Farbe 2' })).toHaveAttribute('aria-checked', 'true'); + await menu.getByRole('menuitemradio', { name: 'Farbe 5' }).click(); + await expect.poll(async () => (await docOf(page, rectangle.id))!.color).toEqual({ red: 1, green: 201 / 255, blue: 201 / 255, alpha: 1 }); + + // A text tapped from the sidebar: in the middle of the view, typed into at once. + const withRectangle = new Set((await drawing(page)).docs.map((item) => item.id)); + await sidebar.getByRole('button', { name: 'Text' }).click(); + const text = await newDoc(page, withRectangle); + const field = page.getByRole('textbox', { name: 'Text' }); + await expect(field).toBeFocused(); + await page.keyboard.type('Netz A'); + await page.keyboard.press('Enter'); + await page.keyboard.type('zweite Zeile'); + await expect.poll(async () => (await docOf(page, text.id))!.text).toBe('Netz A\nzweite Zeile'); + // Its menu: size, style, Java's fifteen colours; „Groß“, then „Kursiv“. + const textFocus = (await page.locator(`g[data-doc="${text.id}"] .doc-focus`).boundingBox())!; + const band = { x: textFocus.x + textFocus.width / 2, y: textFocus.y + textFocus.height - 8 }; + await longPress(page, band); + await expect(menu.getByRole('group')).toHaveText([/^Schriftgröße/, /^Schriftstil/, /^Farbe/]); + await expect(menu.getByRole('group', { name: 'Farbe' }).getByRole('menuitemradio')).toHaveCount(15); + await expect(menu.getByRole('group', { name: 'Schriftgröße' }).getByRole('menuitemradio', { checked: true })).toHaveAccessibleName('Normal'); + await menu.getByRole('menuitemradio', { name: 'Groß', exact: true }).click(); + await longPress(page, band); + await menu.getByRole('group', { name: 'Schriftstil' }).getByRole('menuitemradio', { name: 'Kursiv' }).click(); + await expect + .poll(async () => { + const item = (await docOf(page, text.id))!; + return [item.size, item.italic, item.bold]; + }) + .toEqual([18, true, false]); + await expect(field).toHaveCSS('font-style', 'italic'); + + // Escape ends the focus: the text drawn, with Java's grey border in the documentation mode. + await field.press('Escape'); + await expect(field).toHaveCount(0); + const words = page.locator(`g[data-doc="${text.id}"] .doc-text`); + await expect(words).toHaveText('Netz A\nzweite Zeile'); + await expect(words).toHaveCSS('border-top-color', 'rgb(179, 179, 179)'); + await expect(words).toHaveCSS('font-size', '18px'); + await expect(words).toHaveCSS('font-style', 'italic'); + // A rectangle without the focus is moved at once (Java gives it the focus with the press). + const before = (await docOf(page, rectangle.id))!; + const unfocused = (await page.locator(`g[data-doc="${rectangle.id}"] .doc-rectangle`).boundingBox())!; + await expect(page.locator(`g[data-doc="${rectangle.id}"]`)).not.toHaveAttribute('data-focused', 'true'); + await drag(page, { x: unfocused.x + unfocused.width / 2, y: unfocused.y + unfocused.height / 2 }, { x: unfocused.x + unfocused.width / 2 + 30, y: unfocused.y + unfocused.height / 2 }); + await expect.poll(async () => (await docOf(page, rectangle.id))!.x - before.x).toBeGreaterThan(10); + + // The design: the rectangle opaque, a fifth of the way to white, below the devices; the text without its border; documentation is not chosen. + await page.getByRole('button', { name: 'Wechselt in den Entwurfsmodus' }).click(); + await expect(canvas).toHaveAttribute('data-mode', 'design'); + expect(await fill(page, rectangle.id)).toBe('rgb(255, 212, 212)'); + await expect(page.locator(`g[data-doc="${rectangle.id}"] .doc-rectangle`)).toHaveCSS('stroke', 'rgb(204, 160, 160)'); + await expect(words).toHaveCSS('border-top-style', 'none'); + const wordsBox = (await words.boundingBox())!; + await page.mouse.click(wordsBox.x + 4, wordsBox.y + 4); + await expect(page.locator('[data-focused="true"]')).toHaveCount(0); + await expect(page.getByRole('navigation', { name: 'Komponenten' })).toBeVisible(); + + // Back in the documentation mode: Delete removes the focused rectangle. + await page.getByRole('button', { name: 'Wechselt in den Dokumentationsmodus' }).click(); + const rectangleBox = (await page.locator(`g[data-doc="${rectangle.id}"] .doc-rectangle`).boundingBox())!; + await page.mouse.click(rectangleBox.x + rectangleBox.width / 2, rectangleBox.y + rectangleBox.height / 2); + await expect(page.locator(`g[data-doc="${rectangle.id}"]`)).toHaveAttribute('data-focused', 'true'); + await page.keyboard.press('Delete'); + await expect.poll(async () => (await docOf(page, rectangle.id)) === undefined).toBe(true); + + // A simulation started ends the documentation mode, as Java's does. + await page.getByRole('button', { name: 'Wechselt in den Aktionsmodus' }).click(); + await expect(canvas).toHaveAttribute('data-mode', 'simulation'); + await expect(sidebar).toHaveCount(0); + await page.getByRole('button', { name: 'Wechselt in den Dokumentationsmodus' }).click(); + await expect(canvas).toHaveAttribute('data-mode', 'documentation'); + await expect(page.getByRole('button', { name: 'Wechselt in den Dokumentationsmodus' })).toHaveAttribute('aria-pressed', 'true'); +}); + +test('keeps the documentation mode within reach on a phone', async ({ page }) => { + await page.setViewportSize({ width: 360, height: 740 }); + await openEditor(page, server.base, 'nat_with_mapped_port.fls'); + await page.getByRole('button', { name: 'Wechselt in den Dokumentationsmodus' }).click(); + await expect(page.getByRole('button', { name: 'Gliederungsfläche' })).toBeInViewport({ ratio: 1 }); + const rights = await page.locator('.editor-toolbar > *').evaluateAll((parts) => parts.map((part) => part.getBoundingClientRect().right)); + expect(Math.max(...rights)).toBeLessThanOrEqual(360); +}); diff --git a/packages/editor/src/Editor.tsx b/packages/editor/src/Editor.tsx index 18bd615..42c84c4 100644 --- a/packages/editor/src/Editor.tsx +++ b/packages/editor/src/Editor.tsx @@ -2,7 +2,10 @@ // mode (F4.4b), the device sheet of the selected device (F4.5), Java's mode // buttons and the simulation (F4.6): while it runs, the design is locked as // in Java — no palette, no sheet, nothing moves — the cables that carry a -// frame light up, and a tap on a computer opens its desktop. Desktops left +// frame light up, and a tap on a computer opens its desktop. In the +// documentation mode (F4.8b) the sidebar makes texts and rectangles, which +// lie over the network and are moved, resized, typed into and coloured +// there; for the room it is the design (Java stops a simulation for it). Desktops left // open stay over a return to the design and show again at the next start, // as Java's do (GUIContainer.closeDialogs, reopenDialogs); so does the data // exchange window with its tabs (F4.7). @@ -13,17 +16,38 @@ import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties } from 'react'; import type * as Y from 'yjs'; -import { addDevice, captureCards, connect, createUndoManager, moveDevice, removeDevice, removeLink, removeLinksOf, topologyView, type TopologyView } from '@mdg-filius/doc'; +import { + addDevice, + addDocumentation, + captureCards, + connect, + createUndoManager, + documentationText, + moveDevice, + removeDevice, + removeDocumentation, + removeLink, + removeLinksOf, + setDocumentationColor, + setDocumentationFont, + setDocumentationFrame, + topologyView, + type TopologyView, +} from '@mdg-filius/doc'; +import { DOCUMENTATION_NEW_SIZE, type DocumentationItemKind } from '@mdg-filius/core'; import { Canvas, type CanvasHandle, type Selection, type Side } from './canvas/Canvas.js'; import type { Point } from './canvas/viewport.js'; import { ContextMenu, type MenuItem } from './design/ContextMenu.js'; +import { DocumentationMenu } from './design/DocumentationMenu.js'; +import { DocumentationSidebar } from './design/DocumentationSidebar.js'; +import { DocumentationText } from './design/DocumentationText.js'; import { Palette, type PaletteKind } from './design/Palette.js'; import { RouterDialog } from './design/RouterDialog.js'; import { DeviceSheet } from './sheet/DeviceSheet.js'; import { DesktopWindow, type DesktopWindowName } from './desktop/DesktopWindow.js'; import { useLanguage, useTranslate } from './i18n/i18n.js'; import { CaptureWindow } from './simulation/CaptureWindow.js'; -import { ModeBar } from './simulation/ModeBar.js'; +import { ModeBar, type EditorMode } from './simulation/ModeBar.js'; import { DropControl } from './simulation/DropControl.js'; import { ViewerWindow, type ViewerKind } from './simulation/ViewerWindow.js'; import { useSimulation, type SimHostFactory } from './simulation/useSimulation.js'; @@ -114,6 +138,9 @@ export function Editor({ doc, createSimHost }: { readonly doc: Y.Doc; readonly c const view = useTopologyView(doc); const simulation = useSimulation(doc, createSimHost); const simulating = simulation.mode === 'simulation'; + const [documenting, setDocumenting] = useState(false); + // The simulation comes first: started, it ends the documentation mode (changeMode). + const editorMode: EditorMode = simulating ? 'simulation' : documenting ? 'documentation' : 'design'; const [desktops, setDesktops] = useState([]); const origin = useMemo(() => ({ editor: crypto.randomUUID() }), []); const { manager, canUndo, canRedo } = useUndo(doc, origin); @@ -134,15 +161,14 @@ export function Editor({ doc, createSimHost }: { readonly doc: Y.Doc; readonly c return () => clearTimeout(timer); }, [message]); - // The simulation locks the design: what was chosen or begun is let go. + // The simulation locks the design, the documentation mode takes the surface: what was chosen or begun is let go. useEffect(() => { - if (!simulating) return; setSelection(null); setCableTool(false); setCableFrom(null); setMenu(null); setRouterAt(null); - }, [simulating]); + }, [editorMode]); useEffect(() => { if (simulation.failed) setMessage(t('sim.failed')); @@ -190,6 +216,7 @@ export function Editor({ doc, createSimHost }: { readonly doc: Y.Doc; readonly c useEffect(() => { if (selection?.kind === 'device' && !view.nodes.some((node) => node.id === selection.id)) setSelection(null); if (selection?.kind === 'link' && !view.links.some((link) => link.id === selection.id)) setSelection(null); + if (selection?.kind === 'doc' && !view.docs.some((item) => item.id === selection.id)) setSelection(null); if (cableFrom !== null && !view.nodes.some((node) => node.id === cableFrom.id)) setCableFrom(null); }, [view, selection, cableFrom]); @@ -227,6 +254,7 @@ export function Editor({ doc, createSimHost }: { readonly doc: Y.Doc; readonly c const remove = useCallback( (target: Selection) => { if (target.kind === 'device') removeDevice(doc, target.id, origin); + else if (target.kind === 'doc') removeDocumentation(doc, target.id, origin); else removeLink(doc, target.id, origin); manager?.stopCapturing(); setSelection(null); @@ -243,7 +271,24 @@ export function Editor({ doc, createSimHost }: { readonly doc: Y.Doc; readonly c [openDesktop], ); + /** A text or rectangle from the sidebar: its middle where it was dropped (Java), or in the middle of the view; it has the focus. */ + const onDocumentationItem = (kind: DocumentationItemKind, at: { readonly clientX: number; readonly clientY: number } | null) => { + const point = at === null ? (canvas.current?.surfaceCentre() ?? null) : (canvas.current?.surfacePointAt(at.clientX, at.clientY) ?? null); + if (point === null) return; + const id = crypto.randomUUID(); + addDocumentation(doc, { id, kind, x: point.x - DOCUMENTATION_NEW_SIZE.width / 2, y: point.y - DOCUMENTATION_NEW_SIZE.height / 2 }, origin); + manager?.stopCapturing(); + setSelection({ kind: 'doc', id }); + }; + + const changeMode = (mode: EditorMode) => { + setDocumenting(mode === 'documentation'); + if (mode === 'simulation') simulation.start(language); + else if (simulating) simulation.stop(); + }; + const menuItems = (target: Selection): MenuItem[] => { + if (target.kind === 'doc') return []; if (simulating) { // Java's menu in the simulation: a computer's desktop, then each card's data exchange with its address. if (target.kind !== 'device') return []; @@ -301,7 +346,9 @@ export function Editor({ doc, createSimHost }: { readonly doc: Y.Doc; readonly c return (
- {simulating ? null : ( + {simulating ? null : documenting ? ( + + ) : ( { @@ -325,7 +372,22 @@ export function Editor({ doc, createSimHost }: { readonly doc: Y.Doc; readonly c onCableStart={setCableFrom} onCable={onCable} highlightedLink={highlightedLink} - mode={simulation.mode} + mode={editorMode} + onDocFrame={(id, frame) => setDocumentationFrame(doc, id, frame, origin)} + renderDocText={(item, frame) => { + const text = documentationText(doc, item.id); + return text === undefined ? null : ( + setSelection(null)} + onRemove={() => remove({ kind: 'doc', id: item.id })} + /> + ); + }} activeLinks={simulation.activeLinks} onActivate={(id) => { const kind = view.nodes.find((node) => node.id === id)?.kind; @@ -335,6 +397,12 @@ export function Editor({ doc, createSimHost }: { readonly doc: Y.Doc; readonly c else if (kind === 'gateway') openDesktop(id, 'nat'); }} onMenu={(target, at) => { + if (editorMode === 'documentation') { + if (target.kind !== 'doc') return; + setSelection(target); + setMenu({ target, at }); + return; + } if (simulating) { if (menuItems(target).length > 0) setMenu({ target, at }); return; @@ -344,7 +412,7 @@ export function Editor({ doc, createSimHost }: { readonly doc: Y.Doc; readonly c }} />
- (mode === 'simulation' ? simulation.start(language) : simulation.stop())} onSpeed={simulation.setSpeed} /> + {simulating ? : ( <> + ))} +
+
+
{t('docu.fontStyle')}
+ {STYLES.map((each) => ( + + ))} +
+ + ) : null} +
+
{t('docu.color')}
+ {/* Java's rows: three, as many columns as that makes. */} +
+ {colors.map((color, index) => { + const chosen = sameColor(color, item.color); + return ( +
+
+
+ +
+ ); +} diff --git a/packages/editor/src/design/DocumentationSidebar.tsx b/packages/editor/src/design/DocumentationSidebar.tsx new file mode 100644 index 0000000..2b52d7d --- /dev/null +++ b/packages/editor/src/design/DocumentationSidebar.tsx @@ -0,0 +1,130 @@ +// The documentation mode's sidebar (Java's GUIDocumentationSidebar): „Text“ +// and „Gliederungsfläche“ with Java's icons. An item is dragged onto the +// surface, where it lands with its middle under the pointer, as Java's does; +// tapped, it lands in the middle of the view (Java's tap makes nothing). + +import { useRef, useState, type CSSProperties } from 'react'; +import type { DocumentationItemKind } from '@mdg-filius/core'; +import { DRAG_THRESHOLD } from '../canvas/Canvas.js'; +import { useTranslate } from '../i18n/i18n.js'; +import addRectangle from '../assets/documentation/add_small.png'; +import addText from '../assets/documentation/add_text_small.png'; + +export interface DocumentationSidebarProps { + /** An item dropped at a point of the screen, or tapped (no point). */ + readonly onItem: (kind: DocumentationItemKind, at: { readonly clientX: number; readonly clientY: number } | null) => void; +} + +const ITEMS: readonly { readonly kind: DocumentationItemKind; readonly icon: string; readonly label: string }[] = [ + { kind: 'text', icon: addText, label: 'docu.text' }, + { kind: 'rectangle', icon: addRectangle, label: 'docu.rectangle' }, +]; + +const item: CSSProperties = { + display: 'flex', + flexDirection: 'column', + alignItems: 'center', + gap: 2, + minHeight: 64, + padding: '6px 4px', + border: '2px solid transparent', + borderRadius: 8, + background: 'transparent', + color: 'var(--text-primary)', + font: 'inherit', + fontSize: 12, + textAlign: 'center', + overflowWrap: 'anywhere', + cursor: 'grab', + touchAction: 'none', +}; + +export function DocumentationSidebar({ onItem }: DocumentationSidebarProps) { + const t = useTranslate(); + const [ghost, setGhost] = useState<{ kind: DocumentationItemKind; x: number; y: number } | null>(null); + const press = useRef<{ kind: DocumentationItemKind; x: number; y: number; dragging: boolean } | null>(null); + /** The click the browser sends after a drag ends on the button: not a tap. */ + const afterDrag = useRef(false); + + const onPointerDown = (kind: DocumentationItemKind) => (event: React.PointerEvent) => { + press.current = { kind, x: event.clientX, y: event.clientY, dragging: false }; + // The button is the click's own target: capturing at once takes no click from anything inside it. + event.currentTarget.setPointerCapture(event.pointerId); + }; + const onPointerMove = (event: React.PointerEvent) => { + const now = press.current; + if (now === null) return; + if (!now.dragging) { + if (Math.hypot(event.clientX - now.x, event.clientY - now.y) < DRAG_THRESHOLD) return; + now.dragging = true; + } + setGhost({ kind: now.kind, x: event.clientX, y: event.clientY }); + }; + const onPointerUp = (event: React.PointerEvent) => { + const now = press.current; + press.current = null; + setGhost(null); + if (now?.dragging !== true) return; + afterDrag.current = true; + onItem(now.kind, { clientX: event.clientX, clientY: event.clientY }); + }; + + return ( + + ); +} diff --git a/packages/editor/src/design/DocumentationText.tsx b/packages/editor/src/design/DocumentationText.tsx new file mode 100644 index 0000000..c036f09 --- /dev/null +++ b/packages/editor/src/design/DocumentationText.tsx @@ -0,0 +1,79 @@ +// The field a focused text is typed into (Java's JDocuTextArea): over the +// text, at its size, in its font and colour, scaled with the view. It +// follows the document's Y.Text — what others type comes in, the caret kept — +// and writes what is typed with this editor's origin. Escape ends the focus; +// Ctrl+Delete removes the text, as in Java (Delete alone types). + +import { useEffect, useRef } from 'react'; +import type * as Y from 'yjs'; +import { replaceText, type DocumentationView } from '@mdg-filius/doc'; +import type { ScreenFrame } from '../canvas/Canvas.js'; +import { fontFamily, textColor } from '../canvas/documentationPaint.js'; +import { followText } from '../desktop/textBinding.js'; +import { useTranslate } from '../i18n/i18n.js'; + +export interface DocumentationTextProps { + readonly item: DocumentationView; + readonly frame: ScreenFrame; + readonly text: Y.Text; + readonly origin: object; + readonly onDone: () => void; + readonly onRemove: () => void; +} + +export function DocumentationText({ item, frame, text, origin, onDone, onRemove }: DocumentationTextProps) { + const t = useTranslate(); + const area = useRef(null); + useEffect(() => { + const element = area.current; + if (element === null) return undefined; + const stop = followText(element, text, origin); + // Java gives a text the focus when it gets it (a new one at once). + element.focus(); + return stop; + }, [text, origin]); + return ( +