@bevel-software/platform-core-frontend 0.33.0 → 0.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/package.json +2 -2
  2. package/src/lib/__tests__/api.test.ts +28 -1
  3. package/src/lib/api.ts +4 -2
  4. package/src/modules/access/__tests__/ManageAccessDialog.add-row-picking.test.tsx +53 -1
  5. package/src/modules/access/api.ts +27 -8
  6. package/src/modules/access/components/ManageAccessDialog.tsx +7 -7
  7. package/src/modules/access/index.ts +1 -1
  8. package/src/modules/admin/__tests__/DirectoryGroupsPage.test.tsx +51 -0
  9. package/src/modules/admin/components/DirectoryGroupsPage.tsx +42 -5
  10. package/src/modules/admin/index.ts +1 -1
  11. package/src/modules/admin/services/groups.api.ts +11 -1
  12. package/src/modules/agents/__tests__/useConnectAsChoice.test.ts +56 -0
  13. package/src/modules/agents/components/ConnectAsChoice.tsx +88 -0
  14. package/src/modules/agents/connect-as.ts +15 -0
  15. package/src/modules/agents/index.ts +5 -0
  16. package/src/modules/agents/services/agent-choices.api.ts +39 -0
  17. package/src/modules/agents/useConnectAsChoice.ts +66 -0
  18. package/src/modules/audit/__tests__/AuditLogPage.test.tsx +16 -2
  19. package/src/modules/audit/components/AuditLogPage.tsx +11 -0
  20. package/src/modules/audit/services/audit.api.ts +5 -0
  21. package/src/modules/auth/__tests__/AccountPage.test.tsx +21 -0
  22. package/src/modules/auth/__tests__/account.api.test.ts +69 -0
  23. package/src/modules/auth/components/AccountPage.tsx +8 -2
  24. package/src/modules/auth/index.ts +1 -1
  25. package/src/modules/auth/services/account.api.ts +18 -2
  26. package/src/modules/git/__tests__/BranchSwitcher.test.tsx +0 -14
  27. package/src/modules/git/__tests__/git.api.test.ts +2 -2
  28. package/src/modules/git/hooks/__tests__/useGitState.deleteBranch.test.tsx +1 -1
  29. package/src/modules/library/__tests__/SkillPage.test.tsx +229 -24
  30. package/src/modules/library/__tests__/ToolVarRow.test.tsx +51 -5
  31. package/src/modules/library/components/skill-page/SkillFilePane.tsx +57 -9
  32. package/src/modules/library/components/skill-page/SkillPage.tsx +65 -25
  33. package/src/modules/library/components/tool-page/ToolVarRow.tsx +22 -14
  34. package/src/modules/review/components/MarkdownDiffViewer.tsx +23 -1
  35. package/src/modules/review/components/ReviewPanel.tsx +8 -2
  36. package/src/modules/review/components/__tests__/MarkdownDiffViewer.test.tsx +31 -0
  37. package/src/modules/secrets-vault/components/ConnectToolsPage.tsx +79 -16
  38. package/src/modules/secrets-vault/components/__tests__/ConnectToolsPage.test.tsx +122 -2
  39. package/src/modules/secrets-vault/services/connect.api.ts +20 -5
  40. package/src/modules/toolbar/components/ExternalAgentAccessPage.tsx +45 -4
  41. package/src/modules/toolbar/components/__tests__/ExternalAgentAccessPage.test.tsx +127 -12
  42. package/src/modules/toolbar/services/external-api-keys.api.ts +5 -2
  43. package/src/modules/workspace/components/FileViewer.tsx +1 -1
  44. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +58 -8
  45. package/src/modules/workspace/components/renderers/HtmlRenderer.tsx +40 -7
  46. package/src/modules/workspace/components/renderers/KbAppLink.tsx +56 -0
  47. package/src/modules/workspace/components/renderers/KbMarkdownView.tsx +30 -10
  48. package/src/modules/workspace/components/renderers/MarkdownRenderer.tsx +37 -40
  49. package/src/modules/workspace/components/renderers/__tests__/HtmlRenderer.links.test.tsx +185 -0
  50. package/src/modules/workspace/components/renderers/__tests__/MarkdownRenderer.sectionReclick.test.tsx +88 -0
  51. package/src/modules/workspace/components/renderers/__tests__/MarkdownRenderer.test.tsx +199 -29
  52. package/src/modules/workspace/components/renderers/__tests__/bridgeHarness.ts +37 -4
  53. package/src/modules/workspace/components/renderers/__tests__/htmlSandbox.test.ts +59 -0
  54. package/src/modules/workspace/components/renderers/__tests__/htmlViewsGuide.test.ts +15 -1
  55. package/src/modules/workspace/components/renderers/__tests__/liveDataReferencePage.test.ts +397 -0
  56. package/src/modules/workspace/components/renderers/htmlSandbox.ts +48 -15
  57. package/src/modules/workspace/components/renderers/htmlToolBridge.ts +19 -0
  58. package/src/modules/workspace/components/renderers/kbMarkdownPipeline.tsx +35 -28
  59. package/src/modules/workspace/components/renderers/scrollToHeading.ts +35 -0
  60. package/src/modules/workspace/hooks/__tests__/useLinksOut.test.ts +6 -0
  61. package/src/modules/workspace/hooks/useLinksOut.ts +12 -6
  62. package/src/modules/workspace/index.ts +21 -2
  63. package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +262 -25
  64. package/src/modules/workspace/routing/kb-routes.ts +221 -53
  65. package/src/modules/workspace/utils/__tests__/treeConfirm.test.ts +32 -48
  66. package/src/modules/workspace/utils/fileTree.ts +1 -1
  67. package/src/modules/workspace/utils/treeConfirm.ts +24 -28
