-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspec.go
More file actions
807 lines (717 loc) · 24.5 KB
/
spec.go
File metadata and controls
807 lines (717 loc) · 24.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
package main
import (
"fmt"
"strconv"
"strings"
)
// DiagramSpec represents the logical diagram structure (grid-based)
type DiagramSpec struct {
Boxes []BoxSpec
Arrows []ArrowSpec
Groups []GroupDef
}
// GroupDef represents a visual group that contains boxes
type GroupDef struct {
Name string // Group identifier (e.g., "Team")
Label string // Display label (e.g., "Our Team"); defaults to Name
BoxIDs []string // IDs of boxes belonging to this group
}
// BoxSpec represents a box in grid coordinates
type BoxSpec struct {
ID string
GridX int
GridY int
GridWidth float64 // Width in grid units (default: 2)
GridHeight int // Height in grid units (default: 1)
Label string
Color string // Optional, uses default if empty
BorderColor string // Optional border color (default: black)
BorderWidth int // Optional border width (default: 2)
FontSize int // Optional font size (default: 24)
TextColor string // Optional text color (default: black)
TouchLeft bool // Whether this box touches the previous box ("|" prefix)
Group string // Optional group name this box belongs to (e.g., "Team")
}
// ArrowSpec represents logical connection between boxes
type ArrowSpec struct {
FromID string
ToID string
Flow string // Optional per-arrow flow hint (e.g., "down")
}
// ParsedCoordinate represents a single parsed coordinate with metadata
type ParsedCoordinate struct {
IsRelative bool // true if relative (+/- prefix or "0"), false if absolute
Value int // the numeric value (can be negative for relative)
}
// BoxCoordinates represents the complete coordinate pair for a box
type BoxCoordinates struct {
X ParsedCoordinate // Parsed X coordinate
Y ParsedCoordinate // Parsed Y coordinate
AutoArrow bool // Whether this box had the ">" auto-arrow prefix
GridX int // Resolved absolute grid X
GridY int // Resolved absolute grid Y
}
// BoxStyles represents the parsed style attributes for a box
type BoxStyles struct {
BackgroundColor string
BorderColor string
BorderWidth int
FontSize int
TextColor string
}
// parseCoordinate parses a single coordinate value (GridX or GridY)
// Returns: ParsedCoordinate and error
// Examples:
//
// "5" -> ParsedCoordinate{IsRelative: false, Value: 5} // Absolute
// "+2" -> ParsedCoordinate{IsRelative: true, Value: 2} // Relative positive
// "-1" -> ParsedCoordinate{IsRelative: true, Value: -1} // Relative negative
// "0" -> ParsedCoordinate{IsRelative: true, Value: 0} // Shorthand for "+0"
func parseCoordinate(coordStr string) (ParsedCoordinate, error) {
coordStr = strings.TrimSpace(coordStr)
// Shorthand: "0" means relative zero "+0"
// (Absolute 0 is impossible since grid starts at 1)
if coordStr == "0" {
return ParsedCoordinate{IsRelative: true, Value: 0}, nil
}
// Check for explicit relative prefix
if strings.HasPrefix(coordStr, "+") {
// Relative positive
value, err := strconv.Atoi(coordStr[1:])
return ParsedCoordinate{IsRelative: true, Value: value}, err
}
if strings.HasPrefix(coordStr, "-") {
// Relative negative
value, err := strconv.Atoi(coordStr[1:])
if err != nil {
return ParsedCoordinate{}, err
}
return ParsedCoordinate{IsRelative: true, Value: -value}, nil
}
// Absolute coordinate (no prefix)
value, err := strconv.Atoi(coordStr)
return ParsedCoordinate{IsRelative: false, Value: value}, err
}
// parseBoxStyles parses a style string (e.g., "rb-g-rt") into BoxStyles
// Returns: BoxStyles with parsed attributes
// Supported styles:
// - "rb": Red border (3px width)
// - "g": Gray background
// - "p": Purple background
// - "lp": Light purple background
// - "nbb": No background, no border
// - "rt": Red text
// - "2t": Double text size (48px)
func parseBoxStyles(styleStr string, customColors map[string]string) BoxStyles {
styles := BoxStyles{
BackgroundColor: "",
BorderColor: "",
BorderWidth: 0,
FontSize: 0,
TextColor: "",
}
if styleStr == "" {
return styles
}
styleParts := strings.Split(styleStr, "-")
for _, style := range styleParts {
style = strings.TrimSpace(style)
switch style {
case "rb":
styles.BorderColor = "#FF0000" // Red
styles.BorderWidth = 3 // Bold (3px instead of default 2px)
case "g":
styles.BackgroundColor = "#D3D3D3" // Gray
case "p":
styles.BackgroundColor = "#ecbae6" // Purple
case "lp":
styles.BackgroundColor = "#f5dbf2" // Light purple
case "nbb":
styles.BackgroundColor = "none" // No background
styles.BorderColor = "none" // No border
styles.BorderWidth = 0
case "rt":
styles.TextColor = "#FF0000" // Red text
case "2t":
styles.FontSize = 48 // 200% of default 24
default:
// Check custom colors: "green" → background, "greent" → text color
if customColors != nil {
if hex, ok := customColors[style]; ok {
styles.BackgroundColor = hex
} else if strings.HasSuffix(style, "t") {
name := style[:len(style)-1]
if hex, ok := customColors[name]; ok {
styles.TextColor = hex
}
}
}
}
}
return styles
}
// parseNumberOrFraction parses a string that can be an integer, decimal, or fraction
// Examples:
// - Integer: "2" → 2.0
// - Decimal: "1.5" → 1.5
// - Fraction: "1/2" → 0.5, "3/4" → 0.75
//
// Returns the float64 value and any parsing error
func parseNumberOrFraction(s string) (float64, error) {
s = strings.TrimSpace(s)
// Check if it's a fraction (contains "/")
if strings.Contains(s, "/") {
parts := strings.Split(s, "/")
if len(parts) != 2 {
return 0, fmt.Errorf("invalid fraction '%s': must be 'numerator/denominator'", s)
}
// Parse numerator
numerator, err := strconv.ParseFloat(strings.TrimSpace(parts[0]), 64)
if err != nil {
return 0, fmt.Errorf("invalid fraction '%s': %w", s, err)
}
// Parse denominator
denominator, err := strconv.ParseFloat(strings.TrimSpace(parts[1]), 64)
if err != nil {
return 0, fmt.Errorf("invalid fraction '%s': %w", s, err)
}
// Check for division by zero
if denominator == 0 {
return 0, fmt.Errorf("invalid fraction '%s': division by zero", s)
}
return numerator / denominator, nil
}
// Not a fraction, parse as regular float
return strconv.ParseFloat(s, 64)
}
// LegendEntry represents a single legend item mapping a style code to a description
type LegendEntry struct {
Style string // Style code (e.g., "p", "g", "lp")
Label string // Human-readable description
}
// Frontmatter represents metadata parsed from the top of a diagram file
type Frontmatter struct {
Font string // Path to custom font file (WOFF2 format)
XLabel string // X-axis label; empty string (default) = no axis drawn
YLabel string // Y-axis label; empty string (default) = no axis drawn
Legend []LegendEntry // Legend entries mapping style codes to descriptions
Colors map[string]string // Custom color definitions (name -> hex)
ArrowFlow string // Global arrow flow direction (e.g., "down" for top-down routing)
}
// ParseFrontmatter extracts frontmatter key:value pairs from the top of diagram text.
// Returns the parsed frontmatter and the remaining text with frontmatter lines stripped.
// Supports two formats:
// 1. Delimited: lines between opening and closing "---" markers
// 2. Undelimited: key:value lines at the top (stops at first unrecognized line)
//
// Recognized keys: font
// Comments (#) and blank lines are allowed within frontmatter.
func ParseFrontmatter(text string) (Frontmatter, string) {
var fm Frontmatter
lines := strings.Split(text, "\n")
consumedLines := 0
// Skip leading blank lines and comments to find potential "---" opener
for consumedLines < len(lines) {
trimmed := strings.TrimSpace(lines[consumedLines])
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
consumedLines++
continue
}
break
}
// Check for delimited frontmatter (--- ... ---)
if consumedLines < len(lines) && strings.TrimSpace(lines[consumedLines]) == "---" {
consumedLines++ // consume opening ---
for consumedLines < len(lines) {
trimmed := strings.TrimSpace(lines[consumedLines])
// Closing delimiter ends frontmatter
if trimmed == "---" {
consumedLines++ // consume closing ---
remaining := strings.Join(lines[consumedLines:], "\n")
return fm, remaining
}
consumedLines++
parseFrontmatterKey(&fm, trimmed)
}
// Reached end of input without closing ---; treat entire input as frontmatter
return fm, ""
}
// Undelimited frontmatter: reset and scan from the top
consumedLines = 0
for consumedLines < len(lines) {
trimmed := strings.TrimSpace(lines[consumedLines])
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
consumedLines++
continue
}
if parseFrontmatterKey(&fm, trimmed) {
consumedLines++
continue
}
// First unrecognized line ends frontmatter
break
}
remaining := strings.Join(lines[consumedLines:], "\n")
return fm, remaining
}
// parseFrontmatterKey parses a single frontmatter line into the Frontmatter struct.
// Returns true if the line was a recognized key.
func parseFrontmatterKey(fm *Frontmatter, trimmed string) bool {
// Skip blank lines and comments
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
return true
}
if strings.HasPrefix(trimmed, "font:") {
fm.Font = strings.TrimSpace(strings.TrimPrefix(trimmed, "font:"))
return true
}
if strings.HasPrefix(trimmed, "x-label:") {
fm.XLabel = strings.TrimSpace(strings.TrimPrefix(trimmed, "x-label:"))
return true
}
if strings.HasPrefix(trimmed, "y-label:") {
fm.YLabel = strings.TrimSpace(strings.TrimPrefix(trimmed, "y-label:"))
return true
}
if strings.HasPrefix(trimmed, "legend:") {
value := strings.TrimSpace(strings.TrimPrefix(trimmed, "legend:"))
parts := strings.SplitN(value, "=", 2)
if len(parts) == 2 {
entry := LegendEntry{
Style: strings.TrimSpace(parts[0]),
Label: strings.TrimSpace(parts[1]),
}
fm.Legend = append(fm.Legend, entry)
}
return true
}
if strings.HasPrefix(trimmed, "arrow-flow:") {
fm.ArrowFlow = strings.TrimSpace(strings.TrimPrefix(trimmed, "arrow-flow:"))
return true
}
if strings.HasPrefix(trimmed, "color:") {
value := strings.TrimSpace(strings.TrimPrefix(trimmed, "color:"))
parts := strings.SplitN(value, "=", 2)
if len(parts) == 2 {
name := strings.TrimSpace(parts[0])
hex := strings.TrimSpace(parts[1])
if fm.Colors == nil {
fm.Colors = make(map[string]string)
}
fm.Colors[name] = hex
}
return true
}
return false
}
// ParseDiagramSpec parses the text format into a DiagramSpec
func ParseDiagramSpec(text string, customColors map[string]string) (*DiagramSpec, error) {
spec := &DiagramSpec{
Boxes: []BoxSpec{},
Arrows: []ArrowSpec{},
}
lines := strings.Split(text, "\n")
var previousBoxID string // Track previous box for auto-arrows
var previousGridX int // Track previous box GridX for relative coordinates
var previousGridY int // Track previous box GridY for relative coordinates
internalIDCounter := 0 // Counter for generating internal IDs for unlabeled boxes
groupDefs := make(map[string]string) // Group name -> label (from @Group: Label lines)
boxGroups := make(map[string]string) // Box ID -> group name (from @Group suffix on box lines)
// Container state (purely organizational, no visual rendering)
var inContainer bool
var containerID string
var containerBaseX, containerBaseY int
var containerBoxIDs []string
for _, line := range lines {
line = strings.TrimSpace(line)
if line == "" {
continue
}
// Skip comment lines
if strings.HasPrefix(line, "#") {
continue
}
// Detect container closing "]" with optional @GroupName suffix
if line == "]" || strings.HasPrefix(line, "] ") {
if !inContainer {
return nil, fmt.Errorf("unexpected ']' outside container")
}
// Check for @GroupName suffix on the closing line
if suffix := strings.TrimSpace(strings.TrimPrefix(line, "]")); suffix != "" {
if !strings.HasPrefix(suffix, "@") {
return nil, fmt.Errorf("invalid container closing syntax: '%s' (expected '] @GroupName')", line)
}
containerGroup := strings.TrimPrefix(suffix, "@")
for _, boxID := range containerBoxIDs {
boxGroups[boxID] = containerGroup
// Update BoxSpec.Group field as well
for i := range spec.Boxes {
if spec.Boxes[i].ID == boxID {
spec.Boxes[i].Group = containerGroup
break
}
}
}
}
inContainer = false
containerID = ""
containerBoxIDs = nil
continue
}
// Detect container header: line ends with "["
if strings.HasSuffix(line, "[") {
if inContainer {
return nil, fmt.Errorf("nested containers not supported")
}
// Strip "[" and trim
headerStr := strings.TrimSpace(strings.TrimSuffix(line, "["))
// Parse: "ID: x,y [" or "ID: x,y: Label ["
headerParts := strings.SplitN(headerStr, ":", 3)
if len(headerParts) < 2 {
return nil, fmt.Errorf("invalid container definition: '%s'", line)
}
containerID = strings.TrimSpace(headerParts[0])
coordsStr := strings.TrimSpace(headerParts[1])
coords := strings.Split(coordsStr, ",")
if len(coords) != 2 {
return nil, fmt.Errorf("invalid container coordinates: '%s'", line)
}
baseX, err := strconv.Atoi(strings.TrimSpace(coords[0]))
if err != nil {
return nil, fmt.Errorf("invalid container X coordinate in line: '%s'", line)
}
baseY, err := strconv.Atoi(strings.TrimSpace(coords[1]))
if err != nil {
return nil, fmt.Errorf("invalid container Y coordinate in line: '%s'", line)
}
containerBaseX = baseX
containerBaseY = baseY
// Set previous position to container base so relative coords inside work
previousGridX = containerBaseX
previousGridY = containerBaseY
inContainer = true
continue
}
// Arrow lines (containing "->") are recognized anywhere
if strings.Contains(line, "->") {
parts := strings.Split(line, "->")
if len(parts) == 2 {
from := strings.TrimSpace(parts[0])
toAndFlow := strings.TrimSpace(parts[1])
// Parse optional "| flow" suffix (e.g., "HE | down")
var to, arrowFlow string
if pipeIdx := strings.Index(toAndFlow, "|"); pipeIdx >= 0 {
to = strings.TrimSpace(toAndFlow[:pipeIdx])
arrowFlow = strings.TrimSpace(toAndFlow[pipeIdx+1:])
} else {
to = toAndFlow
}
if from != "" && to != "" {
// Auto-scope arrow IDs inside containers
if inContainer {
from = containerID + "." + from
to = containerID + "." + to
}
// Manual arrows cannot reference internal IDs
if strings.HasPrefix(from, "_box_") || strings.Contains(from, "._box_") {
return nil, fmt.Errorf("arrow '%s -> %s' references box without explicit label (internal ID: %s)", from, to, from)
}
if strings.HasPrefix(to, "_box_") || strings.Contains(to, "._box_") {
return nil, fmt.Errorf("arrow '%s -> %s' references box without explicit label (internal ID: %s)", from, to, to)
}
spec.Arrows = append(spec.Arrows, ArrowSpec{
FromID: from,
ToID: to,
Flow: arrowFlow,
})
continue
}
}
}
// Check for group definition line: @GroupName: Label
if strings.HasPrefix(line, "@") {
groupLine := line[1:] // Strip "@"
groupParts := strings.SplitN(groupLine, ":", 2)
if len(groupParts) == 0 {
continue
}
groupName := strings.TrimSpace(groupParts[0])
groupLabel := groupName // Default label is the group name
if len(groupParts) == 2 {
groupLabel = strings.TrimSpace(groupParts[1])
}
groupDefs[groupName] = groupLabel
continue
}
// Parse box: "dev: 1,2: Sprint Planning" or ">3,2: Daily Standup" (no ID)
parts := strings.SplitN(line, ":", 3)
var id string
var coordsAndLabelParts []string
if len(parts) == 3 {
// Format: "ID: coords: label"
id = strings.TrimSpace(parts[0])
// Validate ID: alphanumeric + underscore + hyphen only
if id == "" {
return nil, fmt.Errorf("invalid box definition: empty ID in line '%s'", line)
}
for _, ch := range id {
if (ch < 'a' || ch > 'z') && (ch < 'A' || ch > 'Z') &&
(ch < '0' || ch > '9') && ch != '_' && ch != '-' {
return nil, fmt.Errorf("invalid ID '%s': must contain only alphanumeric characters, underscore, or hyphen", id)
}
}
coordsAndLabelParts = parts[1:3]
} else if len(parts) == 2 {
// Format: "coords: label" (no ID)
id = "" // Will be assigned internal ID if needed
coordsAndLabelParts = parts
} else {
return nil, fmt.Errorf("invalid box definition: '%s'", line)
}
// Generate internal ID for boxes without explicit IDs
if id == "" {
id = fmt.Sprintf("_box_%d", internalIDCounter)
internalIDCounter++
}
// Scope box IDs inside containers: "X" → "G.X"
if inContainer {
id = containerID + "." + id
}
// Check for auto-arrow prefix ">" or touch-left prefix "|"
coordsStr := strings.TrimSpace(coordsAndLabelParts[0])
autoArrow := strings.HasPrefix(coordsStr, ">")
touchLeft := strings.HasPrefix(coordsStr, "|")
if autoArrow {
// Check if this is the first box
if previousBoxID == "" {
return nil, fmt.Errorf("first box (label '%s') cannot have auto-arrow prefix '>'", id)
}
// Strip the ">" prefix
coordsStr = strings.TrimPrefix(coordsStr, ">")
} else if touchLeft {
// Check if this is the first box
if previousBoxID == "" {
idStr := id
if idStr == "" {
idStr = "(unlabeled)"
}
return nil, fmt.Errorf("first box (label '%s') cannot have touch-left prefix '|'", idStr)
}
// Strip the "|" prefix
coordsStr = strings.TrimPrefix(coordsStr, "|")
}
coords := strings.Split(coordsStr, ",")
if len(coords) != 2 && len(coords) != 3 && len(coords) != 4 {
return nil, fmt.Errorf("invalid coordinate definition: '%s'", line)
}
// Parse GridX coordinate (may be relative or absolute)
coordX, err := parseCoordinate(coords[0])
if err != nil {
return nil, fmt.Errorf("invalid X coordinate in line: '%s'", line)
}
// Parse GridY coordinate (may be relative or absolute)
coordY, err := parseCoordinate(coords[1])
if err != nil {
return nil, fmt.Errorf("invalid Y coordinate in line: '%s'", line)
}
// Parse GridWidth and GridHeight (absolute only)
var gridWidth float64
var gridHeight int
if len(coords) == 4 {
gridWidth, err = parseNumberOrFraction(coords[2])
if err != nil {
return nil, fmt.Errorf("invalid width in line: '%s'", line)
}
gridHeight, err = strconv.Atoi(strings.TrimSpace(coords[3]))
if err != nil {
return nil, fmt.Errorf("invalid height in line: '%s'", line)
}
// Validate dimensions
if gridWidth < 0.2 {
idStr := id
if idStr == "" {
idStr = "(unlabeled)"
}
return nil, fmt.Errorf("box '%s': GridWidth must be >= 0.2, got %.1f", idStr, gridWidth)
}
if gridHeight < 1 {
idStr := id
if idStr == "" {
idStr = "(unlabeled)"
}
return nil, fmt.Errorf("box '%s': GridHeight must be >= 1, got %d", idStr, gridHeight)
}
} else if len(coords) == 3 {
// Custom width, default height
gridWidth, err = parseNumberOrFraction(coords[2])
if err != nil {
return nil, fmt.Errorf("invalid width in line: '%s'", line)
}
gridHeight = 1 // Default height
// Validate width
if gridWidth < 0.2 {
idStr := id
if idStr == "" {
idStr = "(unlabeled)"
}
return nil, fmt.Errorf("box '%s': GridWidth must be >= 0.2, got %.1f", idStr, gridWidth)
}
} else {
// Use defaults (len == 2)
gridWidth = 2.0
gridHeight = 1
}
// Check if first box tries to use relative coordinates
// Inside a container, previousGridX/Y are set to container base, so relative coords are OK
if previousBoxID == "" && !inContainer && (coordX.IsRelative || coordY.IsRelative) {
idStr := id
if idStr == "" {
idStr = "(unlabeled)"
}
return nil, fmt.Errorf("first box (label '%s') cannot use relative coordinates", idStr)
}
// Validate touch-left requirements
if touchLeft {
idStr := id
if idStr == "" {
idStr = "(unlabeled)"
}
// Y coordinate must be 0 (relative, same row)
if !coordY.IsRelative || coordY.Value != 0 {
return nil, fmt.Errorf("box '%s': touch-left prefix '|' requires Y coordinate to be 0 (same row as previous box)", idStr)
}
// X coordinate must be relative with "+" prefix (positive relative)
if !coordX.IsRelative || coordX.Value <= 0 {
return nil, fmt.Errorf("box '%s': touch-left prefix '|' requires X coordinate to be relative with '+' prefix (e.g. '+2'), got relative=%v value=%d", idStr, coordX.IsRelative, coordX.Value)
}
}
// Resolve coordinates
var gridX, gridY int
if coordX.IsRelative {
gridX = previousGridX + coordX.Value
} else if inContainer {
gridX = containerBaseX + coordX.Value
} else {
gridX = coordX.Value
}
if coordY.IsRelative {
gridY = previousGridY + coordY.Value
} else if inContainer {
gridY = containerBaseY + coordY.Value
} else {
gridY = coordY.Value
}
// Validate that resulting coordinates are positive
if gridX < 1 {
idStr := id
if idStr == "" {
idStr = "(unlabeled)"
}
return nil, fmt.Errorf("box '%s': relative GridX coordinate resulted in invalid value %d (must be >= 1)", idStr, gridX)
}
if gridY < 1 {
idStr := id
if idStr == "" {
idStr = "(unlabeled)"
}
return nil, fmt.Errorf("box '%s': relative GridY coordinate resulted in invalid value %d (must be >= 1)", idStr, gridY)
}
// Parse label and optional style attributes
labelAndStyle := strings.TrimSpace(coordsAndLabelParts[1])
// Extract @GroupName suffix (e.g., "Stefanie, p @Team" -> group="Team")
var groupName string
if atIdx := strings.LastIndex(labelAndStyle, " @"); atIdx >= 0 {
groupName = strings.TrimSpace(labelAndStyle[atIdx+2:])
labelAndStyle = strings.TrimSpace(labelAndStyle[:atIdx])
}
labelParts := strings.SplitN(labelAndStyle, ",", 2)
if len(labelParts) == 0 {
return nil, fmt.Errorf("invalid label format: %s", labelAndStyle)
}
label := strings.TrimSpace(labelParts[0])
// Parse optional styles (e.g., "rb-g" -> red border + gray background)
var styleStr string
if len(labelParts) == 2 {
styleStr = strings.TrimSpace(labelParts[1])
}
parsedStyles := parseBoxStyles(styleStr, customColors)
backgroundColor := parsedStyles.BackgroundColor
borderColor := parsedStyles.BorderColor
borderWidth := parsedStyles.BorderWidth
fontSize := parsedStyles.FontSize
textColor := parsedStyles.TextColor
spec.Boxes = append(spec.Boxes, BoxSpec{
ID: id,
GridX: gridX,
GridY: gridY,
GridWidth: gridWidth,
GridHeight: gridHeight,
Label: label,
Color: backgroundColor,
BorderColor: borderColor,
BorderWidth: borderWidth,
FontSize: fontSize,
TextColor: textColor,
TouchLeft: touchLeft,
Group: groupName,
})
// Track box IDs inside the current container
if inContainer {
containerBoxIDs = append(containerBoxIDs, id)
}
// Track box-to-group mapping
if groupName != "" {
boxGroups[id] = groupName
}
// Create auto-arrow if prefix was present
if autoArrow {
spec.Arrows = append(spec.Arrows, ArrowSpec{
FromID: previousBoxID,
ToID: id,
})
}
// Update previous box tracking
previousBoxID = id
previousGridX = gridX
previousGridY = gridY
}
// Check for unclosed container
if inContainer {
return nil, fmt.Errorf("unclosed container '%s'", containerID)
}
// Validate that all arrows reference existing boxes
validBoxIDs := make(map[string]bool)
for _, box := range spec.Boxes {
// All boxes now have IDs (either explicit or internal)
validBoxIDs[box.ID] = true
}
for _, arrow := range spec.Arrows {
if !validBoxIDs[arrow.FromID] {
return nil, fmt.Errorf("arrow '%s -> %s' references non-existent box label '%s'", arrow.FromID, arrow.ToID, arrow.FromID)
}
if !validBoxIDs[arrow.ToID] {
return nil, fmt.Errorf("arrow '%s -> %s' references non-existent box label '%s'", arrow.FromID, arrow.ToID, arrow.ToID)
}
}
// Build groups from box assignments and group definitions
groupBoxIDs := make(map[string][]string) // group name -> list of box IDs
var groupOrder []string // preserve first-seen order
for boxID, gName := range boxGroups {
if _, seen := groupBoxIDs[gName]; !seen {
groupOrder = append(groupOrder, gName)
}
groupBoxIDs[gName] = append(groupBoxIDs[gName], boxID)
}
for _, gName := range groupOrder {
label := gName // default label is the group name
if defLabel, ok := groupDefs[gName]; ok {
label = defLabel
}
spec.Groups = append(spec.Groups, GroupDef{
Name: gName,
Label: label,
BoxIDs: groupBoxIDs[gName],
})
}
return spec, nil
}