working for, now writing

This commit is contained in:
2026-07-28 18:31:05 +02:00
parent efed783e25
commit df33002d30
9 changed files with 337 additions and 714 deletions
+49 -102
View File
@@ -21,7 +21,7 @@ type Choice struct {
type StoryNode struct {
ID string `json:"id"`
Title string `json:"title"`
Content string `json:"content"` // Reiner String, JSON kümmert sich um das Escaping des HTMLs
Content string `json:"content"`
Choices []Choice `json:"choices"`
IsReboot bool `json:"isReboot"`
IsEnd bool `json:"isEnd"`
@@ -48,13 +48,13 @@ var (
func main() {
dirPtr := flag.String("dir", "./stories", "Verzeichnis mit AsciiDoc/Markdown Dateien")
frontendPtr := flag.String("frontend", "./frontend", "Pfad zum Verzeichnis der statischen Frontend-Dateien")
outPtr := flag.String("out", "export/story.html", "Zielpfad für den Dateiexport (Single-File HTML)")
servePtr := flag.Bool("serve", false, "Startet den API- & Preview-Server, statt zu exportieren")
outPtr := flag.String("out", "export", "Ziel-Ordner für den Dateiexport (SSG Modus)")
servePtr := flag.Bool("serve", false, "Startet den Live-Preview-Server (API Modus)")
portPtr := flag.Int("port", 3344, "Port für den Server")
flag.Parse()
fmt.Println("\033[1;36m=== Computer Historyz :: CYOA Engine ===\033[0m")
fmt.Println("\033[1;36m=== Computer Historyz :: CYOA SSG & API ===\033[0m")
if info, err := os.Stat(*frontendPtr); os.IsNotExist(err) || !info.IsDir() {
fmt.Printf("\033[1;33m[WARNUNG]\033[0m Frontend-Verzeichnis '%s' nicht gefunden!\n", *frontendPtr)
}
@@ -64,104 +64,79 @@ func main() {
return
}
// --- EXPORT MODUS ---
fmt.Printf("\033[1;34m[EXPORT]\033[0m Kompiliere Story-Graph via Asciidoctor aus '%s'...\n", *dirPtr)
// --- EXPORT MODUS (Static Site Generation) ---
fmt.Printf("\033[1;34m[EXPORT]\033[0m Kompiliere Story-Graph via Asciidoctor...\n")
graph := loadStoryGraphFromDir(*dirPtr)
validateGraph(graph)
outDir := filepath.Dir(*outPtr)
os.MkdirAll(outDir, 0755)
// Export Ordner anlegen
os.MkdirAll(*outPtr, 0755)
err := buildSingleFileExport(graph, *frontendPtr, *outPtr)
// 1. Statische Daten als JSON schreiben
graphPath := filepath.Join(*outPtr, "graph.json")
graphJson, _ := json.MarshalIndent(graph, "", " ")
os.WriteFile(graphPath, graphJson, 0644)
// 2. Frontend-Dateien 1:1 kopieren
copyFile(filepath.Join(*frontendPtr, "index.html"), filepath.Join(*outPtr, "index.html"))
copyFile(filepath.Join(*frontendPtr, "style.css"), filepath.Join(*outPtr, "style.css"))
copyFile(filepath.Join(*frontendPtr, "engine_logic.js"), filepath.Join(*outPtr, "engine_logic.js"))
copyFile(filepath.Join(*frontendPtr, "engine_ui.js"), filepath.Join(*outPtr, "engine_ui.js"))
fmt.Printf("\033[1;32m[ERFOLG]\033[0m Web-App erfolgreich exportiert nach -> \033[1;33m%s/\033[0m\n", *outPtr)
}
func copyFile(src, dst string) {
input, err := os.ReadFile(src)
if err != nil {
fmt.Printf("\033[1;31m[FEHLER]\033[0m Build fehlgeschlagen: %v\n", err)
os.Exit(1)
fmt.Printf("\033[1;33m[WARNUNG]\033[0m Frontend-Datei %s fehlt.\n", src)
return
}
fmt.Printf("\033[1;32m[ERFOLG]\033[0m Single-File Story exportiert -> \033[1;33m%s\033[0m\n", *outPtr)
os.WriteFile(dst, input, 0644)
}
func startServer(port int, watchDir string, frontendDir string) {
addr := fmt.Sprintf(":%d", port)
fmt.Printf("\n\033[1;32m[SERVER LÄUFT]\033[0m http://localhost:%d\n", port)
http.HandleFunc("/api/graph", func(w http.ResponseWriter, r *http.Request) {
// Dynamischer API-Endpunkt für graph.json
http.HandleFunc("/graph.json", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Type", "application/json")
var graph *StoryGraph
if r.Method == http.MethodPost {
bodyBytes, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, `{"error": "Daten defekt"}`, http.StatusBadRequest)
return
}
graph := &StoryGraph{Nodes: make(map[string]*StoryNode)}
bodyBytes, _ := io.ReadAll(r.Body)
graph = &StoryGraph{Nodes: make(map[string]*StoryNode)}
parseContent(string(bodyBytes), "API_POST_Stream", graph)
validateGraph(graph)
json.NewEncoder(w).Encode(graph)
fmt.Println("\033[1;34m[POST-API]\033[0m Story-Graph verarbeitet.")
return
}
if r.Method == http.MethodGet {
graph := loadStoryGraphFromDir(watchDir)
validateGraph(graph)
json.NewEncoder(w).Encode(graph)
} else {
graph = loadStoryGraphFromDir(watchDir)
}
validateGraph(graph)
json.NewEncoder(w).Encode(graph)
})
// Liefert alles andere aus dem /frontend Ordner
fs := http.FileServer(http.Dir(frontendDir))
http.Handle("/", fs)
fmt.Printf("\n\033[1;32m[SERVER LÄUFT]\033[0m http://localhost:%d\n", port)
if err := http.ListenAndServe(addr, nil); err != nil {
fmt.Printf("\033[1;31m[FEHLER]\033[0m %v\n", err)
}
}
func buildSingleFileExport(graph *StoryGraph, frontendDir string, outPath string) error {
indexPath := filepath.Join(frontendDir, "index.html")
htmlBytes, err := os.ReadFile(indexPath)
if err != nil {
return fmt.Errorf("konnte %s nicht lesen: %v", indexPath, err)
}
htmlStr := string(htmlBytes)
cssBytes, _ := os.ReadFile(filepath.Join(frontendDir, "style.css"))
logicBytes, _ := os.ReadFile(filepath.Join(frontendDir, "engine_logic.js"))
uiBytes, _ := os.ReadFile(filepath.Join(frontendDir, "engine_ui.js"))
graphJson, _ := json.Marshal(graph)
// CSS ersetzen
htmlStr = strings.Replace(htmlStr, `<link rel="stylesheet" href="style.css">`, fmt.Sprintf("<style>\n%s\n</style>", string(cssBytes)), 1)
// JS ersetzen
htmlStr = strings.Replace(htmlStr, `<script src="engine_logic.js"></script>`, fmt.Sprintf("<script>\n%s\n</script>", string(logicBytes)), 1)
htmlStr = strings.Replace(htmlStr, `<script src="engine_ui.js"></script>`, fmt.Sprintf("<script>\n%s\n</script>", string(uiBytes)), 1)
// JSON State in den Data-Block pressen
re := regexp.MustCompile(`(?s)<script id="story-data" type="application/json">.*?</script>`)
htmlStr = re.ReplaceAllString(htmlStr, fmt.Sprintf("<script id=\"story-data\" type=\"application/json\">\n%s\n</script>", string(graphJson)))
return os.WriteFile(outPath, []byte(htmlStr), 0644)
}
// renderAsciidoctor piped rohen AsciiDoc Text in den lokalen Container-Prozess
func renderAsciidoctor(text string) string {
if strings.TrimSpace(text) == "" {
return ""
}
cmd := exec.Command("asciidoctor", "--embedded", "-")
cmd.Stdin = strings.NewReader(text)
out, err := cmd.Output()
if err != nil {
fmt.Printf("\033[1;33m[WARNUNG]\033[0m Asciidoctor Rendering fehlgeschlagen: %v\n", err)
return strings.ReplaceAll(text, "\n", "<br>")
}
return string(out)
}
@@ -184,38 +159,18 @@ func parseContent(rawContent string, sourceName string, graph *StoryGraph) {
currentBody.Reset()
}
nodeID := matches[1]
currentNode = &StoryNode{
ID: nodeID,
Title: nodeID,
Choices: make([]Choice, 0),
FileSource: sourceName,
Metadata: make(map[string]string),
}
if graph.StartNodeID == "" || nodeID == "start" || nodeID == "node_start" {
graph.StartNodeID = nodeID
}
currentNode = &StoryNode{ ID: nodeID, Title: nodeID, Choices: make([]Choice, 0), FileSource: sourceName, Metadata: make(map[string]string) }
if graph.StartNodeID == "" || nodeID == "start" || nodeID == "node_start" { graph.StartNodeID = nodeID }
continue
}
if currentNode == nil {
if strings.TrimSpace(line) != "" {
baseID := "start"
if sourceName != "API_POST_Stream" {
baseID = strings.TrimSuffix(filepath.Base(sourceName), filepath.Ext(sourceName))
}
currentNode = &StoryNode{
ID: baseID,
Title: baseID,
Choices: make([]Choice, 0),
FileSource: sourceName,
Metadata: make(map[string]string),
}
if graph.StartNodeID == "" {
graph.StartNodeID = baseID
}
} else {
continue
}
if sourceName != "API_POST_Stream" { baseID = strings.TrimSuffix(filepath.Base(sourceName), filepath.Ext(sourceName)) }
currentNode = &StoryNode{ ID: baseID, Title: baseID, Choices: make([]Choice, 0), FileSource: sourceName, Metadata: make(map[string]string) }
if graph.StartNodeID == "" { graph.StartNodeID = baseID }
} else { continue }
}
if mMatches := metaRegex.FindStringSubmatch(line); len(mMatches) > 2 {
@@ -228,24 +183,16 @@ func parseContent(rawContent string, sourceName string, graph *StoryGraph) {
}
if cMatches := adocChoiceRegex.FindAllStringSubmatch(line, -1); len(cMatches) > 0 {
for _, match := range cMatches {
currentNode.Choices = append(currentNode.Choices, Choice{TargetID: match[1], Text: strings.TrimSpace(match[2])})
}
for _, match := range cMatches { currentNode.Choices = append(currentNode.Choices, Choice{TargetID: match[1], Text: strings.TrimSpace(match[2])}) }
}
if mMatches := mdChoiceRegex.FindAllStringSubmatch(line, -1); len(mMatches) > 0 {
for _, match := range mMatches {
currentNode.Choices = append(currentNode.Choices, Choice{TargetID: match[2], Text: strings.TrimSpace(match[1])})
}
for _, match := range mMatches { currentNode.Choices = append(currentNode.Choices, Choice{TargetID: match[2], Text: strings.TrimSpace(match[1])}) }
}
lowerLine := strings.ToLower(line)
if strings.Contains(lowerLine, "[reboot]") || strings.Contains(lowerLine, "speicherabbild") {
currentNode.IsReboot = true
}
if strings.Contains(lowerLine, "[ende]") || strings.Contains(lowerLine, "[end]") {
currentNode.IsEnd = true
}
if strings.Contains(lowerLine, "[reboot]") || strings.Contains(lowerLine, "speicherabbild") { currentNode.IsReboot = true }
if strings.Contains(lowerLine, "[ende]") || strings.Contains(lowerLine, "[end]") { currentNode.IsEnd = true }
currentBody.WriteString(line + "\n")
}