middle step

This commit is contained in:
2026-07-28 16:19:17 +02:00
parent ca45f38262
commit 54f115204f
6 changed files with 742 additions and 439 deletions
+52 -103
View File
@@ -22,7 +22,7 @@ type Choice struct {
type StoryNode struct {
ID string `json:"id"`
Title string `json:"title"`
Content template.HTML `json:"content"` // HTML für das Asciidoctor Rendering
Content template.HTML `json:"content"`
Choices []Choice `json:"choices"`
IsReboot bool `json:"isReboot"`
IsEnd bool `json:"isEnd"`
@@ -38,6 +38,14 @@ type StoryGraph struct {
DeadEndNodes []string `json:"deadEndNodes"`
}
// Struct für das saubere Injezieren der Frontend-Komponenten
type TemplateContext struct {
Graph template.JS
CSS template.CSS
Logic template.JS
UI template.JS
}
var (
adocNodeRegex = regexp.MustCompile(`\[\[([a-zA-Z0-9_\-]+)\]\]`)
adocChoiceRegex = regexp.MustCompile(`<<([a-zA-Z0-9_\-]+)\s*,\s*([^>]+)>>`)
@@ -49,12 +57,12 @@ var (
func main() {
dirPtr := flag.String("dir", ".", "Verzeichnis mit AsciiDoc/Markdown Dateien")
outPtr := flag.String("out", "export/story.html", "Zielpfad für den Dateiexport")
tmplPtr := flag.String("tmpl", "template.html", "Pfad zur ausgelagerten HTML/JS Template-Datei")
tmplPtr := flag.String("tmpl", "template.html", "Pfad zur HTML Template-Datei")
servePtr := flag.Bool("serve", false, "Startet den API- & Preview-Server")
portPtr := flag.Int("port", 8080, "Port für den Server")
flag.Parse()
fmt.Println("\033[1;36m=== Computer Historyz :: CYOA Engine (Asciidoctor Bindings) ===\033[0m")
fmt.Println("\033[1;36m=== Computer Historyz :: CYOA Engine (Modular) ===\033[0m")
if *servePtr {
startServer(*portPtr, *dirPtr, *outPtr, *tmplPtr)
@@ -71,26 +79,26 @@ func main() {
fmt.Printf("\033[1;31m[FEHLER]\033[0m %v\n", err)
os.Exit(1)
}
fmt.Printf("\033[1;32m[ERFOLG]\033[0m Story generiert -> \033[1;33m%s\033[0m\n", *outPtr)
fmt.Printf("\033[1;32m[ERFOLG]\033[0m Story modular generiert -> \033[1;33m%s\033[0m\n", *outPtr)
}
// renderAsciidoctor piped rohen AsciiDoc Text in den lokalen Container-Prozess
func renderAsciidoctor(text string) template.HTML {
if strings.TrimSpace(text) == "" {
return ""
func readAsset(basePath, filename string) string {
b, err := os.ReadFile(filepath.Join(filepath.Dir(basePath), filename))
if err != nil {
return fmt.Sprintf("/* %s nicht gefunden */", filename)
}
return string(b)
}
func renderAsciidoctor(text string) template.HTML {
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)
// Fallback auf rohen Text (mit rudimentären Linebreaks), falls asciidoctor fehlschlägt
fallback := strings.ReplaceAll(text, "\n", "<br>")
return template.HTML(fallback)
}
return template.HTML(string(out))
}
@@ -106,86 +114,45 @@ func parseContent(rawContent string, sourceName string, graph *StoryGraph) {
var currentBody strings.Builder
for _, line := range lines {
// Knotenpunkte identifizieren
if matches := adocNodeRegex.FindStringSubmatch(line); len(matches) > 1 {
if currentNode != nil {
// Inhalt über Asciidoctor-Container-Binary exportieren
currentNode.Content = renderAsciidoctor(cleanBodyText(currentBody.String()))
graph.Nodes[currentNode.ID] = currentNode
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 }
}
// Metadaten für das State-System extrahieren
if mMatches := metaRegex.FindStringSubmatch(line); len(mMatches) > 2 {
currentNode.Metadata[strings.ToLower(mMatches[1])] = strings.TrimSpace(mMatches[2])
continue
currentNode.Metadata[strings.ToLower(mMatches[1])] = strings.TrimSpace(mMatches[2]); continue
}
// Titel extrahieren
if hMatches := headingRegex.FindStringSubmatch(line); len(hMatches) > 1 && currentNode.Title == currentNode.ID {
currentNode.Title = strings.TrimSpace(hMatches[1])
}
// Entscheidungen (AsciiDoc)
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])}) }
}
// Entscheidungen (Markdown)
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])}) }
}
// Spezielle System-Tags prüfen
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")
}
if currentNode != nil {
currentNode.Content = renderAsciidoctor(cleanBodyText(currentBody.String()))
graph.Nodes[currentNode.ID] = currentNode
@@ -199,10 +166,7 @@ func loadStoryGraphFromDir(rootDir string) *StoryGraph {
ext := strings.ToLower(filepath.Ext(path))
if ext != ".adoc" && ext != ".md" { return nil }
contentBytes, err := os.ReadFile(path)
if err == nil {
relPath, _ := filepath.Rel(rootDir, path)
parseContent(string(contentBytes), relPath, graph)
}
if err == nil { parseContent(string(contentBytes), filepath.Base(path), graph) }
return nil
})
return graph
@@ -214,37 +178,30 @@ func validateGraph(g *StoryGraph) {
for id, node := range g.Nodes {
for _, choice := range node.Choices {
referenced[choice.TargetID] = true
if _, exists := g.Nodes[choice.TargetID]; !exists {
g.BrokenLinks = append(g.BrokenLinks, fmt.Sprintf("%s -> %s (in %s)", id, choice.TargetID, node.FileSource))
}
}
if len(node.Choices) == 0 && !node.IsReboot && !node.IsEnd {
g.DeadEndNodes = append(g.DeadEndNodes, id)
if _, exists := g.Nodes[choice.TargetID]; !exists { g.BrokenLinks = append(g.BrokenLinks, fmt.Sprintf("%s -> %s (in %s)", id, choice.TargetID, node.FileSource)) }
}
if len(node.Choices) == 0 && !node.IsReboot && !node.IsEnd { g.DeadEndNodes = append(g.DeadEndNodes, id) }
}
for id := range g.Nodes {
if !referenced[id] { g.OrphanNodes = append(g.OrphanNodes, id) }
}
for id := range g.Nodes { if !referenced[id] { g.OrphanNodes = append(g.OrphanNodes, id) } }
}
// JSON Helper für das Template
func getTemplateFuncMap() template.FuncMap {
return template.FuncMap{
"json": func(v interface{}) template.JS {
a, _ := json.Marshal(v)
return template.JS(a)
},
func getContext(graph *StoryGraph, tmplPath string) TemplateContext {
graphJson, _ := json.Marshal(graph)
return TemplateContext{
Graph: template.JS(graphJson),
CSS: template.CSS(readAsset(tmplPath, "style.css")),
Logic: template.JS(readAsset(tmplPath, "engine_logic.js")),
UI: template.JS(readAsset(tmplPath, "engine_ui.js")),
}
}
func generateHTMLFile(g *StoryGraph, outPath string, tmplPath string) error {
fmt.Println("tmp path "+tmplPath)
tmpl, err := template.New(filepath.Base(tmplPath)).Funcs(getTemplateFuncMap()).ParseFiles(tmplPath)
tmpl, err := template.ParseFiles(tmplPath)
if err != nil { return fmt.Errorf("Template-Fehler: %v", err) }
f, err := os.Create(outPath)
if err != nil { return err }
defer f.Close()
return tmpl.Execute(f, g)
return tmpl.Execute(f, getContext(g, tmplPath))
}
func startServer(port int, watchDir string, htmlPath string, tmplPath string) {
@@ -256,33 +213,25 @@ func startServer(port int, watchDir string, htmlPath string, tmplPath string) {
if r.Method == http.MethodPost {
bodyBytes, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Daten defekt", http.StatusBadRequest)
return
}
if err != nil { http.Error(w, "Daten defekt", http.StatusBadRequest); return }
graph := &StoryGraph{Nodes: make(map[string]*StoryNode)}
// Rohdaten durch den Parser und den Asciidoctor-Container schleusen
parseContent(string(bodyBytes), "API_POST_Stream", graph)
validateGraph(graph)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
tmpl, err := template.New(filepath.Base(tmplPath)).Funcs(getTemplateFuncMap()).ParseFiles(tmplPath)
if err != nil {
http.Error(w, "Template-Fehler: "+err.Error(), http.StatusInternalServerError)
return
}
tmpl.Execute(w, graph)
fmt.Println("\033[1;34m[POST-API]\033[0m Story inkl. Asciidoctor-HTML gerendert.")
tmpl, err := template.ParseFiles(tmplPath)
if err != nil { http.Error(w, "Template-Fehler: "+err.Error(), http.StatusInternalServerError); return }
tmpl.Execute(w, getContext(graph, tmplPath))
fmt.Println("\033[1;34m[POST-API]\033[0m Modularer Stack gerendert.")
return
}
if r.Method == http.MethodGet {
freshGraph := loadStoryGraphFromDir(watchDir)
_ = generateHTMLFile(freshGraph, htmlPath, tmplPath)
http.ServeFile(w, r, htmlPath)
}
})
http.ListenAndServe(addr, nil)
}
}