@@ -8,6 +8,7 @@ import {
8
8
  useKbMarkdownComponents,
9
9
  type KbImageResolver,
10
10
  } from './kbMarkdownPipeline';
11
+ import { KbAppLink, type KbLinkTarget } from './KbAppLink';
11
12
 
12
13
  // A frontmatter value that is a single markdown link, e.g.
13
14
  // `nodeType: [Process](../../NodeTypes/Process.md)` (parseFrontmatter strips
@@ -31,25 +32,25 @@ const FRONTMATTER_LINK_RE = /^\[([^\]]+)\]\(<?([^)>]+)>?\)$/;
31
32
  function FrontmatterValue({
32
33
  value,
33
34
  onOpenFile,
35
+ fileLinkTarget,
34
36
  }: {
35
37
  value: string;
36
38
  onOpenFile: (href: string) => void;
39
+ fileLinkTarget?: (href: string) => KbLinkTarget | null;
37
40
  }) {
38
41
  const match = value.match(FRONTMATTER_LINK_RE);
39
42
  const href = match ? defaultUrlTransform(match[2]) : '';
40
43
  if (match && href) {
41
44
  const label = match[1];
42
45
  return (
43
- <a
46
+ <KbAppLink
44
47
  href={href}
45
- onClick={(e) => {
46
- e.preventDefault();
47
- onOpenFile(href);
48
- }}
48
+ target={fileLinkTarget?.(href) ?? null}
49
+ onOpen={() => onOpenFile(href)}
49
50
  className="text-accent hover:text-accent-hover hover:underline cursor-pointer"
50
51
  >
51
52
  {label}
52
- </a>
53
+ </KbAppLink>
53
54
  );
54
55
  }
55
56
  return <>{value}</>;
@@ -58,9 +59,11 @@ function FrontmatterValue({
58
59
  function FrontmatterPanel({
59
60
  data,
60
61
  onOpenFile,
62
+ fileLinkTarget,
61
63
  }: {
62
64
  data: Record<string, string | string[]>;
63
65
  onOpenFile: (href: string) => void;
66
+ fileLinkTarget?: (href: string) => KbLinkTarget | null;
64
67
  }) {
65
68
  const entries = Object.entries(data).filter(([, v]) => {
66
69
  if (Array.isArray(v)) return v.length > 0;
@@ -77,7 +80,7 @@ function FrontmatterPanel({
77
80
  {Array.isArray(value) ? (
78
81
  value.join(', ')
79
82
  ) : (
80
- <FrontmatterValue value={value} onOpenFile={onOpenFile} />
83
+ <FrontmatterValue value={value} onOpenFile={onOpenFile} fileLinkTarget={fileLinkTarget} />
81
84
  )}
82
85
  </span>
83
86
  </div>
@@ -102,6 +105,15 @@ interface KbMarkdownViewProps {
102
105
  * which has no in-app navigation).
103
106
  */
104
107
  onOpenNodeId?: (id: string) => void;
108
+ /**
109
+ * Where an in-app link leads (body or link-valued frontmatter), so its
110
+ * anchor names the address the click opens and says when that is a new tab
111
+ * — see `KbAppLink` in the pipeline. The file page passes the file-nav
112
+ * hook's answer; omitted, an anchor carries the href as written.
113
+ */
114
+ fileLinkTarget?: (href: string) => KbLinkTarget | null;
115
+ /** The same for an id-link. */
116
+ nodeIdLinkTarget?: (id: string) => KbLinkTarget | null;
105
117
  /**
106
118
  * When provided, each heading gets a hover-revealed copy button that copies
107
119
  * `headingLink(slug)` — the heading's citation deep-link. `slug` is the
@@ -146,7 +158,7 @@ interface KbMarkdownViewProps {
146
158
  * frontmatter panel, with navigation injected via `onOpenFile` so it carries no
147
159
  * dependency on workspace routing or context.
148
160
  */
149
- export function KbMarkdownView({ source, onOpenFile, onOpenNodeId, headingLink, resolveImage, linkPolicy, containerRef, scroll = true, className }: KbMarkdownViewProps) {
161
+ export function KbMarkdownView({ source, onOpenFile, onOpenNodeId, fileLinkTarget, nodeIdLinkTarget, headingLink, resolveImage, linkPolicy, containerRef, scroll = true, className }: KbMarkdownViewProps) {
150
162
  const { data: frontmatter, body } = useMemo(() => parseFrontmatter(source), [source]);
151
163
  // CommonMark rejects unescaped spaces in link destinations, so a KB link like
152
164
  // `[Foo](Some File.md)` would render as plain text. Wrap space-bearing
@@ -154,14 +166,22 @@ export function KbMarkdownView({ source, onOpenFile, onOpenNodeId, headingLink,
154
166
  // rule covers an image's `![alt](Some Shot.png)` tail.
155
167
  const normalizedBody = useMemo(() => escapeSpacesInLinkDestinations(body), [body]);
156
168
 
157
- const components = useKbMarkdownComponents({ onOpenFile, onOpenNodeId, headingLink, resolveImage, linkPolicy });
169
+ const components = useKbMarkdownComponents({
170
+ onOpenFile,
171
+ onOpenNodeId,
172
+ fileLinkTarget,
173
+ nodeIdLinkTarget,
174
+ headingLink,
175
+ resolveImage,
176
+ linkPolicy,
177
+ });
158
178
 
159
179
  return (
160
180
  <div
161
181
  className={`${scroll ? 'flex-1 overflow-auto' : 'min-w-0'} ${className ?? ''}`}
162
182
  ref={containerRef}
163
183
  >
164
- <FrontmatterPanel data={frontmatter} onOpenFile={onOpenFile} />
184
+ <FrontmatterPanel data={frontmatter} onOpenFile={onOpenFile} fileLinkTarget={fileLinkTarget} />
165
185
  <div className="prose prose-sm max-w-none">
166
186
  <Markdown
167
187
  remarkPlugins={KB_REMARK_PLUGINS}
@@ -6,6 +6,7 @@ import {
6
6
  useFileNav,
7
7
  useNodeIdNav,
8
8
  useCanonicalFileUrl,
9
+ useFileNodeId,
9
10
  } from '../../routing/kb-routes';
10
11
  import { useRendererWorkspaceId } from './rendererWorkspace';
11
12
  import { useRendererSurface } from './rendererSurface';
@@ -13,29 +14,7 @@ import { WorkspaceContext } from '../../state/workspace.context';
13
14
  import { markdownLinkForPaste } from '../../utils/pasteLink';
14
15
  import { useWorkspaceImageResolver } from '../../hooks/useWorkspaceImageResolver';
15
16
  import type { FileRendererProps, RendererSaveState } from './types';
16
-
17
- /** Decode a URL hash (`#some%20slug`) to its bare slug, tolerating bad escapes. */
18
- function safeDecodeHash(hash: string): string {
19
- const raw = hash.replace(/^#/, '');
20
- try {
21
- return decodeURIComponent(raw);
22
- } catch {
23
- return raw;
24
- }
25
- }
26
-
27
- /** Escape a slug for safe interpolation into an attribute-selector string. */
28
- function escapeForSelector(value: string): string {
29
- return (
30
- value
31
- .replace(/["\\]/g, '\\$&')
32
- // CSS-hex-escape control characters (newline, CR, …): a raw control char in
33
- // a CSS string is a syntax error that would make querySelector throw. The
34
- // trailing space terminates the hex escape.
35
- // eslint-disable-next-line no-control-regex
36
- .replace(/[\x00-\x1f\x7f]/g, (c) => `\\${c.charCodeAt(0).toString(16)} `)
37
- );
38
- }
17
+ import { scrollToHeading } from './scrollToHeading';
39
18
 
40
19
  /**
41
20
  * Markdown view/edit renderer driven entirely by the parent's `readOnly`
@@ -63,12 +42,13 @@ export function MarkdownRenderer({
63
42
  onSaveStateChange,
64
43
  readOnly = false,
65
44
  }: FileRendererProps) {
66
- // openLink here is the navigating version: clicking a markdown link to a file
67
- // updates the URL so the route reflects what's on screen.
68
- const { openLink } = useFileNav();
69
- // Shared id-link resolver (resolve-id → openFile, heading preserved) — same
45
+ // A link out of the page opens its file in a new tab and leaves this one
46
+ // where it is; a section link scrolls here. The hook decides which, and
47
+ // `linkTarget` is the same answer for the anchor to carry.
48
+ const { openLink, linkTarget } = useFileNav();
49
+ // Shared id-link follower (the node's id URL, heading preserved) — same
70
50
  // implementation the chat citation renderer uses.
71
- const { openNodeId } = useNodeIdNav();
51
+ const { openNodeId, nodeIdTarget } = useNodeIdNav();
72
52
  // The URL hash carries a heading slug for citation deep-links
73
53
  // (`…/Node.md#goal`); we scroll the matching heading into view once the
74
54
  // rendered content is in the DOM.
@@ -126,19 +106,17 @@ export function MarkdownRenderer({
126
106
  // Deep-link scroll: when the URL has a `#heading-slug` fragment, scroll the
127
107
  // heading with that id (added by rehype-slug) into view. Re-runs when the
128
108
  // hash, the file, or the rendered value changes — the latter because the
129
- // content may still be loading when the route first resolves.
109
+ // content may still be loading when the route first resolves. Also on
110
+ // `location.key`: a section link to this file navigates to this tab's own
111
+ // address plus the fragment, and when the tab is already there the hash
112
+ // string does not change — only the key, which `navigate` renews on every
113
+ // call — so a second click on the same link, after the reader scrolled
114
+ // away, scrolls again instead of doing nothing.
130
115
  useEffect(() => {
131
- if (!readOnly) return;
132
- const slug = location.hash ? safeDecodeHash(location.hash) : '';
133
- if (!slug) return;
134
- const raf = requestAnimationFrame(() => {
135
- const container = scrollContainerRef.current;
136
- if (!container) return;
137
- const target = container.querySelector(`[id="${escapeForSelector(slug)}"]`);
138
- target?.scrollIntoView({ block: 'start' });
139
- });
116
+ if (!readOnly || !location.hash) return;
117
+ const raf = requestAnimationFrame(() => scrollToHeading(scrollContainerRef.current, location.hash));
140
118
  return () => cancelAnimationFrame(raf);
141
- }, [location.hash, filePath, value, readOnly]);
119
+ }, [location.hash, location.key, filePath, value, readOnly]);
142
120
 
143
121
  // Citation deep-link for a heading: the node's canonical URL (its id URL when
144
122
  // it's a node, else the path URL) plus the heading's `#slug`. Matches the "copy
@@ -159,6 +137,23 @@ export function MarkdownRenderer({
159
137
  (href: string) => openLink(href, filePath),
160
138
  [openLink, filePath],
161
139
  );
140
+ const fileLinkTarget = useCallback(
141
+ (href: string) => linkTarget(href, filePath),
142
+ [linkTarget, filePath],
143
+ );
144
+ // An id-link to THIS node is a section link whatever the address bar says:
145
+ // the tab may still be on the path URL (the id not canonicalized yet, or a
146
+ // library frame that never canonicalizes), so the hook is told which node
147
+ // is on screen rather than reading it off the URL.
148
+ const ownNodeId = useFileNodeId(filePath);
149
+ const handleNodeIdLink = useCallback(
150
+ (idOrLink: string) => openNodeId(idOrLink, ownNodeId),
151
+ [openNodeId, ownNodeId],
152
+ );
153
+ const nodeIdLinkTarget = useCallback(
154
+ (idOrLink: string) => nodeIdTarget(idOrLink, ownNodeId),
155
+ [nodeIdTarget, ownNodeId],
156
+ );
162
157
 
163
158
  // An image in the page: the same grammar, but the bytes come from this
164
159
  // workspace's raw file route (a plain `<img>` authenticates through the
@@ -266,7 +261,9 @@ export function MarkdownRenderer({
266
261
  <KbMarkdownView
267
262
  source={value}
268
263
  onOpenFile={handleFileLink}
269
- onOpenNodeId={openNodeId}
264
+ onOpenNodeId={handleNodeIdLink}
265
+ fileLinkTarget={fileLinkTarget}
266
+ nodeIdLinkTarget={nodeIdLinkTarget}
270
267
  headingLink={headingLink}
271
268
  resolveImage={resolveImage}
272
269
  // On a renderer surface (the embed) EVERY outgoing link is the
@@ -0,0 +1,185 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
3
+ import { MemoryRouter, useLocation } from 'react-router-dom';
4
+ import { getFileRenderer } from '..';
5
+ import { GitContext, type GitContextValue } from '../../../../git';
6
+ import { WorkspaceContext, type WorkspaceContextValue } from '../../../state/workspace.context';
7
+ import { PageLinkHomeContext } from '../htmlToolBridge';
8
+
9
+ /**
10
+ * A link written in an HTML page, as the app follows it: the frame's nav
11
+ * bridge posts `bevel.navigate`, and the page's file opens in a NEW TAB at its
12
+ * plain address while this tab — its address, its full-screen view — stays.
13
+ */
14
+
15
+ const HtmlRenderer = getFileRenderer('Dashboards/Roadmap.html');
16
+ const PATH = 'knowledge-base/Dashboards/Roadmap.html';
17
+ const AT = '/workspace/main/knowledge-base/Dashboards/Roadmap.html';
18
+
19
+ const workspace = { workspaceId: 'main', kbDirName: 'knowledge-base' } as unknown as WorkspaceContextValue;
20
+ const git = { status: { branch: 'main' } } as unknown as GitContextValue;
21
+
22
+ function LocationProbe() {
23
+ const location = useLocation();
24
+ return <output data-testid="location">{location.pathname + location.search + location.hash}</output>;
25
+ }
26
+
27
+ function onFilePage(at: string) {
28
+ return render(
29
+ <MemoryRouter initialEntries={[at]}>
30
+ <WorkspaceContext.Provider value={workspace}>
31
+ <GitContext.Provider value={git}>
32
+ <HtmlRenderer content="<h1>Roadmap</h1>" filePath={PATH} onSave={async () => undefined} readOnly />
33
+ <LocationProbe />
34
+ </GitContext.Provider>
35
+ </WorkspaceContext.Provider>
36
+ </MemoryRouter>,
37
+ );
38
+ }
39
+
40
+ function frameOf(container: HTMLElement) {
41
+ return waitFor(() => {
42
+ const el = container.querySelector('iframe');
43
+ if (!el) throw new Error('no frame yet');
44
+ return el;
45
+ });
46
+ }
47
+
48
+ /** Post a link click from the frame, as its nav bridge does; `newTab` for a modified or middle click. */
49
+ async function clickInFrame(container: HTMLElement, href: string, newTab = false) {
50
+ const iframe = await frameOf(container);
51
+ window.dispatchEvent(
52
+ new MessageEvent('message', {
53
+ data: newTab ? { type: 'bevel.navigate', href, newTab } : { type: 'bevel.navigate', href },
54
+ source: iframe.contentWindow,
55
+ }),
56
+ );
57
+ }
58
+
59
+ function stubWindowOpen() {
60
+ return vi.spyOn(window, 'open').mockImplementation(() => ({ opener: window }) as unknown as Window);
61
+ }
62
+
63
+ afterEach(() => {
64
+ cleanup();
65
+ vi.restoreAllMocks();
66
+ });
67
+
68
+ describe('a link inside an HTML page', () => {
69
+ it('opens the linked file in a new tab and leaves this tab where it is', async () => {
70
+ const open = stubWindowOpen();
71
+ const { container } = onFilePage(AT);
72
+ await clickInFrame(container, '../Knowledge/Plan.md');
73
+ expect(open).toHaveBeenCalledWith('/workspace/main/knowledge-base/Knowledge/Plan.md', '_blank');
74
+ expect(screen.getByTestId('location').textContent).toBe(AT);
75
+ });
76
+
77
+ it('in full screen, opens the plain address and the page stays full screen', async () => {
78
+ const open = stubWindowOpen();
79
+ const { container } = onFilePage(`${AT}?fullscreen=1`);
80
+ await clickInFrame(container, 'Board.html#totals');
81
+ expect(open).toHaveBeenCalledWith('/workspace/main/knowledge-base/Dashboards/Board.html#totals', '_blank');
82
+ expect(screen.getByTestId('location').textContent).toBe(`${AT}?fullscreen=1`);
83
+ });
84
+
85
+ it('scrolls a link to a section of the page itself inside the frame, and this tab stays put', async () => {
86
+ const open = stubWindowOpen();
87
+ const { container } = onFilePage(`${AT}?fullscreen=1`);
88
+ const frame = await frameOf(container);
89
+ const post = vi.spyOn(frame.contentWindow!, 'postMessage');
90
+ await clickInFrame(container, 'Roadmap.html#q3');
91
+ await clickInFrame(container, '/workspace/main/knowledge-base/Dashboards/Roadmap.html#q4');
92
+ expect(open).not.toHaveBeenCalled();
93
+ expect(post).toHaveBeenCalledWith({ type: 'bevel.jump', hash: '#q3' }, '*');
94
+ expect(post).toHaveBeenCalledWith({ type: 'bevel.jump', hash: '#q4' }, '*');
95
+ expect(screen.getByTestId('location').textContent).toBe(`${AT}?fullscreen=1`);
96
+ });
97
+
98
+ // Where a section link's new tab lands: `Board.html#totals`. The fragment
99
+ // is on the app's address, which the frame never sees, so the page is
100
+ // handed it once it has loaded, as a click on a section link inside it is.
101
+ it('scrolls the page to the section its address names once the frame has loaded', async () => {
102
+ const { container } = onFilePage(`${AT}#q3`);
103
+ const frame = await frameOf(container);
104
+ const post = vi.spyOn(frame.contentWindow!, 'postMessage');
105
+ fireEvent.load(frame);
106
+ expect(post).toHaveBeenCalledWith({ type: 'bevel.jump', hash: '#q3' }, '*');
107
+ expect(screen.getByTestId('location').textContent).toBe(`${AT}#q3`);
108
+ });
109
+
110
+ it('in full screen, scrolls the page to the section its address names too', async () => {
111
+ const { container } = onFilePage(`${AT}?fullscreen=1#totals`);
112
+ const frame = await frameOf(container);
113
+ const post = vi.spyOn(frame.contentWindow!, 'postMessage');
114
+ fireEvent.load(frame);
115
+ expect(post).toHaveBeenCalledWith({ type: 'bevel.jump', hash: '#totals' }, '*');
116
+ });
117
+
118
+ it('hands the frame no jump when its address names no section', async () => {
119
+ const { container } = onFilePage(AT);
120
+ const frame = await frameOf(container);
121
+ const post = vi.spyOn(frame.contentWindow!, 'postMessage');
122
+ fireEvent.load(frame);
123
+ expect(post).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'bevel.jump' }), '*');
124
+ });
125
+
126
+ it('resolves against the page home its host names (a skill page), on that branch', async () => {
127
+ const open = stubWindowOpen();
128
+ const { container } = render(
129
+ <MemoryRouter initialEntries={['/library/skills/report']}>
130
+ <WorkspaceContext.Provider value={workspace}>
131
+ <GitContext.Provider value={{ status: { branch: 'draft' } } as unknown as GitContextValue}>
132
+ <PageLinkHomeContext.Provider value={{ path: 'knowledge-base/Skills/report/view.html', branch: 'main' }}>
133
+ <HtmlRenderer content="<h1>View</h1>" filePath="view.html" onSave={async () => undefined} readOnly />
134
+ </PageLinkHomeContext.Provider>
135
+ <LocationProbe />
136
+ </GitContext.Provider>
137
+ </WorkspaceContext.Provider>
138
+ </MemoryRouter>,
139
+ );
140
+ const frame = await frameOf(container);
141
+ const post = vi.spyOn(frame.contentWindow!, 'postMessage');
142
+ await clickInFrame(container, 'template.md');
143
+ expect(open).toHaveBeenCalledWith('/workspace/main/knowledge-base/Skills/report/template.md', '_blank');
144
+ await clickInFrame(container, 'view.html#steps');
145
+ expect(post).toHaveBeenCalledWith({ type: 'bevel.jump', hash: '#steps' }, '*');
146
+ expect(open).toHaveBeenCalledTimes(1);
147
+ expect(screen.getByTestId('location').textContent).toBe('/library/skills/report');
148
+ });
149
+
150
+ // A modified or middle click in the page, relayed by the bridge: the
151
+ // browser would open the link in a new tab, so the app does, a section of
152
+ // this page included (where it would otherwise scroll in place), at the
153
+ // plain address; this tab and its full-screen view stay.
154
+ it('opens a modified click in a new tab at the plain address, a section of this page too', async () => {
155
+ const open = stubWindowOpen();
156
+ const { container } = onFilePage(`${AT}?fullscreen=1`);
157
+ const frame = await frameOf(container);
158
+ const post = vi.spyOn(frame.contentWindow!, 'postMessage');
159
+ await clickInFrame(container, 'Board.html', true);
160
+ await clickInFrame(container, '#q3', true);
161
+ await clickInFrame(container, 'Roadmap.html#q4', true);
162
+ expect(open.mock.calls).toEqual([
163
+ ['/workspace/main/knowledge-base/Dashboards/Board.html', '_blank'],
164
+ [`${AT}#q3`, '_blank'],
165
+ [`${AT}#q4`, '_blank'],
166
+ ]);
167
+ expect(post).not.toHaveBeenCalled();
168
+ expect(screen.getByTestId('location').textContent).toBe(`${AT}?fullscreen=1`);
169
+ });
170
+
171
+ it('opens a modified click on an external link in a new tab, as a plain one', async () => {
172
+ const open = vi.spyOn(window, 'open').mockReturnValue(null);
173
+ const { container } = onFilePage(AT);
174
+ await clickInFrame(container, 'https://example.com/docs', true);
175
+ expect(open).toHaveBeenCalledWith('https://example.com/docs', '_blank', 'noopener,noreferrer');
176
+ });
177
+
178
+ it('opens an external link as before, with no referrer', async () => {
179
+ const open = vi.spyOn(window, 'open').mockReturnValue(null);
180
+ const { container } = onFilePage(AT);
181
+ await clickInFrame(container, 'https://example.com/docs');
182
+ expect(open).toHaveBeenCalledWith('https://example.com/docs', '_blank', 'noopener,noreferrer');
183
+ expect(screen.getByTestId('location').textContent).toBe(AT);
184
+ });
185
+ });
@@ -0,0 +1,88 @@
1
+ import { describe, it, expect, afterEach } from 'vitest';
2
+ import { render, screen, waitFor } from '@testing-library/react';
3
+ import userEvent from '@testing-library/user-event';
4
+ import { MemoryRouter, useLocation } from 'react-router-dom';
5
+ import { WorkspaceContext } from '../../../state/workspace.context';
6
+ import { makeWorkspaceFixture } from '../../../__tests__/testFixtures';
7
+ import { GitContext, type GitContextValue } from '../../../../git/state/git.context';
8
+ import { MarkdownRenderer } from '../MarkdownRenderer';
9
+
10
+ /**
11
+ * A section link to the file on screen, clicked TWICE. `MarkdownRenderer.test`
12
+ * stubs the router's `navigate` to assert where a link goes; this file keeps
13
+ * the real one, because the second click is the point: it navigates to the
14
+ * address the tab is already at, so the hash string does not change — only
15
+ * the router's `location.key` — and the heading must scroll into view again
16
+ * all the same, as it would for a reader who scrolled away and clicked the
17
+ * link a second time.
18
+ */
19
+
20
+ function LocationProbe() {
21
+ const location = useLocation();
22
+ return <output data-testid="location">{location.pathname + location.search + location.hash}</output>;
23
+ }
24
+
25
+ const git: GitContextValue = {
26
+ status: { branch: 'alice/draft', hasUpstream: true, unmergedFromUpstream: false },
27
+ branches: [],
28
+ availability: 'ready',
29
+ lastError: null,
30
+ refreshStatus: async () => null,
31
+ refreshBranches: async () => {},
32
+ createBranch: async () => {},
33
+ deleteBranch: async () => {},
34
+ pull: async () => {},
35
+ fetchForkBase: async () => null,
36
+ fetchFileHistory: async () => [],
37
+ fetchFileDiff: async () => '',
38
+ fetchFileAtChange: async () => ({ baseline: null, current: null }),
39
+ fetchFileComparison: async () => '',
40
+ };
41
+
42
+ const originalScrollIntoView = Element.prototype.scrollIntoView;
43
+ afterEach(() => {
44
+ Element.prototype.scrollIntoView = originalScrollIntoView;
45
+ });
46
+
47
+ describe('MarkdownRenderer — a section link clicked again', () => {
48
+ it('scrolls the heading into view on every click, not only when the hash changes', async () => {
49
+ const scrolled: string[] = [];
50
+ Element.prototype.scrollIntoView = function (this: Element) {
51
+ scrolled.push(this.id);
52
+ };
53
+ const content = '# Intro\n\n[Goal](Foo.md#goal)\n\n## Goal\n\nText';
54
+ const tab = { path: 'Knowledge/Foo.md', content, savedContent: content, isDirty: false, pendingFileContent: null };
55
+ render(
56
+ <MemoryRouter initialEntries={['/workspace/alice%2Fdraft/Knowledge/Foo.md']}>
57
+ <WorkspaceContext.Provider
58
+ value={makeWorkspaceFixture({
59
+ openTabs: [tab],
60
+ activeTab: tab,
61
+ openFilePath: 'Knowledge/Foo.md',
62
+ openFileContent: content,
63
+ openFileSavedContent: content,
64
+ })}
65
+ >
66
+ <GitContext.Provider value={git}>
67
+ <MarkdownRenderer content={content} filePath="Knowledge/Foo.md" onSave={async () => {}} readOnly />
68
+ <LocationProbe />
69
+ </GitContext.Provider>
70
+ </WorkspaceContext.Provider>
71
+ </MemoryRouter>,
72
+ );
73
+ const user = userEvent.setup();
74
+ const link = screen.getByRole('link', { name: 'Goal' });
75
+ expect(link).toHaveAttribute('href', '/workspace/alice%2Fdraft/Knowledge/Foo.md#goal');
76
+
77
+ await user.click(link);
78
+ await waitFor(() => expect(scrolled).toEqual(['goal']));
79
+ expect(screen.getByTestId('location').textContent).toBe('/workspace/alice%2Fdraft/Knowledge/Foo.md#goal');
80
+
81
+ // The reader scrolled away and clicks the same link: same address, same
82
+ // hash, and the heading comes back into view. (Queried again: the
83
+ // navigation re-rendered the page's anchors.)
84
+ await user.click(screen.getByRole('link', { name: 'Goal' }));
85
+ await waitFor(() => expect(scrolled).toEqual(['goal', 'goal']));
86
+ expect(screen.getByTestId('location').textContent).toBe('/workspace/alice%2Fdraft/Knowledge/Foo.md#goal');
87
+ });
88
+ });