Files
pages/internal/server/macro_expand.go
Anya Tokugawa c1175d389f Implement Knowledge City platform, organizer and DAV integration
Capture accumulated application, UI, CLI, regression tests and design documentation changes, including task project mapping and default CalDAV list naming.

Keep deployment data, backups, local credentials and build artifacts out of Git. Move the Compose enrollment token to an ignored local environment file.
2026-09-27 14:44:43 +09:00

268 lines
8.2 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package server
import (
"context"
"html"
"net/http"
"net/url"
"regexp"
"strings"
"pageswiki/internal/store"
)
var childrenMacroRe = regexp.MustCompile(`\{\{children([^}]*)\}\}`)
var cityMacroRe = regexp.MustCompile(`\{\{(city-breadcrumbs|spot-pages|quartier|street|spot|nearby|city)(?:\s+([^}]*))?\}\}`)
var cityMacroOptionRe = regexp.MustCompile(`([a-z_-]+)=(?:"([^"]*)"|'([^']*)'|([^\s]+))`)
type childrenMacroArgs struct {
TargetPath string
Excludes []string
View string
Offset int
Limit int
}
func parseChildrenMacroArgs(raw, currentPath string) childrenMacroArgs {
targetPath := currentPath
excludeRaw := ""
raw = strings.TrimSpace(raw)
parts := strings.Fields(raw)
if strings.HasPrefix(raw, ":") {
parts = strings.Fields(strings.TrimSpace(strings.TrimPrefix(raw, ":")))
if len(parts) > 0 && !strings.Contains(parts[0], "=") {
targetPath = parts[0]
parts = parts[1:]
}
}
for _, part := range parts {
switch {
case strings.HasPrefix(part, "exclude="):
excludeRaw = strings.TrimPrefix(part, "exclude=")
}
}
if !strings.HasPrefix(targetPath, "/") {
targetPath = "/" + targetPath
}
return childrenMacroArgs{
TargetPath: targetPath,
Excludes: splitExcludePatterns(excludeRaw),
View: "list",
Limit: 120,
}
}
func splitExcludePatterns(raw string) []string {
var out []string
for _, pattern := range strings.Split(raw, ",") {
pattern = strings.TrimSpace(pattern)
if pattern == "" {
continue
}
if !strings.HasPrefix(pattern, "/") {
pattern = "/" + pattern
}
out = append(out, pattern)
}
return out
}
func isExcludedPath(path string, patterns []string) bool {
path = strings.TrimRight(path, "/")
for _, pattern := range patterns {
pattern = strings.TrimRight(pattern, "/")
if pattern != "" &&
(path == pattern || strings.HasPrefix(path, pattern+"/")) {
return true
}
}
return false
}
func (s *Server) expandMacros(
body string,
currentPath string,
domainUUID string,
) string {
return s.expandMacrosFiltered(body, currentPath, domainUUID, nil)
}
func (s *Server) expandMacrosForRequest(r *http.Request, body, currentPath, domainUUID string) string {
return s.expandMacrosFilteredContext(r.Context(), body, currentPath, domainUUID, s.pathReadFilter(r))
}
func (s *Server) expandMacrosFiltered(body, currentPath, domainUUID string, allowed func(string) bool) string {
return s.expandMacrosFilteredContext(context.Background(), body, currentPath, domainUUID, allowed)
}
func (s *Server) expandMacrosFilteredContext(ctx context.Context, body, currentPath, domainUUID string, allowed func(string) bool) string {
body = s.expandCityMacrosContext(ctx, body, currentPath, domainUUID, allowed)
return s.expandChildrenMacros(body, currentPath)
}
func (s *Server) expandChildrenMacros(body, currentPath string) string {
return childrenMacroRe.ReplaceAllStringFunc(body, func(macro string) string {
match := childrenMacroRe.FindStringSubmatch(macro)
raw := ""
if len(match) >= 2 {
raw = match[1]
}
args := parseChildrenMacroArgs(raw, currentPath)
query := url.Values{
"path": {args.TargetPath},
}
if len(args.Excludes) > 0 {
query.Set("exclude", strings.Join(args.Excludes, ","))
}
source := "/v/children?" + query.Encode()
return `<section class="children-list children-async" ` +
`data-children-path="` + html.EscapeString(args.TargetPath) + `" ` +
`data-children-exclude="` + html.EscapeString(strings.Join(args.Excludes, ",")) + `" ` +
`data-children-src="` + html.EscapeString(source) + `">` +
`<div class="children-loading" role="status">Loading…</div>` +
`</section>`
})
}
func (s *Server) expandCityMacros(body, currentPath, domainUUID string, allowed func(string) bool) string {
return s.expandCityMacrosContext(context.Background(), body, currentPath, domainUUID, allowed)
}
func (s *Server) expandCityMacrosContext(ctx context.Context, body, currentPath, domainUUID string, allowed func(string) bool) string {
if !cityMacroRe.MatchString(body) || s.store == nil {
return body
}
context, err := s.store.ResolveCityPathContextWithContext(ctx, domainUUID, currentPath)
if err != nil {
return body
}
var city store.CityMap
cityLoaded := false
if allowed != nil {
if context.Quartier != nil && !allowed(context.Quartier.PathPrefix) {
context.Quartier = nil
context.Street = nil
context.Spot = nil
}
if context.Street != nil && !allowed(context.Street.PathPrefix) {
context.Street = nil
context.Spot = nil
}
if context.Spot != nil && !allowed(context.Spot.PathPrefix) {
context.Spot = nil
}
}
link := func(kind string, node *store.CityNodeDetail) string {
if node == nil {
return `<span class="city-macro-empty">—</span>`
}
quartierName := ""
if context.Quartier != nil {
quartierName = context.Quartier.Name
}
return `<a href="` + html.EscapeString(cityDetailHref(kind, node.Name, quartierName, node.UUID)) + `">` + html.EscapeString(node.Title) + `</a>`
}
return cityMacroRe.ReplaceAllStringFunc(body, func(macro string) string {
if ctx.Err() != nil {
return macro
}
match := cityMacroRe.FindStringSubmatch(macro)
name, raw := match[1], match[2]
options := map[string]string{}
for _, option := range cityMacroOptionRe.FindAllStringSubmatch(raw, -1) {
value := option[2]
if value == "" {
value = option[3]
}
if value == "" {
value = option[4]
}
options[option[1]] = value
}
switch name {
case "city":
return `<nav class="city-macro city-macro-city"><a href="/v/city">City Map</a></nav>`
case "quartier":
return `<span class="city-macro city-macro-quartier">` + link("quartier", context.Quartier) + `</span>`
case "street":
return `<span class="city-macro city-macro-street">` + link("street", context.Street) + `</span>`
case "spot":
return `<span class="city-macro city-macro-spot">` + link("spot", context.Spot) + `</span>`
case "city-breadcrumbs":
parts := []string{`<a href="/v/city">City</a>`}
if context.Quartier != nil {
parts = append(parts, link("quartier", context.Quartier))
}
if context.Street != nil {
parts = append(parts, link("street", context.Street))
}
if context.Spot != nil {
parts = append(parts, link("spot", context.Spot))
}
return `<nav class="city-macro city-macro-breadcrumbs" aria-label="City">` + strings.Join(parts, `<span>›</span>`) + `</nav>`
case "spot-pages":
if context.Spot == nil {
return `<div class="city-macro city-macro-pages"></div>`
}
pages, err := s.store.ListSpotPagesContext(ctx, domainUUID, context.Spot.UUID)
if err != nil {
return macro
}
items := []string{}
for _, page := range pages {
if ctx.Err() != nil {
return macro
}
if allowed != nil && (page.Path == "" || !allowed(page.Path)) {
continue
}
if edge := options["edge"]; edge != "" && page.EdgeType != edge {
continue
}
label := page.Label
if label == "" {
label = page.Path
}
items = append(items, `<li><a href="`+html.EscapeString(cityPageHref(page.Path))+`">`+html.EscapeString(label)+`</a></li>`)
}
return `<ul class="city-macro city-macro-pages">` + strings.Join(items, "") + `</ul>`
case "nearby":
if context.Spot == nil {
return `<ul class="city-macro city-macro-nearby"></ul>`
}
if !cityLoaded {
city, err = s.store.GetCityMapContext(ctx, domainUUID)
if err != nil {
return macro
}
if allowed != nil {
city = filterCityProjection(city, allowed)
}
cityLoaded = true
}
spots := map[string]store.CitySpot{}
for _, quartier := range city.Quartiers {
for _, street := range quartier.Streets {
for _, spot := range street.Spots {
spots[spot.UUID] = spot
}
}
}
items := []string{}
for _, relation := range city.Relations {
if relation.SourceSpotUUID != context.Spot.UUID || (options["relation"] != "" && relation.RelationType != options["relation"]) {
continue
}
target, ok := spots[relation.TargetSpotUUID]
if ok {
items = append(items, `<li><a href="/v/city/p/`+url.PathEscape(target.Name)+`">`+html.EscapeString(target.Title)+`</a> <small>`+html.EscapeString(relation.RelationType)+`</small></li>`)
}
}
return `<ul class="city-macro city-macro-nearby">` + strings.Join(items, "") + `</ul>`
}
return macro
})
}