From cd3bb4cffca9e1769ee8b3ff0292f0233ac09259 Mon Sep 17 00:00:00 2001 From: Jan Halfar Date: Thu, 5 Nov 2026 16:14:50 +0100 Subject: [PATCH] feat: inlined shape debugger --- CLAUDE.md | 4 +- .../shapes/default.semanticshape.html | 4 +- go/internal/semanticscrape/document_test.go | 52 +++ go/internal/service/gotsrpc_gen.go | 13 +- go/internal/service/gotsrpcclient_gen.go | 6 +- go/internal/service/semanticservice.go | 2 +- go/internal/service/serviceinterface.go | 2 +- go/internal/service/shapeservice.go | 20 +- go/internal/service/shapeservice_test.go | 13 +- go/internal/vo/shape.go | 2 + macos/Walker.xcodeproj/project.pbxproj | 2 + macos/Walker/Generated/ServiceClient.swift | 6 +- macos/Walker/Generated/WalkerVo.swift | 5 +- macos/Walker/Model/ServerModel.swift | 13 + macos/Walker/Model/ServerStore.swift | 31 ++ macos/Walker/Model/SettingsMigration.swift | 2 + macos/Walker/Model/ShapeDevModel.swift | 82 +++- macos/Walker/Views/SemanticOutline.swift | 204 +++++++-- macos/Walker/Views/ServerDetailView.swift | 15 +- macos/Walker/Views/ShapeDevView.swift | 433 +++++++++++++----- macos/Walker/Views/ShapeWebView.swift | 12 - macos/Walker/WalkerApp.swift | 6 - 22 files changed, 703 insertions(+), 226 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 913b7a0..76686ab 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -61,12 +61,12 @@ Most `go/cmd/walker/*.yaml` files are local, site-specific configs and are usual - A zero `time.Time` is encoded as `null`, but a value `time.Time` becomes a non-optional `Date`. Use `*time.Time` for timestamps that can be unset (see `vo.ScrapeSummary`). - go's `time.Duration` (nanoseconds) is `GoTime.Duration`; a bare `Duration` is `Swift.Duration`. - The app has no graph view for now - the 3D graph was removed, the Go side (`GetGraph`, `GetPageGraph`, `GetPageFolderLinks`, `GetFolderPages`) stays and the generated Swift client still has those calls. -- The shape developer window (`ShapeDevView`, `ShapeDevModel`, `ShapeWebView`) iterates on a semantic shape against a live page. It calls `GetShapeRoot`/`ValidateShape`/`GetShapeRootVersion` (`service/shapeservice.go`; the app polls the version every second and validates again when a shape file changes), which load the shape root from a path on the server (client and server share a file system) and return an `semanticshape.TraceNode` tree (`Root.Trace`). Selecting a node highlights its locators in the WKWebView. "Load Config" takes the site (base url + first path) and the shape root (resolved against the config's directory) of a local config (`ShapeDevModel.load`); the window of a local server starts with its own config. The tree (`ShapeTreeView`) writes rules as plain-language chips, marks elements from other shape files (`Source`) and wildcards (`TraceNode.Via`), and shows the details of the selected node inline - neutral selection, a click on the selected row toggles the details, keyboard navigation is its own (List without selection binding). Source references open the editor chosen in the window's toolbar or the settings - one setting, `Editor.key` - at the line (`EditorMenu` greys out editors whose url scheme has no app, `SourceLink`, `zed://file…`, `vscode://file…`). The middle column (`PageDataView`) shows a link preview from the OpenGraph data (`OpenGraphView`), the head and the JSON-LD of the validated html (`semanticshape.ExtractPageData`, same locators as the trace), linked with the tree in both directions. The right column (`OutlinePane`, toolbar toggle, hidden by default) shows the semantic outline of the page from the same source as the validation - for "Rendered" the DOM snapshot goes to `GetSemanticDocument` as html, so selectors match the web view; it reloads with the page (`ShapeDevModel.pageVersion`), the source and the content switch, not with shape edits, and hovering highlights in the page via `ShapeHighlighter.highlight(locators:color:)`. +- The shape developer is the "Shapes" section of a server in the main window (`ShapeDevView` with its control bar instead of toolbar items, `ShapeDevModel` kept per server in `ServerModel.shapeDev`, so it survives switching sections; `ShapeWebView`) and iterates on a semantic shape against a live page. It calls `GetShapeRoot`/`ValidateShape`/`GetShapeRootVersion` (`service/shapeservice.go`; the app polls the version every second and validates again when a shape file changes), which load the shape root from a path on the server (client and server share a file system) and return an `semanticshape.TraceNode` tree (`Root.Trace`). Selecting a node highlights its locators in the WKWebView. A local server brings the shape root of its config, resolved against the config's directory, and its site (base url + first path) as the first page (`ShapeDevModel.follow`, every time the section opens; the shape root menu lists the config's root first, `configRoot`). Without a shape root the section shows only `ShapeRootPrompt`, which makes the user choose a folder; for a local server it is written to the config as `shaperoot` (`ServerStore.setShapeRoot`, relative to the config's directory when inside it). The group header sits next to the group picker (`GroupHeaderButton`): a local server keeps it in its config as `groupheader` (`ServerStore.setGroupHeader`, `follow` reads it back), for a remote one it is an override kept in the app; either way `ValidateShape` gets it as `groupHeader` (empty: the walker's own), so an edit counts before the walker restarts. The tree (`ShapeTreeView`) writes rules as plain-language chips, marks elements from other shape files (`Source`) and wildcards (`TraceNode.Via`), and shows the details of the selected node inline - neutral selection, a click on the selected row toggles the details, keyboard navigation is its own (List without selection binding). Source references open the editor chosen in the window's toolbar or the settings - one setting, `Editor.key` - at the line (`EditorMenu` greys out editors whose url scheme has no app, `SourceLink`, `zed://file…`, `vscode://file…`). The middle column (`PageDataView`) shows a link preview from the OpenGraph data (`OpenGraphView`), the head and the JSON-LD of the validated html (`semanticshape.ExtractPageData`, same locators as the trace), linked with the tree in both directions. The right column (`OutlinePane`, toolbar toggle, hidden by default) shows the semantic outline of the page from the same source as the validation - for "Rendered" the DOM snapshot goes to `GetSemanticDocument` as html, so selectors match the web view; it reloads with the page (`ShapeDevModel.pageVersion`) and the source, not with shape edits; the content of a branch comes from `ShapeDevModel.outlineContent()`, same source, and hovering highlights in the page via `ShapeHighlighter.highlight(locators:color:)`. - The app is **not sandboxed** (hardened runtime only): local walkers read configs and shape roots by path. The "helpers" run script phase builds `go/cmd/walker` and `go/cmd/configvalidator` (`go build -C "$ROOT/go"`) into `Contents/Helpers` (with the Go pinned in `mise.toml`, resolved via `mise which go` with `GOTOOLCHAIN=local` - the build fails if mise is missing or `mise trust && mise install` hasn't run; target `ENABLE_USER_SCRIPT_SANDBOXING = NO`, go needs its module cache). - Configs are edited only in the main window, in the overview of a local server: `LocalConfigForm` is the config form (`ConfigFormView`, fields with notes on the resulting crawl behaviour - keep them in sync with the Go side) with the walker's state on top. It saves to the file right away and rereads it when it changes on disk. Its yaml backend is the `configvalidator` helper; `ConfigTool` talks to it over stdin/stdout JSON. - Local walkers: a `Server` with a `configPath` is a local config (sidebar section "Local"), its `baseURL` follows the config's `addr` (`ServerStore.refreshLocal`, not while its walker runs). `LocalWalkers` (owned by the `AppDelegate`, which stops them on quit) runs the walker helper per config with `-exit-on-stdin-close`, in the config's directory, and keeps state and log (`LocalWalkers.logLines`, a setting, default 10000 lines). Local servers get the normal `ServerDetailView`; their `OverviewView` puts the scrape cards above the log (`LocalWalkerLogPane`) and the config form beside them. - Live metrics (top of the Performance view, `LiveMetrics`, `LiveMetricsView`): the `AppDelegate` (owner of `ServerStore` and `LocalWalkers`) runs `ServerStore.sampleMetrics` for the app's lifetime: every refresh interval it reads the `/metrics` of all servers in parallel (local ones only while running, 5 s timeout) (`PromText` parses the text format) and keeps the charted series for 30 minutes in memory - a local debugging tool. Each `MetricsChart` is evaluated locally (rate, gauge, histogram quantile over bucket increases) and carries the equivalent PromQL, so a Prometheus server backend can answer the same charts later. Charts use one axis each; new metrics need a `kept` entry, a chart case and its PromQL. -- The result inspector (`ResultSections`, shared by the results, folder and broken link inspectors) shows the semantic outline of the whole page (`SemanticOutlineSection`, `SemanticOutline`) instead of the scraped headings - landmarks tinted, navs collapsed with their links, a "Content" switch (`outlineShowsContent`) adds texts, images with thumbnails, figures, lists with markers and tables as grids: the server fetches the live page via `GetSemanticDocument`, the loader comes from the environment (`semanticDocumentLoader`, set in `ServerDetailView`). Hovering an element highlights it in the preview by its selector (`PreviewController.highlight`), headings the selector misses in the live DOM are found by level and text. Title, description, canonical and robots still come from the scrape result's `Structure`. +- The result inspector (`ResultSections`, shared by the results, folder and broken link inspectors) shows the semantic outline of the whole page (`SemanticOutlineSection`, `SemanticOutline`) instead of the scraped headings - landmarks tinted, navs collapsed with their links, it loads without content; clicking an element shows the content of its branch - texts, teaser links, images with thumbnails, figures, lists with markers and tables as grids - and clicking again hides it (`SemanticOutline.branches`, an element without an entry follows its parent). The first click loads the document with content once, the rows come from it with the content hidden outside the open branches (`isContent`, links only on navs) - `TestExtractDocument_ContentKeepsTheOutline` guarantees that this gives exactly the outline without content: the server fetches the live page via `GetSemanticDocument`, the loader comes from the environment (`semanticDocumentLoader`, set in `ServerDetailView`). Hovering an element highlights it in the preview by its selector (`PreviewController.highlight`), headings the selector misses in the live DOM are found by level and text. Title, description, canonical and robots still come from the scrape result's `Structure`. - The app target must not use `MainActor` default isolation (it would isolate the generated `Codable` conformances). App model classes are `@MainActor` explicitly. **Logging.** Log messages go through `log/slog` with attributes (`slog.Info("scrape cycle completed", "pages", n)`), never `fmt.Print`/`log.Print`. `cmd/walker` sets the default logger: `-log-level debug|info|warn|error`, `-log-format text|json`, text on stderr by default. `fmt` is only for program output: CLI results and usage, reports, `configvalidator`'s stderr (the app shows it as is). The app's log view parses the slog text lines (`SlogEntry`), so keep walker's default format text. diff --git a/go/internal/demoshop/shapes/default.semanticshape.html b/go/internal/demoshop/shapes/default.semanticshape.html index e0e70d5..dd7c034 100644 --- a/go/internal/demoshop/shapes/default.semanticshape.html +++ b/go/internal/demoshop/shapes/default.semanticshape.html @@ -10,7 +10,9 @@
-

+ +

+

diff --git a/go/internal/semanticscrape/document_test.go b/go/internal/semanticscrape/document_test.go index 7229e16..ab53a52 100644 --- a/go/internal/semanticscrape/document_test.go +++ b/go/internal/semanticscrape/document_test.go @@ -801,3 +801,55 @@ func runOutlineTests(t *testing.T, tests []outlineTest) { }) } } + +// contentHidden removes what Options{Content: true} adds: the content +// elements - an outline element in one stays - and the links of everything +// but navs. The macOS app shows the content per branch from one document with +// content, by hiding it the same way. +func contentHidden(elements []DocumentElement) []DocumentElement { + content := map[ElementType]bool{ + ElementTypeText: true, ElementTypeImage: true, ElementTypeFigure: true, + ElementTypeUnorderedList: true, ElementTypeOrderedList: true, ElementTypeListItem: true, + ElementTypeDefinitions: true, ElementTypeTerm: true, ElementTypeDefinition: true, + ElementTypeTable: true, ElementTypeRow: true, ElementTypeHeaderCell: true, ElementTypeCell: true, + } + result := []DocumentElement{} + for _, e := range elements { + if content[e.ElementType] { + result = append(result, contentHidden(e.Children)...) + continue + } + if e.ElementType != ElementTypeNav { + e.Links = nil + } + e.Children = contentHidden(e.Children) + result = append(result, e) + } + return result +} + +func normalized(elements []DocumentElement) []DocumentElement { + result := []DocumentElement{} + for _, e := range elements { + e.Children = normalized(e.Children) + if len(e.Links) == 0 { + e.Links = nil + } + result = append(result, e) + } + return result +} + +func TestExtractDocument_ContentKeepsTheOutline(t *testing.T) { + pages := map[string][]byte{} + for _, name := range []string{"keeping-sourdough-alive.html", "keeping-sourdough-alive-divs.html", "keeping-sourdough-alive-aria.html", "news-portal-home.html"} { + pages[name] = readTestData(t, name) + } + for name, htmlBytes := range pages { + t.Run(name, func(t *testing.T) { + structure := extract(t, htmlBytes) + withContent := extractContent(t, htmlBytes) + assert.Equal(t, normalized(structure.Body), normalized(contentHidden(withContent.Body))) + }) + } +} diff --git a/go/internal/service/gotsrpc_gen.go b/go/internal/service/gotsrpc_gen.go index 1c4828d..cfb7f07 100644 --- a/go/internal/service/gotsrpc_gen.go +++ b/go/internal/service/gotsrpc_gen.go @@ -391,19 +391,20 @@ func (p *ServiceGoTSRPCProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) case ServiceGoTSRPCProxyValidateShape: var rets []any var ( - arg_shapeRoot string - arg_group string - arg_targetURL string - arg_html string + arg_shapeRoot string + arg_group string + arg_groupHeader string + arg_targetURL string + arg_html string ) - args := []any{&arg_shapeRoot, &arg_group, &arg_targetURL, &arg_html} + args := []any{&arg_shapeRoot, &arg_group, &arg_groupHeader, &arg_targetURL, &arg_html} if err := gotsrpc.LoadArgs(&args, call, r); err != nil { call.SetError(err) gotsrpc.ErrorCouldNotLoadArgs(w) return } call.ExecutionStart() - validateShapeValidation := p.service.ValidateShape(arg_shapeRoot, arg_group, arg_targetURL, arg_html) + validateShapeValidation := p.service.ValidateShape(arg_shapeRoot, arg_group, arg_groupHeader, arg_targetURL, arg_html) call.ExecutionEnd() rets = []any{validateShapeValidation} if err := gotsrpc.Reply(rets, call, r, w); err != nil { diff --git a/go/internal/service/gotsrpcclient_gen.go b/go/internal/service/gotsrpcclient_gen.go index 3402e8b..1c37fc5 100644 --- a/go/internal/service/gotsrpcclient_gen.go +++ b/go/internal/service/gotsrpcclient_gen.go @@ -28,7 +28,7 @@ type ServiceGoTSRPCClient interface { GetShapeRootVersion(ctx go_context.Context, shapeRoot string) (retGetShapeRootVersion_0 string, clientErr error) GetStatus(ctx go_context.Context) (retGetStatus_0 github_com_foomo_walker_go_internal_vo.ServiceStatus, clientErr error) RestartScrape(ctx go_context.Context) (retRestartScrape_0 bool, clientErr error) - ValidateShape(ctx go_context.Context, shapeRoot string, group string, targetURL string, html string) (validation github_com_foomo_walker_go_internal_vo.ShapeValidation, clientErr error) + ValidateShape(ctx go_context.Context, shapeRoot string, group string, groupHeader string, targetURL string, html string) (validation github_com_foomo_walker_go_internal_vo.ShapeValidation, clientErr error) } type HTTPServiceGoTSRPCClient struct { @@ -213,8 +213,8 @@ func (tsc *HTTPServiceGoTSRPCClient) RestartScrape(ctx go_context.Context) (retR return } -func (tsc *HTTPServiceGoTSRPCClient) ValidateShape(ctx go_context.Context, shapeRoot string, group string, targetURL string, html string) (validation github_com_foomo_walker_go_internal_vo.ShapeValidation, clientErr error) { - rpcArgs := []any{shapeRoot, group, targetURL, html} +func (tsc *HTTPServiceGoTSRPCClient) ValidateShape(ctx go_context.Context, shapeRoot string, group string, groupHeader string, targetURL string, html string) (validation github_com_foomo_walker_go_internal_vo.ShapeValidation, clientErr error) { + rpcArgs := []any{shapeRoot, group, groupHeader, targetURL, html} rpcReply := []any{&validation} rpcErr := tsc.Client.Call(ctx, tsc.URL, tsc.EndPoint, "ValidateShape", rpcArgs, rpcReply) if rpcErr != nil { diff --git a/go/internal/service/semanticservice.go b/go/internal/service/semanticservice.go index 00160fb..e567d8d 100644 --- a/go/internal/service/semanticservice.go +++ b/go/internal/service/semanticservice.go @@ -50,7 +50,7 @@ func (s *service) GetSemanticDocument(targetURL, html string, content bool) (res return result } fetchStart := time.Now() - body, statusCode, _, err := s.fetch(targetURL) + body, statusCode, _, err := s.fetch(targetURL, s.groupHeader()) fetchDuration = time.Since(fetchStart) result.StatusCode = statusCode if err != nil { diff --git a/go/internal/service/serviceinterface.go b/go/internal/service/serviceinterface.go index 85fd371..96394e7 100644 --- a/go/internal/service/serviceinterface.go +++ b/go/internal/service/serviceinterface.go @@ -31,7 +31,7 @@ type Service interface { // shape developer GetShapeRoot(shapeRoot string) (info vo.ShapeRootInfo) GetShapeRootVersion(shapeRoot string) string - ValidateShape(shapeRoot, group, targetURL, html string) (validation vo.ShapeValidation) + ValidateShape(shapeRoot, group, groupHeader, targetURL, html string) (validation vo.ShapeValidation) // semantic scrape GetSemanticDocument(targetURL, html string, content bool) (result vo.SemanticDocument) diff --git a/go/internal/service/shapeservice.go b/go/internal/service/shapeservice.go index 87f75d0..a99749d 100644 --- a/go/internal/service/shapeservice.go +++ b/go/internal/service/shapeservice.go @@ -70,7 +70,9 @@ func (s *service) GetShapeRootVersion(shapeRoot string) string { // every call to pick up changes. Without html the server fetches targetURL, // otherwise html is a snapshot of the page in a browser. An empty group is // the group the page reports in the group header, or default.semanticshape.html. -func (s *service) ValidateShape(shapeRoot, group, targetURL, html string) (validation vo.ShapeValidation) { +// groupHeader names that response header, empty is the one of the walker's +// config - an edited header is used before the walker restarts. +func (s *service) ValidateShape(shapeRoot, group, groupHeader, targetURL, html string) (validation vo.ShapeValidation) { var ( start = time.Now() loadDuration, fetchDuration time.Duration @@ -84,6 +86,7 @@ func (s *service) ValidateShape(shapeRoot, group, targetURL, html string) (valid "url", targetURL, "source", validation.Source, "requestedGroup", requestedGroup, + "groupHeader", validation.GroupHeader, "group", validation.Group, "bytes", htmlLength, "load", loadDuration, @@ -109,7 +112,11 @@ func (s *service) ValidateShape(shapeRoot, group, targetURL, html string) (valid ) slog.Info("shape validated", attrs...) }() + if groupHeader == "" { + groupHeader = s.groupHeader() + } validation.URL = targetURL + validation.GroupHeader = groupHeader validation.Source = ShapeSourceRendered loadStart := time.Now() root, lintErrors, err := loadShapeRoot(shapeRoot) @@ -123,7 +130,7 @@ func (s *service) ValidateShape(shapeRoot, group, targetURL, html string) (valid if html == "" { validation.Source = ShapeSourceServer fetchStart := time.Now() - body, statusCode, detectedGroup, errFetch := s.fetch(targetURL) + body, statusCode, detectedGroup, errFetch := s.fetch(targetURL, groupHeader) fetchDuration = time.Since(fetchStart) validation.StatusCode = statusCode validation.DetectedGroup = detectedGroup @@ -184,8 +191,9 @@ func (s *service) groupHeader() string { return s.conf.GroupHeader } -// fetch loads a page like the crawler does -func (s *service) fetch(targetURL string) (body []byte, statusCode int, group string, err error) { +// fetch loads a page like the crawler does - group is the value of the +// response header groupHeader +func (s *service) fetch(targetURL, groupHeader string) (body []byte, statusCode int, group string, err error) { req, err := http.NewRequest(http.MethodGet, targetURL, nil) if err != nil { return nil, 0, "", err @@ -202,8 +210,8 @@ func (s *service) fetch(targetURL string) (body []byte, statusCode int, group st return nil, 0, "", err } defer resp.Body.Close() - if header := s.groupHeader(); header != "" { - group = resp.Header.Get(header) + if groupHeader != "" { + group = resp.Header.Get(groupHeader) if strings.HasSuffix(group, "/") { group += "index" } diff --git a/go/internal/service/shapeservice_test.go b/go/internal/service/shapeservice_test.go index b8724cc..4c78088 100644 --- a/go/internal/service/shapeservice_test.go +++ b/go/internal/service/shapeservice_test.go @@ -42,7 +42,7 @@ func TestValidateShapeRendered(t *testing.T) { w := httptest.NewRecorder() demoHandler(t).ServeHTTP(w, httptest.NewRequest(http.MethodGet, "http://localhost/product/car-04", nil)) s := &service{} - validation := s.ValidateShape(demoshop.ShapesDir(), "product", "http://localhost/product/car-04", w.Body.String()) + validation := s.ValidateShape(demoshop.ShapesDir(), "product", "", "http://localhost/product/car-04", w.Body.String()) assert.Empty(t, validation.Error) assert.Equal(t, ShapeSourceRendered, validation.Source) require.NotNil(t, validation.Report) @@ -58,18 +58,25 @@ func TestValidateShapeServer(t *testing.T) { })) defer page.Close() s := &service{conf: &config.Config{GroupHeader: demoshop.GroupHeader, Agent: "test-agent"}} - validation := s.ValidateShape(demoshop.ShapesDir(), "", page.URL+"/product/robot-01", "") + validation := s.ValidateShape(demoshop.ShapesDir(), "", "", page.URL+"/product/robot-01", "") assert.Empty(t, validation.Error) assert.Equal(t, ShapeSourceServer, validation.Source) assert.Equal(t, http.StatusOK, validation.StatusCode) assert.Equal(t, "product", validation.Group, "the group comes from the header") + assert.Equal(t, demoshop.GroupHeader, validation.GroupHeader) assert.Equal(t, 121, validation.Report.Score.Points) + + // a header passed in wins over the config's - an edited one, before the walker restarts + stale := &service{conf: &config.Config{GroupHeader: "x-old-header", Agent: "test-agent"}} + validation = stale.ValidateShape(demoshop.ShapesDir(), "", demoshop.GroupHeader, page.URL+"/product/robot-01", "") + assert.Equal(t, "product", validation.Group) + assert.Equal(t, demoshop.GroupHeader, validation.GroupHeader) } func TestValidateShapeServerErrorPage(t *testing.T) { page := httptest.NewServer(http.NotFoundHandler()) defer page.Close() - validation := (&service{}).ValidateShape(demoshop.ShapesDir(), "product", page.URL+"/product/robot-01", "") + validation := (&service{}).ValidateShape(demoshop.ShapesDir(), "product", "", page.URL+"/product/robot-01", "") assert.Equal(t, http.StatusNotFound, validation.StatusCode) assert.Equal(t, "the page returned 404 Not Found - nothing validated", validation.Error) assert.Nil(t, validation.Report) diff --git a/go/internal/vo/shape.go b/go/internal/vo/shape.go index 88c947f..7a0140a 100644 --- a/go/internal/vo/shape.go +++ b/go/internal/vo/shape.go @@ -19,6 +19,8 @@ type ShapeValidation struct { // Source is "server" for a page the server fetched, "rendered" for a snapshot of a browser's DOM Source string StatusCode int + // GroupHeader is the response header the group was read from - "" if there is none + GroupHeader string // DetectedGroup is the value of the group header of the fetched page DetectedGroup string Report *semanticshape.Report diff --git a/macos/Walker.xcodeproj/project.pbxproj b/macos/Walker.xcodeproj/project.pbxproj index 31dedc3..0b63f8e 100644 --- a/macos/Walker.xcodeproj/project.pbxproj +++ b/macos/Walker.xcodeproj/project.pbxproj @@ -204,6 +204,7 @@ ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; CODE_SIGN_ENTITLEMENTS = Walker.entitlements; CODE_SIGN_IDENTITY = "-"; + "CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development"; CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; CURRENT_PROJECT_VERSION = 1; @@ -234,6 +235,7 @@ ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; CODE_SIGN_ENTITLEMENTS = Walker.entitlements; CODE_SIGN_IDENTITY = "-"; + "CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development"; CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; CURRENT_PROJECT_VERSION = 1; diff --git a/macos/Walker/Generated/ServiceClient.swift b/macos/Walker/Generated/ServiceClient.swift index 77c7098..efbeba7 100644 --- a/macos/Walker/Generated/ServiceClient.swift +++ b/macos/Walker/Generated/ServiceClient.swift @@ -381,12 +381,13 @@ extension Walker { return try await transport.call(endpoint: endpoint, method: "RestartScrape", args: GotsRPCNoArgs(), result: _Result.self).r0 } - public func validateShape(shapeRoot: String, group: String, targetURL: String, html: String) async throws -> WalkerVO.ShapeValidation { + public func validateShape(shapeRoot: String, group: String, groupHeader: String, targetURL: String, html: String) async throws -> WalkerVO.ShapeValidation { struct _Args: Encodable { let a0: String let a1: String let a2: String let a3: String + let a4: String func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() @@ -394,6 +395,7 @@ extension Walker { try container.encode(a1) try container.encode(a2) try container.encode(a3) + try container.encode(a4) } } @@ -406,7 +408,7 @@ extension Walker { } } - return try await transport.call(endpoint: endpoint, method: "ValidateShape", args: _Args(a0: shapeRoot, a1: group, a2: targetURL, a3: html), result: _Result.self).r0 + return try await transport.call(endpoint: endpoint, method: "ValidateShape", args: _Args(a0: shapeRoot, a1: group, a2: groupHeader, a3: targetURL, a4: html), result: _Result.self).r0 } } } diff --git a/macos/Walker/Generated/WalkerVo.swift b/macos/Walker/Generated/WalkerVo.swift index f2ae873..541c614 100644 --- a/macos/Walker/Generated/WalkerVo.swift +++ b/macos/Walker/Generated/WalkerVo.swift @@ -633,6 +633,7 @@ extension WalkerVO { public var group: String public var source: String public var statusCode: Int + public var groupHeader: String public var detectedGroup: String public var report: SemanticShapeVO.Report? public var trace: SemanticShapeVO.TraceNode? @@ -640,11 +641,12 @@ extension WalkerVO { public var lintErrors: [SemanticShapeVO.LintError]? public var error: String - public init(url: String, group: String, source: String, statusCode: Int, detectedGroup: String, report: SemanticShapeVO.Report? = nil, trace: SemanticShapeVO.TraceNode? = nil, page: SemanticShapeVO.PageData? = nil, lintErrors: [SemanticShapeVO.LintError]? = nil, error: String) { + public init(url: String, group: String, source: String, statusCode: Int, groupHeader: String, detectedGroup: String, report: SemanticShapeVO.Report? = nil, trace: SemanticShapeVO.TraceNode? = nil, page: SemanticShapeVO.PageData? = nil, lintErrors: [SemanticShapeVO.LintError]? = nil, error: String) { self.url = url self.group = group self.source = source self.statusCode = statusCode + self.groupHeader = groupHeader self.detectedGroup = detectedGroup self.report = report self.trace = trace @@ -658,6 +660,7 @@ extension WalkerVO { case group = "Group" case source = "Source" case statusCode = "StatusCode" + case groupHeader = "GroupHeader" case detectedGroup = "DetectedGroup" case report = "Report" case trace = "Trace" diff --git a/macos/Walker/Model/ServerModel.swift b/macos/Walker/Model/ServerModel.swift index edcbccd..c53aa4f 100644 --- a/macos/Walker/Model/ServerModel.swift +++ b/macos/Walker/Model/ServerModel.swift @@ -8,6 +8,19 @@ import Observation @MainActor @Observable final class ServerModel { + /// shapeDevModel is the shape developer of this server - made when its + /// section opens the first time, kept while the app runs + @ObservationIgnored private var shapeDevModel: ShapeDevModel? + + var shapeDev: ShapeDevModel { + if let shapeDevModel { + return shapeDevModel + } + let model = ShapeDevModel(server: server) + shapeDevModel = model + return model + } + enum Connection: Equatable { case unknown case online diff --git a/macos/Walker/Model/ServerStore.swift b/macos/Walker/Model/ServerStore.swift index 06c9b6a..07517e3 100644 --- a/macos/Walker/Model/ServerStore.swift +++ b/macos/Walker/Model/ServerStore.swift @@ -68,6 +68,37 @@ final class ServerStore { return server } + /// setShapeRoot writes the shape root into the config of a local server - + /// relative to the config's directory if it is in it, as walker resolves it + func setShapeRoot(_ id: Server.ID, path: String) async throws { + try await updateConfig(id) { form, base in + let dir = base.hasSuffix("/") ? base : base + "/" + form.shapeRoot = path.hasPrefix(dir) ? String(path.dropFirst(dir.count)) : path + } + } + + /// setGroupHeader writes the group header into the config of a local server + func setGroupHeader(_ id: Server.ID, header: String) async throws { + try await updateConfig(id) { form, _ in + form.groupHeader = header + } + } + + /// updateConfig changes the form of the config of a local server and + /// writes it - comments and unknown keys of the config stay. base is the + /// directory of the config. + private func updateConfig(_ id: Server.ID, _ change: (inout ConfigTool.Form, _ base: String) -> Void) async throws { + guard let url = server(id)?.configURL else { + throw CocoaError(.fileNoSuchFile) + } + let yaml = try String(contentsOf: url, encoding: .utf8) + let base = url.deletingLastPathComponent().path(percentEncoded: false) + var form = try await ConfigTool.read(yaml: yaml, base: base).form + change(&form, base) + let written = try await ConfigTool.write(yaml: yaml, form: form) + try written.write(to: url, atomically: true, encoding: .utf8) + } + /// refreshLocal reads and validates a local config - the address of the /// server follows its addr @discardableResult diff --git a/macos/Walker/Model/SettingsMigration.swift b/macos/Walker/Model/SettingsMigration.swift index 8cc208b..da3819e 100644 --- a/macos/Walker/Model/SettingsMigration.swift +++ b/macos/Walker/Model/SettingsMigration.swift @@ -12,6 +12,8 @@ enum SettingsMigration { } defaults.removeObject(forKey: key) } + // the content switch of the outline is gone - a branch shows its content on a click + defaults.removeObject(forKey: "outlineShowsContent") } /// renamed is the current name of an old key - schemaDevEditor is diff --git a/macos/Walker/Model/ShapeDevModel.swift b/macos/Walker/Model/ShapeDevModel.swift index 319bb80..8085862 100644 --- a/macos/Walker/Model/ShapeDevModel.swift +++ b/macos/Walker/Model/ShapeDevModel.swift @@ -32,6 +32,17 @@ final class ShapeDevModel { var group: String { didSet { save() } } + /// groupHeader names the response header the group of a page is read + /// from - "" is the one of the server's config. A local server takes it + /// from its config, which may be newer than the running walker's. + var groupHeader: String { + didSet { save() } + } + + /// effectiveGroupHeader is the header the validation reads the group from + var effectiveGroupHeader: String { + groupHeader.isEmpty ? rootInfo?.groupHeader ?? "" : groupHeader + } var source: Source { didSet { save() } } @@ -53,6 +64,8 @@ final class ShapeDevModel { private(set) var pageVersion = 0 /// outline is the semantic document of the page, from the same source as the validation private(set) var outline: OutlineState = .idle + /// outlineVersion counts the loaded outlines - a new one starts without content + private(set) var outlineVersion = 0 enum OutlineState { case idle @@ -61,6 +74,9 @@ final class ShapeDevModel { case failed(String) } + /// configRoot is the shape root of the config of a local server, nil if it has none + private(set) var configRoot: String? + /// selection is the id of the selected trace item var selection: TraceItem.ID? { didSet { highlightSelection() } @@ -86,6 +102,7 @@ final class ShapeDevModel { address = defaults.string(forKey: prefix + "address") ?? "" shapeRoot = defaults.string(forKey: prefix + "shapeRoot") ?? "" group = defaults.string(forKey: prefix + "group") ?? "" + groupHeader = defaults.string(forKey: prefix + "groupHeader") ?? "" source = Source(rawValue: defaults.string(forKey: prefix + "source") ?? "") ?? .server recentRoots = defaults.stringArray(forKey: Self.recentRootsKey) ?? [] } @@ -95,6 +112,7 @@ final class ShapeDevModel { defaults.set(address, forKey: prefix + "address") defaults.set(shapeRoot, forKey: prefix + "shapeRoot") defaults.set(group, forKey: prefix + "group") + defaults.set(groupHeader, forKey: prefix + "groupHeader") defaults.set(source.rawValue, forKey: prefix + "source") } @@ -139,20 +157,30 @@ final class ShapeDevModel { /// load takes the site and the shape root of a walker config: the page /// is the base url with the first start path, a relative shape root is /// resolved against the directory of the config, like walker does - func load(_ form: ConfigTool.Form, configURL: URL) { + /// follow takes the shape root of the config of a local server - the + /// section belongs to it - and its site as the first page + func follow(_ form: ConfigTool.Form, configURL: URL) { if !form.shapeRoot.isEmpty { let root = form.shapeRoot.hasPrefix("/") ? URL(filePath: form.shapeRoot) : configURL.deletingLastPathComponent().appending(path: form.shapeRoot) - chooseRoot(root.standardizedFileURL.path(percentEncoded: false)) + let path = root.standardizedFileURL.path(percentEncoded: false) + if path != shapeRoot { + chooseRoot(path) + } + configRoot = path + } else { + configRoot = nil } - guard !form.baseURL.isEmpty else { return } + if groupHeader != form.groupHeader { + groupHeader = form.groupHeader + } + guard address.isEmpty, !form.baseURL.isEmpty else { return } var page = form.baseURL if let path = form.paths.first, !path.isEmpty, path != "/" { page = page.trimmingCharacters(in: CharacterSet(charactersIn: "/")) + (path.hasPrefix("/") ? path : "/" + path) } address = page - open() } func loadRoot() async { @@ -234,7 +262,7 @@ final class ShapeDevModel { } html = snapshot } - let validation = try await client.validateShape(shapeRoot: shapeRoot, group: group, targetURL: url.absoluteString, html: html) + let validation = try await client.validateShape(shapeRoot: shapeRoot, group: group, groupHeader: groupHeader, targetURL: url.absoluteString, html: html) guard !Task.isCancelled, count == validationCount else { return } apply(validation) error = nil @@ -371,10 +399,11 @@ final class ShapeDevModel { error = message } - /// loadOutline extracts the semantic document of the page in the web view: - /// the server fetches it, or it gets the snapshot of the rendered DOM - func loadOutline(content: Bool) async { - guard let url = highlighter.pageURL ?? pageURL else { + /// loadOutline extracts the semantic outline of the page in the web view, + /// without content: the server fetches it, or it gets the snapshot of the + /// rendered DOM + func loadOutline() async { + guard highlighter.pageURL ?? pageURL != nil else { outline = .idle return } @@ -383,16 +412,9 @@ final class ShapeDevModel { } outline = .loading do { - var html = "" - if source == .rendered { - guard let snapshot = await highlighter.snapshot() else { - outline = .failed("the page has no DOM yet") - return - } - html = snapshot - } - let document = try await client.getSemanticDocument(targetURL: url.absoluteString, html: html, content: content) + let document = try await fetchOutline(content: false) guard !Task.isCancelled else { return } + outlineVersion += 1 outline = .loaded(document) } catch is CancellationError { return @@ -401,6 +423,30 @@ final class ShapeDevModel { } } + /// outlineContent extracts the outline with its content from the same + /// source - for the branches the user opens + func outlineContent() async throws -> WalkerVO.SemanticDocument { + try await fetchOutline(content: true) + } + + private struct OutlineError: LocalizedError { + let errorDescription: String? + } + + private func fetchOutline(content: Bool) async throws -> WalkerVO.SemanticDocument { + guard let url = highlighter.pageURL ?? pageURL else { + throw OutlineError(errorDescription: "no page") + } + var html = "" + if source == .rendered { + guard let snapshot = await highlighter.snapshot() else { + throw OutlineError(errorDescription: "the page has no DOM yet") + } + html = snapshot + } + return try await client.getSemanticDocument(targetURL: url.absoluteString, html: html, content: content) + } + /// hoverOutline highlights an element of the outline in the page, nil /// brings back the highlight of the selected shape node func hoverOutline(_ selector: String?) { diff --git a/macos/Walker/Views/SemanticOutline.swift b/macos/Walker/Views/SemanticOutline.swift index 3f2eb78..645e45a 100644 --- a/macos/Walker/Views/SemanticOutline.swift +++ b/macos/Walker/Views/SemanticOutline.swift @@ -17,7 +17,8 @@ extension EnvironmentValues { } /// SemanticOutlineSection loads the outline of a page from the server - the -/// live page, fetched like the crawler does - and shows it +/// live page, fetched like the crawler does - and shows it. The content of a +/// branch is loaded when the user clicks it. struct SemanticOutlineSection: View { let url: String /// preview shows the page - hovering an element highlights it there @@ -25,8 +26,8 @@ struct SemanticOutlineSection: View { @Environment(\.semanticDocumentLoader) private var loader @State private var state = LoadState.loading - /// showsContent adds texts, links, images and figures to the outline - @AppStorage("outlineShowsContent") private var showsContent = false + /// loads counts the loaded outlines - a new one starts without content + @State private var loads = 0 enum LoadState { case loading @@ -38,17 +39,10 @@ struct SemanticOutlineSection: View { Section { content } header: { - HStack { - Text("Document outline") - .help("The landmarks, articles, sections, asides and headings of the page, as the server fetches it now") - Spacer() - Toggle("Content", isOn: $showsContent) - .toggleStyle(.switch) - .controlSize(.mini) - .help(showsContent ? "Show the structure only" : "Show the texts, links, images and figures too") - } + Text("Document outline") + .help("The landmarks, articles, sections, asides and headings of the page, as the server fetches it now - click an element to show the content of its branch") } - .task(id: "\(showsContent) \(url)") { + .task(id: url) { await load() } } @@ -64,12 +58,18 @@ struct SemanticOutlineSection: View { Label(message, systemImage: "exclamationmark.triangle") .foregroundStyle(.red) case let .loaded(result): - SemanticDocumentContent(result: result, pageURL: URL(string: url)) { selector, element in + SemanticDocumentContent(result: result, pageURL: URL(string: url), loadContent: loadContent) { selector, element in preview?.highlight(selector: selector, element: element) } + .id(loads) } } + private var loadContent: SemanticDocumentContent.ContentLoader? { + guard let loader else { return nil } + return { [url] in try await loader(url, true) } + } + private func load() async { guard let loader else { state = .failed("No server to load the outline from.") @@ -77,8 +77,9 @@ struct SemanticOutlineSection: View { } state = .loading do { - let result = try await loader(url, showsContent) + let result = try await loader(url, false) guard !Task.isCancelled else { return } + loads += 1 state = .loaded(result) } catch is CancellationError { return @@ -92,9 +93,15 @@ struct SemanticOutlineSection: View { /// missing main, the outline and the language - rows of a form section or a /// stack struct SemanticDocumentContent: View { + /// ContentLoader loads the same document with its content - texts, + /// links, images, figures, lists and tables + typealias ContentLoader = @MainActor () async throws -> WalkerVO.SemanticDocument + let result: WalkerVO.SemanticDocument /// pageURL resolves relative image sources var pageURL: URL? + /// loadContent is called when the user opens the content of a branch the first time + var loadContent: ContentLoader? var onHover: ((String?, SemanticScrapeVO.DocumentElement?) -> Void)? var body: some View { @@ -111,31 +118,76 @@ struct SemanticDocumentContent: View { Label("The page has no landmarks, articles, sections, asides or headings.", systemImage: "rectangle.dashed") .foregroundStyle(.orange) } else { - SemanticOutline(elements: body, pageURL: pageURL, onHover: onHover) + SemanticOutline(elements: body, pageURL: pageURL, loadContent: loadBody, onHover: onHover) } if !document.lang.isEmpty { LabeledContent("Language", value: document.lang) } } } + + private var loadBody: SemanticOutline.ContentLoader? { + guard let loadContent else { return nil } + return { + let result = try await loadContent() + if !result.error.isEmpty { + throw SemanticOutline.ContentError(message: result.error) + } + return result.document?.body ?? [] + } + } } /// SemanticOutline renders the outline of a page as an indented tree: /// landmarks and containers with their labels, the links of navs, headings -/// sized by level, and with content texts, images, figures, lists and tables - -/// a table as a grid. Containers collapse - navs start collapsed, menus are long. -/// Headings are marked for what search engines dislike: empty headings, -/// skipped levels and more than one h1. +/// sized by level. Clicking an element shows the content of its branch - texts, +/// teaser links, images, figures, lists and tables, a table as a grid - and +/// clicking it again hides it; the content is loaded with the first click. +/// Containers collapse - navs start collapsed, menus are long. Headings are +/// marked for what search engines dislike: empty headings, skipped levels and +/// more than one h1. struct SemanticOutline: View { + /// ContentLoader loads the outline with its content - the same structure, + /// the content elements between its elements + typealias ContentLoader = @MainActor () async throws -> [SemanticScrapeVO.DocumentElement] + + struct ContentError: LocalizedError { + let message: String + var errorDescription: String? { message } + } + + /// elements are the outline without content let elements: [SemanticScrapeVO.DocumentElement] /// pageURL resolves relative image sources var pageURL: URL? + /// loadContent loads the content - without it, clicks show nothing + var loadContent: ContentLoader? /// onHover reports the selector under the mouse, with its element - a link /// has none - and nil, when it left var onHover: ((String?, SemanticScrapeVO.DocumentElement?) -> Void)? /// containers the user opened or closed, by selector - against their default @State private var toggled: Set = [] + /// branches whose content the user showed (true) or hid (false), by + /// selector - an element without an entry follows its parent, the outline + /// starts without content + @State private var branches: [String: Bool] = [:] + @State private var content = ContentState.none + + enum ContentState { + case none + case loading + case loaded([SemanticScrapeVO.DocumentElement]) + case failed(String) + } + + /// source is the tree the rows come from: the outline with content once it is loaded + private var source: [SemanticScrapeVO.DocumentElement] { + if case let .loaded(elements) = content { + return elements + } + return elements + } private static let indent: CGFloat = 14 @@ -155,6 +207,8 @@ struct SemanticOutline: View { let depth: Int /// marker of a list item: a bullet or its number var marker: String? + /// showsContent: the content of this row's branch is shown + var showsContent = false var selector: String { switch content { @@ -209,40 +263,90 @@ struct SemanticOutline: View { } /// rows are the visible elements and links - without the content of - /// collapsed containers + /// collapsed containers, and content only in the branches that show it private var rows: [Row] { var rows: [Row] = [] - func visit(_ elements: [SemanticScrapeVO.DocumentElement], parent: SemanticScrapeVO.ElementType?, path: String, depth: Int) { + func visit(_ elements: [SemanticScrapeVO.DocumentElement], parent: SemanticScrapeVO.ElementType?, path: String, depth: Int, showsContent inherited: Bool) { for (index, element) in elements.enumerated() { let id = "\(path)/\(index)" + if element.isContent, !inherited { + // hidden content - an outline element in it, which the content pass never makes, stays + visit(element.children ?? [], parent: element.elementType, path: id, depth: depth, showsContent: false) + continue + } + let showsContent = element.isContent ? inherited : branches[element.selector] ?? inherited let marker: String? = switch parent { case .unorderedList: "•" case .orderedList: "\(index + 1)." default: nil } - rows.append(Row(id: id, content: .element(element), depth: depth, marker: marker)) + rows.append(Row(id: id, content: .element(element), depth: depth, marker: marker, showsContent: showsContent)) if isCollapsed(element) { continue } - for (linkIndex, link) in (element.links ?? []).enumerated() { - rows.append(Row(id: "\(id)/link\(linkIndex)", content: .link(link), depth: depth + 1)) + // the links of a nav are structure, all others - teasers of headings, links in texts - content + if element.elementType == .nav || showsContent { + for (linkIndex, link) in (element.links ?? []).enumerated() { + rows.append(Row(id: "\(id)/link\(linkIndex)", content: .link(link), depth: depth + 1, showsContent: showsContent)) + } } if element.elementType == .table { if !(element.children ?? []).isEmpty { - rows.append(Row(id: "\(id)/grid", content: .grid(element), depth: depth + 1)) + rows.append(Row(id: "\(id)/grid", content: .grid(element), depth: depth + 1, showsContent: showsContent)) } } else { - visit(element.children ?? [], parent: element.elementType, path: id, depth: depth + 1) + visit(element.children ?? [], parent: element.elementType, path: id, depth: depth + 1, showsContent: showsContent) } } } - visit(elements, parent: nil, path: "", depth: 0) + visit(source, parent: nil, path: "", depth: 0, showsContent: false) return rows } + /// toggleContent shows or hides the content of the branch of an element - + /// its descendants follow it - and loads the content the first time + private func toggleContent(_ element: SemanticScrapeVO.DocumentElement, showsContent: Bool) { + func forget(_ elements: [SemanticScrapeVO.DocumentElement]) { + for child in elements { + branches[child.selector] = nil + forget(child.children ?? []) + } + } + forget(element.children ?? []) + branches[element.selector] = !showsContent + if !showsContent { + // a collapsed container opens to show its content + if isCollapsed(element) { + toggled.formSymmetricDifference([element.selector]) + } + Task { await loadContentIfNeeded() } + } + } + + private func loadContentIfNeeded() async { + switch content { + case .loading, .loaded: return + case .none, .failed: break + } + guard let loadContent else { return } + content = .loading + do { + content = .loaded(try await loadContent()) + } catch is CancellationError { + content = .none + } catch { + content = .failed(error.localizedDescription) + } + } + var body: some View { let issues = issues VStack(alignment: .leading, spacing: 6) { + if case let .failed(message) = content { + Label("The content could not be loaded: \(message)", systemImage: "exclamationmark.triangle") + .font(.callout) + .foregroundStyle(.orange) + } ForEach(rows, id: \.id) { row in content(row, issues: issues) .padding(.leading, CGFloat(row.depth) * Self.indent) @@ -271,8 +375,24 @@ struct SemanticOutline: View { case let .element(element): if element.isListItem { listItemRow(element, marker: row.marker) - } else { + } else if element.isContent || loadContent == nil { self.row(element, issue: issues[element.selector]) + } else { + HStack(alignment: .firstTextBaseline, spacing: 6) { + self.row(element, issue: issues[element.selector]) + Spacer(minLength: 4) + contentIndicator(row.showsContent) + } + // selectable text - the outline panes enable it - would take the click + .textSelection(.disabled) + .contentShape(.rect) + .onTapGesture { + toggleContent(element, showsContent: row.showsContent) + } + .pointerStyle(.link) + .help(row.showsContent + ? "Click to hide the content of this branch" + : "Click to show the texts, links, images, lists and tables of this branch") } case let .link(link): linkRow(link) @@ -281,6 +401,22 @@ struct SemanticOutline: View { } } + /// contentIndicator marks a branch that shows its content - a spinner + /// while the content loads + @ViewBuilder + private func contentIndicator(_ showsContent: Bool) -> some View { + if showsContent { + if case .loading = content { + ProgressView() + .controlSize(.mini) + } else { + Image(systemName: "text.alignleft") + .font(.caption2) + .foregroundStyle(Color.accentColor) + } + } + } + /// guides are the lines of the nesting private func guides(depth: Int) -> some View { HStack(spacing: Self.indent - 1) { @@ -516,6 +652,16 @@ struct SemanticOutline: View { } extension SemanticScrapeVO.DocumentElement { + /// isContent: texts, images, figures, lists and tables - what the outline + /// gets with content, between its elements + var isContent: Bool { + [ + .text, .image, .figure, + .unorderedList, .orderedList, .listItem, .definitions, .term, .definition, + .table, .row, .headerCell, .cell, + ].contains(elementType) + } + /// isListItem: li, dt and dd var isListItem: Bool { [.listItem, .term, .definition].contains(elementType) diff --git a/macos/Walker/Views/ServerDetailView.swift b/macos/Walker/Views/ServerDetailView.swift index 7f4cf38..6818179 100644 --- a/macos/Walker/Views/ServerDetailView.swift +++ b/macos/Walker/Views/ServerDetailView.swift @@ -5,7 +5,6 @@ struct ServerDetailView: View { @AppStorage(SettingsView.refreshIntervalKey) private var refreshInterval = SettingsView .defaultRefreshInterval @State private var section = Section.overview - @Environment(\.openWindow) private var openWindow enum Section: String, CaseIterable, Identifiable { case overview = "Overview" @@ -14,6 +13,7 @@ struct ServerDetailView: View { case redirects = "Redirects" case links = "Links" case performance = "Performance" + case shapes = "Shapes" var id: Self { self } @@ -48,6 +48,8 @@ struct ServerDetailView: View { LinksView(model: model) case .performance: PerformanceView(model: model) + case .shapes: + ShapeDevView(model: model.shapeDev) } } // the result inspectors of all sections load outlines from this server @@ -81,8 +83,8 @@ struct ServerDetailView: View { .help("Overview of \(model.server.name)") } .sharedBackgroundVisibility(.hidden) - // the overview shows both scrapes side by side - if section != .overview { + // the overview shows both scrapes side by side, the shapes validate live pages + if section != .overview, section != .shapes { ToolbarItem(placement: .navigation) { Picker("Scrape", selection: $model.scrape) { ForEach(ServerModel.Scrape.allCases) { scrape in @@ -102,13 +104,6 @@ struct ServerDetailView: View { LocalWalkerButton(server: model.server) } } - ToolbarItem(placement: .primaryAction) { - Button("Shape Developer", systemImage: "checklist") { - openWindow(id: ShapeDevWindow.id, value: model.server.id) - } - .keyboardShortcut("s", modifiers: [.command, .shift]) - .help("Iterate on a semantic shape against a page of this server's site") - } ToolbarItem(placement: .principal) { Picker("Section", selection: $section) { ForEach(Section.tabs) { section in diff --git a/macos/Walker/Views/ShapeDevView.swift b/macos/Walker/Views/ShapeDevView.swift index 22abd73..f346fbc 100644 --- a/macos/Walker/Views/ShapeDevView.swift +++ b/macos/Walker/Views/ShapeDevView.swift @@ -1,56 +1,34 @@ import AppKit import SwiftUI -/// ShapeDevWindow is the content of a shape developer window - one per server -struct ShapeDevWindow: View { - static let id = "shape-developer" - - let serverID: Server.ID? - @Environment(ServerStore.self) private var store - - var body: some View { - if let server = store.servers.first(where: { $0.id == serverID }) { - ShapeDevView(server: server) - } else { - ContentUnavailableView("No Server", systemImage: "server.rack", description: Text("The server of this window was removed.")) - } - } -} - -/// ShapeDevView iterates on a shape and a website: the evaluated shape as a -/// tree next to the page, a selected node is highlighted in the page +/// ShapeDevView iterates on a shape and a website of a server - the Shapes +/// section of the server: the evaluated shape as a tree next to the page, a +/// selected node is highlighted in the page. A local server brings the shape +/// root and the site of its config. struct ShapeDevView: View { @Environment(ServerStore.self) private var store - @State private var model: ShapeDevModel + @Bindable var model: ShapeDevModel /// showsPageData shows the head and the JSON-LD between the shape and the page @AppStorage("shapeDevShowsPageData") private var showsPageData = true /// showsOutline shows the semantic outline of the page right of it @AppStorage("shapeDevShowsOutline") private var showsOutline = false - init(server: Server) { - _model = State(initialValue: ShapeDevModel(server: server)) - } + /// followed is set once a local server brought the shape root of its + /// config - until then the prompt for a root would flash + @State private var followed = false var body: some View { - // every column takes the full height - small content like a lint - // error would otherwise be centered vertically by the split view - HSplitView { - ShapePane(model: model) - .frame(minWidth: 320, idealWidth: 440, maxWidth: 700, maxHeight: .infinity, alignment: .top) - if showsPageData { - PageDataPane(model: model) - .frame(minWidth: 280, idealWidth: 380, maxWidth: 700, maxHeight: .infinity, alignment: .top) - } - page - .frame(minWidth: 420, maxWidth: .infinity, maxHeight: .infinity) - if showsOutline { - OutlinePane(model: model) - .frame(minWidth: 280, idealWidth: 380, maxWidth: 700, maxHeight: .infinity, alignment: .top) + Group { + if !followed { + ProgressView() + .controlSize(.small) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else if model.shapeRoot.isEmpty { + ShapeRootPrompt(model: model) + } else { + developer } } - .frame(maxWidth: .infinity, maxHeight: .infinity) - .navigationTitle("Shape – \(model.server.name)") - .toolbar { toolbar } .task(id: model.shapeRoot) { await model.loadRoot() // edits to the shape files validate again, until the root changes @@ -65,19 +43,42 @@ struct ShapeDevView: View { .onChange(of: model.shapeRoot) { Task { await model.validate() } } - .onAppear { - model.open() + .onChange(of: model.groupHeader) { + Task { await model.validate() } } - // the window of a local config starts with the site and shape root of the config + // a local server brings the shape root of its config - and its site, until another page is open .task { - guard model.server.isLocal, model.address.isEmpty, model.shapeRoot.isEmpty else { return } - await load(model.server) + if let url = model.server.configURL, let result = try? await store.refreshLocal(model.server.id) { + model.follow(result.form, configURL: url) + } + followed = true + model.open() } } - private func load(_ server: Server) async { - guard let url = server.configURL, let result = try? await store.refreshLocal(server.id) else { return } - model.load(result.form, configURL: url) + /// developer is the bar and the panes - shown once there is a shape root + private var developer: some View { + VStack(spacing: 0) { + bar + Divider() + // every column takes the full height - small content like a lint + // error would otherwise be centered vertically by the split view + HSplitView { + ShapePane(model: model) + .frame(minWidth: 320, idealWidth: 440, maxWidth: 700, maxHeight: .infinity, alignment: .top) + if showsPageData { + PageDataPane(model: model) + .frame(minWidth: 280, idealWidth: 380, maxWidth: 700, maxHeight: .infinity, alignment: .top) + } + page + .frame(minWidth: 420, maxWidth: .infinity, maxHeight: .infinity) + if showsOutline { + OutlinePane(model: model) + .frame(minWidth: 280, idealWidth: 380, maxWidth: 700, maxHeight: .infinity, alignment: .top) + } + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } } @ViewBuilder @@ -95,41 +96,20 @@ struct ShapeDevView: View { } } - @ToolbarContentBuilder - private var toolbar: some ToolbarContent { - ToolbarItem(placement: .navigation) { + /// bar holds the controls of the section: the page, the shape root and + /// group it is validated with, the editor, the panes and the source + private var bar: some View { + HStack(spacing: 10) { Button("Reload", systemImage: "arrow.clockwise") { model.reload() } + .labelStyle(.iconOnly) .keyboardShortcut("r") - .help("Reload the page and the shape, then validate again") - } - ToolbarItem(placement: .principal) { + .help("Reload the page and the shape, then validate again (⌘R)") AddressField(text: $model.address) { model.open() } - .frame(minWidth: 280, idealWidth: 480) - } - .sharedBackgroundVisibility(.hidden) - ToolbarItem { - Menu("Load Config", systemImage: "doc.text") { - ForEach(store.localServers) { server in - Button(server.name) { - Task { await load(server) } - } - .help(server.configPath ?? "") - } - } - .disabled(store.localServers.isEmpty) - .help(store.localServers.isEmpty - ? "Add a local config to load its site and shape root" - : "Open the site of a local config and use its shape root") - } - ToolbarItem { + .frame(minWidth: 220, maxWidth: .infinity) ShapeRootMenu(model: model) - } - ToolbarItem { - EditorMenu() - } - ToolbarItem { + .fixedSize() Picker("Group", selection: $model.group) { Text(autoGroupTitle).tag("") if let groups = model.rootInfo?.groups, !groups.isEmpty { @@ -139,38 +119,37 @@ struct ShapeDevView: View { } } } - .frame(minWidth: 160) + .labelsHidden() + .fixedSize() .help("The group shape to validate with") - } - ToolbarItem { - Toggle(isOn: $showsPageData) { - Label("Head & JSON-LD", systemImage: "curlybraces.square") - } - .help(showsPageData ? "Hide the head and the JSON-LD of the validated html" : "Show the head and the JSON-LD of the validated html") - } - ToolbarItem { - Toggle(isOn: $showsOutline) { - Label("Document Outline", systemImage: "list.bullet.indent") - } - .help(showsOutline ? "Hide the outline of the page" : "Show the outline of the page: landmarks, articles, sections, headings - and its content") - } - ToolbarItem { - Button("Web Inspector", systemImage: "hammer") { - model.highlighter.showInspector() - } - .keyboardShortcut("i", modifiers: [.command, .option]) - .disabled(model.pageURL == nil) - .help("Open the Web Inspector of the page (⌥⌘I) - or right click an element and choose Inspect Element") - } - ToolbarItem { + GroupHeaderButton(model: model) + .fixedSize() Picker("Source", selection: $model.source) { ForEach(ShapeDevModel.Source.allCases) { source in Text(source.rawValue).tag(source) } } .pickerStyle(.segmented) + .labelsHidden() + .fixedSize() .help("Server: the server fetches the page like the crawler - Rendered: a snapshot of the DOM in the web view") + Divider() + .frame(height: 18) + EditorMenu() + .fixedSize() + Toggle(isOn: $showsPageData) { + Label("Head & JSON-LD", systemImage: "curlybraces.square") + } + .help(showsPageData ? "Hide the head and the JSON-LD of the validated html" : "Show the head and the JSON-LD of the validated html") + Toggle(isOn: $showsOutline) { + Label("Document Outline", systemImage: "list.bullet.indent") + } + .help(showsOutline ? "Hide the outline of the page" : "Show the outline of the page: landmarks, articles, sections, headings - and their content") } + .toggleStyle(.button) + .labelStyle(.iconOnly) + .padding(.horizontal, 10) + .padding(.vertical, 6) } /// autoGroupTitle names the group auto resolves to @@ -178,13 +157,209 @@ struct ShapeDevView: View { if let detected = model.validation?.detectedGroup, !detected.isEmpty { return "Auto (\(detected))" } - if let header = model.rootInfo?.groupHeader, !header.isEmpty { + if !model.effectiveGroupHeader.isEmpty { + let header = model.effectiveGroupHeader return "Auto (header \(header))" } return "Auto" } } +/// GroupHeaderButton shows the response header the group of a page is read +/// from - a click edits it. A local server keeps it in its config as +/// groupheader, for a remote one it overrides the server's in this app. +private struct GroupHeaderButton: View { + @Bindable var model: ShapeDevModel + @Environment(ServerStore.self) private var store + @State private var isEditing = false + @State private var draft = "" + @State private var error: String? + @State private var isSaving = false + + private var isLocal: Bool { model.server.configURL != nil } + /// serverHeader is the header of the running walker's config + private var serverHeader: String { model.rootInfo?.groupHeader ?? "" } + + var body: some View { + Button { + draft = model.effectiveGroupHeader + error = nil + isEditing = true + } label: { + Label(model.effectiveGroupHeader.isEmpty ? "No Group Header" : model.effectiveGroupHeader, systemImage: "tag") + .labelStyle(.titleAndIcon) + .foregroundStyle(model.effectiveGroupHeader.isEmpty ? .secondary : .primary) + } + .help(model.effectiveGroupHeader.isEmpty + ? "No response header names the group of a page - every page is validated with default.semanticshape.html unless a group is chosen. Click to set one." + : "The response header \(model.effectiveGroupHeader) names the group of a page - click to edit") + .popover(isPresented: $isEditing, arrowEdge: .bottom) { + editor + } + } + + private var editor: some View { + VStack(alignment: .leading, spacing: 10) { + Text("Group Header") + .font(.headline) + TextField("Group header", text: $draft, prompt: Text("x-next-js-app")) + .textFieldStyle(.roundedBorder) + .frame(width: 260) + .onSubmit(save) + Text(note) + .font(.caption) + .foregroundStyle(.secondary) + .frame(width: 260, alignment: .leading) + .fixedSize(horizontal: false, vertical: true) + if let error { + Label(error, systemImage: "exclamationmark.triangle") + .font(.caption) + .foregroundStyle(.red) + .frame(width: 260, alignment: .leading) + .fixedSize(horizontal: false, vertical: true) + } + HStack { + if !isLocal, !model.groupHeader.isEmpty { + Button("Use the Server's") { + model.groupHeader = "" + isEditing = false + } + .help(serverHeader.isEmpty ? "The server's config has no group header" : "The server's config has \(serverHeader)") + } + Spacer() + Button("Cancel") { isEditing = false } + .keyboardShortcut(.cancelAction) + Button(isLocal ? "Save to Config" : "Use") { save() } + .keyboardShortcut(.defaultAction) + .disabled(isSaving) + } + } + .padding(14) + } + + private var note: String { + if isLocal { + return "The response header that names the group of a page, e.g. x-next-js-app: product validates with groups/product.semanticshape.html. Saved to the config as groupheader - the validation here uses it right away, a running walker after a restart." + } + return "The response header that names the group of a page, e.g. x-next-js-app: product validates with groups/product.semanticshape.html. Used for the validation here, the server's config stays as it is" + (serverHeader.isEmpty ? " (it has none)." : " (\(serverHeader)).") + } + + private func save() { + let header = draft.trimmingCharacters(in: .whitespaces) + guard isLocal else { + model.groupHeader = header == serverHeader ? "" : header + isEditing = false + return + } + isSaving = true + error = nil + Task { + defer { isSaving = false } + do { + try await store.setGroupHeader(model.server.id, header: header) + model.groupHeader = header + isEditing = false + } catch { + self.error = "The config could not be written: \(error.localizedDescription)" + } + } + } +} + +/// ShapeRootPanel lets the user choose a shape root folder +enum ShapeRootPanel { + /// choose returns the chosen folder - nil if the user cancelled. from is + /// where the panel starts, a folder or "". + @MainActor + static func choose(from: String) -> String? { + let panel = NSOpenPanel() + panel.canChooseDirectories = true + panel.canChooseFiles = false + panel.canCreateDirectories = true + panel.allowsMultipleSelection = false + panel.prompt = "Choose" + panel.message = "Choose a shape root - the folder with default.semanticshape.html and groups/" + if !from.isEmpty { + panel.directoryURL = URL(filePath: from) + } + guard panel.runModal() == .OK, let url = panel.url else { return nil } + return url.path(percentEncoded: false) + } +} + +/// ShapeRootPrompt is all the section shows without a shape root: the shapes +/// a page is validated with are the first thing it needs. For a local server +/// the folder goes into its config as shaperoot - the walker validates its +/// scrapes with it too. +private struct ShapeRootPrompt: View { + let model: ShapeDevModel + @Environment(ServerStore.self) private var store + @State private var error: String? + @State private var isWriting = false + + private var isLocal: Bool { model.server.configURL != nil } + + var body: some View { + ContentUnavailableView { + Label("No Shape Root", systemImage: "folder.badge.questionmark") + } description: { + if isLocal { + Text("Choose the folder with the semantic shapes of \(model.server.name). It is written to the config as `shaperoot` - a running walker validates its scrapes with it after a restart.") + } else { + Text("Choose the folder with the semantic shapes of \(model.server.name) - a path the server can read, it shares the file system with this app.") + } + } actions: { + Button { + if let path = ShapeRootPanel.choose(from: model.recentRoots.first ?? model.server.configURL?.deletingLastPathComponent().path(percentEncoded: false) ?? "") { + use(path) + } + } label: { + Label("Choose Shape Root…", systemImage: "folder") + } + .buttonStyle(.borderedProminent) + .disabled(isWriting) + if !model.recentRoots.isEmpty { + Menu("Recent") { + ForEach(model.recentRoots, id: \.self) { root in + Button(root) { use(root) } + } + } + .fixedSize() + .disabled(isWriting) + } + if let error { + Label(error, systemImage: "exclamationmark.triangle") + .foregroundStyle(.red) + } + } + } + + /// use takes the folder - for a local server it is written to the config first + private func use(_ path: String) { + guard isLocal else { + model.chooseRoot(path) + return + } + isWriting = true + error = nil + Task { + defer { isWriting = false } + do { + try await store.setShapeRoot(model.server.id, path: path) + if let url = model.server.configURL { + let result = try await store.refreshLocal(model.server.id) + model.follow(result.form, configURL: url) + } + if model.shapeRoot.isEmpty { + model.chooseRoot(path) + } + } catch { + self.error = "The config could not be written: \(error.localizedDescription)" + } + } + } +} + /// ShapeRootMenu picks the shape root - a directory on the server, which /// shares the file system with this app private struct ShapeRootMenu: View { @@ -192,31 +367,41 @@ private struct ShapeRootMenu: View { var body: some View { Menu { - ForEach(model.recentRoots, id: \.self) { root in - Button(root) { model.chooseRoot(root) } + if let configRoot = model.configRoot { + Section("From the Config") { + Button(configRoot) { model.chooseRoot(configRoot) } + } } - if !model.recentRoots.isEmpty { - Divider() + let recent = model.recentRoots.filter { $0 != model.configRoot } + if !recent.isEmpty { + Section("Recent") { + ForEach(recent, id: \.self) { root in + Button(root) { model.chooseRoot(root) } + } + } } + Divider() Button("Choose…") { choose() } } label: { Label(model.shapeRoot.isEmpty ? "Shape Root" : (model.shapeRoot as NSString).lastPathComponent, systemImage: "folder") .labelStyle(.titleAndIcon) } - .help(model.shapeRoot.isEmpty ? "Choose the shape root" : model.shapeRoot) + .help(help) + } + + private var help: String { + if model.shapeRoot.isEmpty { + return "Choose the shape root" + } + if model.shapeRoot == model.configRoot { + return "\(model.shapeRoot) - the shape root of the config of this server" + } + return model.shapeRoot } private func choose() { - let panel = NSOpenPanel() - panel.canChooseDirectories = true - panel.canChooseFiles = false - panel.allowsMultipleSelection = false - panel.message = "Choose a shape root - the directory with default.semanticshape.html and groups/" - if !model.shapeRoot.isEmpty { - panel.directoryURL = URL(filePath: model.shapeRoot) - } - if panel.runModal() == .OK, let url = panel.url { - model.chooseRoot(url.path(percentEncoded: false)) + if let path = ShapeRootPanel.choose(from: model.shapeRoot) { + model.chooseRoot(path) } } } @@ -225,8 +410,6 @@ private struct ShapeRootMenu: View { /// the validation - hovering an element highlights it in the page private struct OutlinePane: View { let model: ShapeDevModel - /// showsContent adds texts, links, images and figures - shared with the result inspector - @AppStorage("outlineShowsContent") private var showsContent = false var body: some View { VStack(spacing: 0) { @@ -235,9 +418,9 @@ private struct OutlinePane: View { content .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) } - // a new page, source or content setting loads again - shape edits don't change the page - .task(id: "\(model.pageVersion) \(model.source.rawValue) \(showsContent)") { - await model.loadOutline(content: showsContent) + // a new page or source loads again - shape edits don't change the page + .task(id: "\(model.pageVersion) \(model.source.rawValue)") { + await model.loadOutline() } } @@ -251,12 +434,9 @@ private struct OutlinePane: View { .foregroundStyle(.secondary) } Spacer() - Toggle("Content", isOn: $showsContent) - .toggleStyle(.switch) - .controlSize(.mini) - .help(showsContent ? "Show the structure only" : "Show the texts, links, images and figures too") } .padding(10) + .help("Click an element to show the content of its branch: texts, links, images, lists and tables") } @ViewBuilder @@ -275,9 +455,12 @@ private struct OutlinePane: View { case let .loaded(result): ScrollView { VStack(alignment: .leading, spacing: 8) { - SemanticDocumentContent(result: result, pageURL: model.highlighter.pageURL ?? model.pageURL) { selector, _ in + SemanticDocumentContent(result: result, pageURL: model.highlighter.pageURL ?? model.pageURL, loadContent: { [model] in + try await model.outlineContent() + }) { selector, _ in model.hoverOutline(selector) } + .id(model.outlineVersion) } .padding(10) .frame(maxWidth: .infinity, alignment: .leading) diff --git a/macos/Walker/Views/ShapeWebView.swift b/macos/Walker/Views/ShapeWebView.swift index 4899a59..750f89a 100644 --- a/macos/Walker/Views/ShapeWebView.swift +++ b/macos/Walker/Views/ShapeWebView.swift @@ -176,18 +176,6 @@ final class ShapeHighlighter { return pageURL != nil && !webView.isLoading } - /// showInspector opens the Web Inspector of the page. WebKit has no public - /// api for it - the private inspector is only used if the web view has it, - /// right click "Inspect Element" works in any case. - func showInspector() { - let inspectorSelector = NSSelectorFromString("_inspector") - let showSelector = NSSelectorFromString("show") - guard let webView, webView.responds(to: inspectorSelector), - let inspector = webView.perform(inspectorSelector)?.takeUnretainedValue() as? NSObject, - inspector.responds(to: showSelector) else { return } - inspector.perform(showSelector) - } - /// snapshot is the html of the DOM as it is now func snapshot() async -> String? { guard let webView else { return nil } diff --git a/macos/Walker/WalkerApp.swift b/macos/Walker/WalkerApp.swift index c21e06a..bca44a8 100644 --- a/macos/Walker/WalkerApp.swift +++ b/macos/Walker/WalkerApp.swift @@ -12,12 +12,6 @@ struct WalkerApp: App { .environment(store) .environment(appDelegate.walkers) } - // the shape developer of a server - a shape and a website side by side - WindowGroup("Shape Developer", id: ShapeDevWindow.id, for: Server.ID.self) { $serverID in - ShapeDevWindow(serverID: serverID) - .environment(store) - .environment(appDelegate.walkers) - } Settings { SettingsView() }