Files
pages/internal/server/children_projection.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

336 lines
9.6 KiB
Go

package server
import (
"fmt"
"html"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"pageswiki/internal/store"
)
func (s *Server) handleChildrenProjection(w http.ResponseWriter, r *http.Request) {
args := parseChildrenMacroArgs("", r.URL.Query().Get("path"))
args.View = r.URL.Query().Get("view")
if args.View == "compact" {
args.View = "icon"
}
if args.View != "icon" && args.View != "detail" {
args.View = "list"
}
args.Excludes = splitExcludePatterns(r.URL.Query().Get("exclude"))
args.Offset, _ = strconv.Atoi(r.URL.Query().Get("offset"))
args.Limit, _ = strconv.Atoi(r.URL.Query().Get("limit"))
if args.Limit <= 0 || args.Limit > 400 {
args.Limit = 120
}
rendered, err := s.renderReadableChildren(r, args)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "private, no-store")
_, _ = w.Write([]byte(rendered))
}
func (s *Server) renderChildrenProjection(
domainUUID string,
args childrenMacroArgs,
) (string, error) {
return s.renderChildrenProjectionFiltered(domainUUID, args, nil)
}
func (s *Server) renderChildrenProjectionFiltered(
domainUUID string,
args childrenMacroArgs,
allowed func(string) bool,
) (string, error) {
// /u is a profile/user-Wiki namespace, not a root directory entry. Keep it
// reachable by URL while hiding it from every root children projection,
// including asynchronous view switches and cached continuation requests.
if args.TargetPath == "/" && !isExcludedPath("/u", args.Excludes) {
args.Excludes = append(args.Excludes, "/u")
}
if args.View == "list" {
entries, total, err := s.store.ListChildEntriesPageInDomain(domainUUID, args.TargetPath, args.Offset, args.Limit)
if err != nil {
return "", err
}
var body strings.Builder
body.WriteString(`<ul class="children-view-list">`)
for _, entry := range entries {
child := entry.Path
if isExcludedPath(child, args.Excludes) || (allowed != nil && !allowed(child)) {
continue
}
displayName := entry.Title
if displayName == "" {
displayName = childName(args.TargetPath, child)
}
body.WriteString(fmt.Sprintf(
`<li class="children-entry" data-child-path="%s"><a href="%s">%s</a></li>`,
html.EscapeString(child),
html.EscapeString((&url.URL{Path: child}).EscapedPath()),
html.EscapeString(displayName),
))
}
body.WriteString("</ul>")
writeChildrenMore(
&body,
args,
args.Offset+len(entries),
total,
)
return body.String(), nil
}
entries, total, err := s.store.ListChildEntriesPageInDomain(
domainUUID,
args.TargetPath,
args.Offset,
args.Limit,
)
if err != nil {
return "", err
}
var body strings.Builder
if args.View == "icon" {
body.WriteString(`<div class="children-icon-grid">`)
} else {
body.WriteString(`<table class="children-detail"><thead><tr>` +
`<th>Name</th><th>Type</th><th>Size</th><th>Updated</th>` +
`</tr></thead><tbody>`)
}
for _, entry := range entries {
if isExcludedPath(entry.Path, args.Excludes) || (allowed != nil && !allowed(entry.Path)) {
continue
}
if args.View == "icon" {
body.WriteString(s.renderChildIcon(args.TargetPath, entry))
continue
}
contentType := entry.ContentType
if entry.IsDir {
contentType = "folder"
}
updated := "—"
if entry.UpdatedAt > 0 {
updated = time.Unix(entry.UpdatedAt, 0).Format("2006-01-02 15:04")
}
displayName := entry.Title
if displayName == "" {
displayName = childName(args.TargetPath, entry.Path)
}
body.WriteString(fmt.Sprintf(
`<tr class="children-entry" data-child-path="%s"><td><a href="%s">%s</a></td><td>%s</td><td>%d</td><td>%s</td></tr>`,
html.EscapeString(entry.Path),
html.EscapeString((&url.URL{Path: entry.Path}).EscapedPath()),
html.EscapeString(displayName),
html.EscapeString(contentType),
entry.Size,
updated,
))
}
if args.View == "icon" {
body.WriteString("</div>")
} else {
body.WriteString("</tbody></table>")
}
writeChildrenMore(&body, args, args.Offset+len(entries), total)
return body.String(), nil
}
func writeChildrenMore(
body *strings.Builder,
args childrenMacroArgs,
nextOffset, total int,
) {
if nextOffset >= total {
return
}
query := url.Values{
"path": {args.TargetPath},
"view": {args.View},
"offset": {strconv.Itoa(nextOffset)},
"limit": {strconv.Itoa(args.Limit)},
}
if len(args.Excludes) > 0 {
query.Set("exclude", strings.Join(args.Excludes, ","))
}
body.WriteString(fmt.Sprintf(
`<div class="children-next" data-children-next="%s" aria-label="Load more items"></div>`,
html.EscapeString("/v/children?"+query.Encode()),
))
}
func childName(parent, child string) string {
return strings.TrimPrefix(strings.TrimPrefix(child, parent), "/")
}
func (s *Server) renderChildIcon(parent string, entry store.BrowserEntry) string {
path := html.EscapeString(entry.Path)
name := entry.Title
if name == "" {
name = childName(parent, entry.Path)
}
name = html.EscapeString(name)
preview := s.entryPreviewHTML(entry, true)
return fmt.Sprintf(
`<a class="children-icon-item children-entry" data-child-path="%s" href="%s">%s<span class="children-icon-name">%s</span></a>`,
path,
html.EscapeString((&url.URL{Path: entry.Path}).EscapedPath()),
preview,
name,
)
}
// entryPreviewHTML is shared by directory listings and search results. Callers
// that render broad result sets can disable enqueueing and rely on the periodic
// preview scheduler, avoiding a burst of database writes during navigation.
func (s *Server) entryPreviewHTML(
entry store.BrowserEntry,
enqueueMissing bool,
) string {
if entry.IsDir {
return childTypeIcon("folder")
}
filename := entry.Filename
if filename == "" {
filename = filepath.Base(entry.Path)
}
adapter := selectProjectionAdapter(contentDescriptor{
MediaType: strings.ToLower(strings.Split(entry.ContentType, ";")[0]),
Filename: filename,
SizeBytes: int64(entry.Size),
})
previewURL, cached := s.entryPreviewState(entry, adapter.ID, enqueueMissing)
if cached {
badge := ""
switch adapter.ID {
case "pdf":
badge = "PDF"
case "video":
badge = "▶"
case "excalidraw":
badge = "EX"
case "archive":
badge = "ZIP"
}
badgeHTML := ""
if badge != "" {
badgeHTML = `<span class="children-preview-badge">` + badge + `</span>`
}
return fmt.Sprintf(
`<span class="children-preview children-preview-pending"><img data-preview-kind="image" data-preview-src="%s" alt="">%s</span>`,
html.EscapeString(previewURL),
badgeHTML,
)
}
switch adapter.ID {
case "image":
return pendingPreviewIcon("image", previewURL, "")
case "video":
return pendingPreviewIcon("video", previewURL, "▶")
case "pdf":
return pendingPreviewIcon("pdf", previewURL, "PDF")
case "excalidraw":
return pendingPreviewIcon("drawing", previewURL, "EX")
case "archive":
return childTypeIcon("archive")
case "debian-package":
return childTypeIcon("package")
case "audio":
return childTypeIcon("audio")
case "text", "csv":
if isProgramFilename(filename) {
return childTypeIcon("code")
}
return childTypeIcon("text")
default:
if isProgramFilename(filename) {
return childTypeIcon("code")
}
switch strings.ToLower(filepath.Ext(filename)) {
case ".txt", ".md", ".log", ".rst":
return childTypeIcon("text")
}
return childTypeIcon("file")
}
}
func (s *Server) entryPreviewState(
entry store.BrowserEntry,
kind string,
enqueueMissing bool,
) (string, bool) {
if enqueueMissing {
return s.enqueuePreview(entry)
}
switch kind {
case "image", "pdf", "video", "excalidraw", "archive":
default:
return "", false
}
if s.previewRoot == "" || entry.DocumentHash == "" {
return "", false
}
cacheURL := s.previewCacheURL(entry.DocumentHash, kind)
info, err := os.Stat(s.previewCachePath(entry.DocumentHash, kind))
return cacheURL, err == nil && info.Size() > 0
}
func pendingPreviewIcon(kind, cacheURL, badge string) string {
if cacheURL == "" {
return childTypeIcon(kind)
}
badgeHTML := ""
if badge != "" {
badgeHTML = `<span class="children-preview-badge">` + badge + `</span>`
}
return `<span class="children-preview children-preview-placeholder" ` +
`data-preview-cache="` + html.EscapeString(cacheURL) + `" ` +
`data-preview-badge="` + html.EscapeString(badge) + `">` +
childTypeIcon(kind) + badgeHTML + `</span>`
}
func isProgramFilename(filename string) bool {
switch strings.ToLower(filepath.Ext(filename)) {
case ".py", ".sh", ".bash", ".zsh", ".js", ".jsx", ".ts", ".tsx",
".go", ".rs", ".c", ".h", ".cc", ".cpp", ".java", ".rb", ".php",
".sql", ".css", ".html", ".yaml", ".yml", ".toml":
return true
default:
return false
}
}
func childTypeIcon(kind string) string {
paths := map[string]string{
"folder": `<path d="M3 6h7l2 2h9v11H3z"/>`,
"archive": `<path d="M5 3h14v18H5zM9 3v4h3v4H9v4h3v4H9"/>`,
"package": `<path d="m4 8 8-4 8 4v9l-8 4-8-4zM4 8l8 4 8-4M12 12v9"/>`,
"audio": `<path d="M9 18V6l10-2v12M9 10l10-2M6 21a3 3 0 1 0 0-6 3 3 0 0 0 0 6M16 19a3 3 0 1 0 0-6 3 3 0 0 0 0 6"/>`,
"image": `<path d="M4 5h16v14H4zM7 15l4-4 3 3 2-2 4 4M8 9h.01"/>`,
"video": `<path d="M4 6h12v12H4zM16 10l4-2v8l-4-2z"/>`,
"pdf": `<path d="M6 3h9l4 4v14H6zM15 3v5h4M8 16h2a2 2 0 0 0 0-4H8v6M13 18v-6h3M13 15h3"/>`,
"drawing": `<path d="M4 19l4-1 10-10-3-3L5 15zM13 7l3 3M4 21h16"/>`,
"code": `<path d="m9 7-5 5 5 5M15 7l5 5-5 5M14 4l-4 16"/>`,
"text": `<path d="M6 3h9l4 4v14H6zM15 3v5h4M9 12h7M9 16h7"/>`,
"file": `<path d="M6 3h9l4 4v14H6zM15 3v5h4"/>`,
}
path := paths[kind]
if path == "" {
path = paths["file"]
}
return `<span class="children-type-icon children-type-` + kind +
`" aria-hidden="true"><svg viewBox="0 0 24 24">` + path +
`</svg></span>`
}