@lincyaw/aegis-ui 0.18.0 → 0.19.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.
- package/dist/components/ui/AnchoredPopover.cjs +1 -1
- package/dist/components/ui/AnchoredPopover.cjs.map +1 -1
- package/dist/components/ui/AnchoredPopover.d.ts +15 -1
- package/dist/components/ui/AnchoredPopover.js +104 -78
- package/dist/components/ui/AnchoredPopover.js.map +1 -1
- package/dist/components/ui/CodeBlock.cjs +2 -2
- package/dist/components/ui/CodeBlock.cjs.map +1 -1
- package/dist/components/ui/CodeBlock.d.ts +10 -1
- package/dist/components/ui/CodeBlock.js +65 -57
- package/dist/components/ui/CodeBlock.js.map +1 -1
- package/dist/components/ui/DetailBeside.cjs +1 -1
- package/dist/components/ui/DetailBeside.cjs.map +1 -1
- package/dist/components/ui/DetailBeside.d.ts +38 -9
- package/dist/components/ui/DetailBeside.js +104 -85
- package/dist/components/ui/DetailBeside.js.map +1 -1
- package/dist/components/ui/index.d.ts +1 -1
- package/dist/lib/scrollView.cjs +1 -1
- package/dist/lib/scrollView.cjs.map +1 -1
- package/dist/lib/scrollView.d.ts +6 -0
- package/dist/lib/scrollView.js +26 -17
- package/dist/lib/scrollView.js.map +1 -1
- package/dist/style.css +1 -1
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const B=require("react/jsx-runtime"),s=require("react"),D=require("react-dom");;/* empty css */const A='a[href], button:not(:disabled), input:not(:disabled):not([type="hidden"]), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])';function M(i,e,c,y,l){const g=window.innerHeight-i.bottom,E=i.top,u=c==="auto"?g>=e.height+l||g>=E?"bottom":"top":c,w=u==="bottom"?i.bottom+l:i.top-l-e.height,h=y==="start"?i.left:i.right-e.width,p=window.innerWidth-e.width-l;return{top:w,left:Math.max(l,Math.min(h,p)),side:u}}function N(i){const e=i.offsetParent;if(!(e instanceof HTMLElement)||e===document.body&&getComputedStyle(e).position==="static")return{top:-window.scrollY,left:-window.scrollX};const c=e.getBoundingClientRect();return{top:c.top+e.clientTop-e.scrollTop,left:c.left+e.clientLeft-e.scrollLeft}}function j({open:i,anchor:e,onClose:c,children:y,placement:l="auto",align:g="start",ariaLabel:E,container:u=null,autoFocus:w=!0,className:h}){const p=s.useRef(null),v=s.useRef(null),[m,L]=s.useState(null),a=i&&e!==null,C=s.useCallback(()=>{const r=p.current;if(!r||!e)return;const t=parseFloat(getComputedStyle(r).getPropertyValue("--anchored-popover-gap")),f=M(e.getBoundingClientRect(),r.getBoundingClientRect(),l,g,Number.isNaN(t)?0:t);if(u===null){L(f);return}const b=N(r);L({...f,top:f.top-b.top,left:f.left-b.left})},[e,l,g,u]);s.useLayoutEffect(()=>{if(!a){L(null);return}C();let r=0;const t=()=>{cancelAnimationFrame(r),r=requestAnimationFrame(C)};return window.addEventListener("scroll",t,!0),window.addEventListener("resize",t),()=>{cancelAnimationFrame(r),window.removeEventListener("scroll",t,!0),window.removeEventListener("resize",t)}},[a,C]);const d=s.useRef({anchor:e,onClose:c});d.current={anchor:e,onClose:c};const R=s.useCallback(()=>{d.current.onClose(),v.current?.focus()},[]);s.useEffect(()=>{if(!a)return;const r=document.activeElement;v.current=r instanceof HTMLElement?r:null;const t=p.current,f=n=>{const{target:o}=n;!(o instanceof Node)||t?.contains(o)||d.current.anchor?.contains?.(o)||d.current.onClose()},b=n=>{if(!t||n.key!=="Tab")return;const o=Array.from(t.querySelectorAll(A)).filter(q=>q.getClientRects().length>0);(n.shiftKey?n.target===t||n.target===o[0]:o.length===0||n.target===o[o.length-1])&&(n.preventDefault(),R())},k=n=>{const{target:o}=n;if(!(!(o instanceof Node)||n.isComposing)){if(n.key==="Tab"&&!n.shiftKey&&t&&!t.contains(o)&&d.current.anchor?.contains?.(o)){n.preventDefault(),v.current=o instanceof HTMLElement?o:null,(t.querySelector(A)??t).focus();return}n.key==="Escape"&&(t?.contains(o)?(n.preventDefault(),n.stopPropagation(),R()):d.current.anchor?.contains?.(o)&&(n.preventDefault(),n.stopPropagation(),d.current.onClose()))}};return document.addEventListener("pointerdown",f,!0),document.addEventListener("keydown",k),t?.addEventListener("keydown",b),()=>{document.removeEventListener("pointerdown",f,!0),document.removeEventListener("keydown",k),t?.removeEventListener("keydown",b)}},[a,R]);const P=m!==null,x=s.useRef(!1);if(s.useEffect(()=>{if(!a){x.current=!1;return}if(!w||!P||x.current)return;x.current=!0;const r=p.current;(r?.querySelector(A)??r)?.focus({preventScroll:!0})},[a,P,w]),!a)return null;const S=["aegis-anchored-popover",u===null?"":"aegis-anchored-popover--contained",m?`aegis-anchored-popover--${m.side}`:"",h??""].filter(Boolean).join(" "),T=m?{top:m.top,left:m.left}:{visibility:"hidden"};return D.createPortal(B.jsx("div",{ref:p,className:S,style:T,role:"dialog","aria-label":E,tabIndex:-1,children:y}),u??document.body)}exports.AnchoredPopover=j;
|
|
2
2
|
//# sourceMappingURL=AnchoredPopover.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AnchoredPopover.cjs","sources":["../../../src/components/ui/AnchoredPopover.tsx"],"sourcesContent":["import {\n type CSSProperties,\n type ReactNode,\n useCallback,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n} from 'react';\n\nimport { createPortal } from 'react-dom';\n\nimport './AnchoredPopover.css';\n\n/**\n * What a popover stands beside: an element, or anything that reports a\n * rectangle in viewport coordinates, such as a range of selected lines.\n */\nexport interface PopoverAnchor {\n getBoundingClientRect: () => DOMRect;\n /** Presses inside the anchor leave the popover open, e.g. to move a selection. */\n contains?: (node: Node) => boolean;\n}\n\nexport interface AnchoredPopoverProps {\n open: boolean;\n anchor: PopoverAnchor | null;\n /** Fired by Escape, a press outside the popover and its anchor, or Tab out of it. */\n onClose: () => void;\n children: ReactNode;\n /**\n * `auto` opens below the anchor and flips above it when there is more\n * room there; `bottom` and `top` keep their side.\n */\n placement?: 'auto' | 'bottom' | 'top';\n /** `start` lines the popover up with the anchor's left edge, `end` with its right. */\n align?: 'start' | 'end';\n /** Accessible name of the popover, which is a non-modal dialog. */\n ariaLabel: string;\n className?: string;\n}\n\nconst TABBABLE =\n 'a[href], button:not(:disabled), input:not(:disabled):not([type=\"hidden\"]), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex=\"-1\"])';\n\ninterface Position {\n top: number;\n left: number;\n side: 'top' | 'bottom';\n}\n\nfunction place(\n anchor: DOMRect,\n panel: DOMRect,\n placement: NonNullable<AnchoredPopoverProps['placement']>,\n align: NonNullable<AnchoredPopoverProps['align']>,\n gap: number,\n): Position {\n const below = window.innerHeight - anchor.bottom;\n const above = anchor.top;\n const side =\n placement === 'auto'\n ? below >= panel.height + gap || below >= above\n ? 'bottom'\n : 'top'\n : placement;\n const top =\n side === 'bottom' ? anchor.bottom + gap : anchor.top - gap - panel.height;\n const preferred =\n align === 'start' ? anchor.left : anchor.right - panel.width;\n const maxLeft = window.innerWidth - panel.width - gap;\n return { top, left: Math.max(gap, Math.min(preferred, maxLeft)), side };\n}\n\n/**\n * Arbitrary content in an overlay beside an anchor, e.g. what is known\n * about a selected code range. It follows the anchor as the page scrolls\n * and closes on Escape, a press outside it, or Tab past its last control.\n * Opening moves focus to its first control; Escape and Tab hand focus back\n * to where it was.\n */\nexport function AnchoredPopover({\n open,\n anchor,\n onClose,\n children,\n placement = 'auto',\n align = 'start',\n ariaLabel,\n className,\n}: AnchoredPopoverProps) {\n const panelRef = useRef<HTMLDivElement>(null);\n const returnFocus = useRef<HTMLElement | null>(null);\n const [position, setPosition] = useState<Position | null>(null);\n const shown = open && anchor !== null;\n\n const update = useCallback(() => {\n const panel = panelRef.current;\n if (!panel || !anchor) {\n return;\n }\n const gap = parseFloat(\n getComputedStyle(panel).getPropertyValue('--anchored-popover-gap'),\n );\n setPosition(\n place(\n anchor.getBoundingClientRect(),\n panel.getBoundingClientRect(),\n placement,\n align,\n Number.isNaN(gap) ? 0 : gap,\n ),\n );\n }, [anchor, placement, align]);\n\n useLayoutEffect(() => {\n if (!shown) {\n setPosition(null);\n return undefined;\n }\n update();\n let frame = 0;\n const schedule = (): void => {\n cancelAnimationFrame(frame);\n frame = requestAnimationFrame(update);\n };\n window.addEventListener('scroll', schedule, true);\n window.addEventListener('resize', schedule);\n return () => {\n cancelAnimationFrame(frame);\n window.removeEventListener('scroll', schedule, true);\n window.removeEventListener('resize', schedule);\n };\n }, [shown, update]);\n\n // Read by listeners that live as long as the popover is open.\n const latest = useRef({ anchor, onClose });\n latest.current = { anchor, onClose };\n\n const closeAndReturn = useCallback(() => {\n latest.current.onClose();\n returnFocus.current?.focus();\n }, []);\n\n useEffect(() => {\n if (!shown) {\n return undefined;\n }\n const active = document.activeElement;\n returnFocus.current = active instanceof HTMLElement ? active : null;\n const panel = panelRef.current;\n const onPointerDown = (event: PointerEvent): void => {\n const { target } = event;\n if (!(target instanceof Node) || panel?.contains(target)) {\n return;\n }\n if (latest.current.anchor?.contains?.(target)) {\n return;\n }\n latest.current.onClose();\n };\n const onKeyDown = (event: KeyboardEvent): void => {\n if (!panel) {\n return;\n }\n if (event.key !== 'Tab') {\n return;\n }\n const tabbable = Array.from(\n panel.querySelectorAll<HTMLElement>(TABBABLE),\n ).filter((element) => element.getClientRects().length > 0);\n const atEdge = event.shiftKey\n ? event.target === panel || event.target === tabbable[0]\n : tabbable.length === 0 ||\n event.target === tabbable[tabbable.length - 1];\n if (atEdge) {\n event.preventDefault();\n closeAndReturn();\n }\n };\n // Escape from the popover or its anchor, e.g. a line number just pressed.\n const onEscape = (event: KeyboardEvent): void => {\n const { target } = event;\n if (event.key !== 'Escape' || event.isComposing) {\n return;\n }\n if (!(target instanceof Node)) {\n return;\n }\n if (panel?.contains(target)) {\n event.preventDefault();\n event.stopPropagation();\n closeAndReturn();\n } else if (latest.current.anchor?.contains?.(target)) {\n event.preventDefault();\n event.stopPropagation();\n latest.current.onClose();\n }\n };\n document.addEventListener('pointerdown', onPointerDown, true);\n document.addEventListener('keydown', onEscape);\n panel?.addEventListener('keydown', onKeyDown);\n return () => {\n document.removeEventListener('pointerdown', onPointerDown, true);\n document.removeEventListener('keydown', onEscape);\n panel?.removeEventListener('keydown', onKeyDown);\n };\n }, [shown, closeAndReturn]);\n\n // Focus moves in once the panel is placed: while hidden it cannot take it.\n const placed = position !== null;\n const focused = useRef(false);\n useEffect(() => {\n if (!shown) {\n focused.current = false;\n return;\n }\n if (!placed || focused.current) {\n return;\n }\n focused.current = true;\n const panel = panelRef.current;\n (panel?.querySelector<HTMLElement>(TABBABLE) ?? panel)?.focus({\n preventScroll: true,\n });\n }, [shown, placed]);\n\n if (!shown) {\n return null;\n }\n const cls = [\n 'aegis-anchored-popover',\n position ? `aegis-anchored-popover--${position.side}` : '',\n className ?? '',\n ]\n .filter(Boolean)\n .join(' ');\n const style: CSSProperties = position\n ? { top: position.top, left: position.left }\n : { visibility: 'hidden' };\n return createPortal(\n <div\n ref={panelRef}\n className={cls}\n style={style}\n role=\"dialog\"\n aria-label={ariaLabel}\n tabIndex={-1}\n >\n {children}\n </div>,\n document.body,\n );\n}\n"],"names":["TABBABLE","place","anchor","panel","placement","align","gap","below","above","side","top","preferred","maxLeft","AnchoredPopover","open","onClose","children","ariaLabel","className","panelRef","useRef","returnFocus","position","setPosition","useState","shown","update","useCallback","useLayoutEffect","frame","schedule","latest","closeAndReturn","useEffect","active","onPointerDown","event","target","onKeyDown","tabbable","element","onEscape","placed","focused","cls","style","createPortal","jsx"],"mappings":"oMA0CA,MAAMA,EACJ,6JAQF,SAASC,EACPC,EACAC,EACAC,EACAC,EACAC,EACU,CACV,MAAMC,EAAQ,OAAO,YAAcL,EAAO,OACpCM,EAAQN,EAAO,IACfO,EACJL,IAAc,OACVG,GAASJ,EAAM,OAASG,GAAOC,GAASC,EACtC,SACA,MACFJ,EACAM,EACJD,IAAS,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AAQ,WAAWM,CAAM,IACjDD,EAAM,eAAA,EACNA,EAAM,gBAAA,EACNL,EAAO,QAAQ,QAAA,GAEnB,EACA,gBAAS,iBAAiB,cAAeI,EAAe,EAAI,EAC5D,SAAS,iBAAiB,UAAWM,CAAQ,EAC7CtC,GAAO,iBAAiB,UAAWmC,CAAS,EACrC,IAAM,CACX,SAAS,oBAAoB,cAAeH,EAAe,EAAI,EAC/D,SAAS,oBAAoB,UAAWM,CAAQ,EAChDtC,GAAO,oBAAoB,UAAWmC,CAAS,CACjD,CACF,EAAG,CAACb,EAAOO,CAAc,CAAC,EAG1B,MAAMU,EAASpB,IAAa,KACtBqB,EAAUvB,EAAAA,OAAO,EAAK,EAgB5B,GAfAa,EAAAA,UAAU,IAAM,CACd,GAAI,CAACR,EAAO,CACVkB,EAAQ,QAAU,GAClB,MACF,CACA,GAAI,CAACD,GAAUC,EAAQ,QACrB,OAEFA,EAAQ,QAAU,GAClB,MAAMxC,EAAQgB,EAAS,SACtBhB,GAAO,cAA2BH,CAAQ,GAAKG,IAAQ,MAAM,CAC5D,cAAe,EAAA,CAChB,CACH,EAAG,CAACsB,EAAOiB,CAAM,CAAC,EAEd,CAACjB,EACH,OAAO,KAET,MAAMmB,EAAM,CACV,yBACAtB,EAAW,2BAA2BA,EAAS,IAAI,GAAK,GACxDJ,GAAa,EAAA,EAEZ,OAAO,OAAO,EACd,KAAK,GAAG,EACL2B,EAAuBvB,EACzB,CAAE,IAAKA,EAAS,IAAK,KAAMA,EAAS,IAAA,EACpC,CAAE,WAAY,QAAA,EAClB,OAAOwB,EAAAA,aACLC,EAAAA,IAAC,MAAA,CACC,IAAK5B,EACL,UAAWyB,EACX,MAAAC,EACA,KAAK,SACL,aAAY5B,EACZ,SAAU,GAET,SAAAD,CAAA,CAAA,EAEH,SAAS,IAAA,CAEb"}
|
|
1
|
+
{"version":3,"file":"AnchoredPopover.cjs","sources":["../../../src/components/ui/AnchoredPopover.tsx"],"sourcesContent":["import {\n type CSSProperties,\n type ReactNode,\n useCallback,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n} from 'react';\n\nimport { createPortal } from 'react-dom';\n\nimport './AnchoredPopover.css';\n\n/**\n * What a popover stands beside: an element, or anything that reports a\n * rectangle in viewport coordinates, such as a range of selected lines.\n */\nexport interface PopoverAnchor {\n getBoundingClientRect: () => DOMRect;\n /** Presses inside the anchor leave the popover open, e.g. to move a selection. */\n contains?: (node: Node) => boolean;\n}\n\nexport interface AnchoredPopoverProps {\n open: boolean;\n anchor: PopoverAnchor | null;\n /** Fired by Escape, a press outside the popover and its anchor, or Tab out of it. */\n onClose: () => void;\n children: ReactNode;\n /**\n * `auto` opens below the anchor and flips above it when there is more\n * room there; `bottom` and `top` keep their side.\n */\n placement?: 'auto' | 'bottom' | 'top';\n /** `start` lines the popover up with the anchor's left edge, `end` with its right. */\n align?: 'start' | 'end';\n /** Accessible name of the popover, which is a non-modal dialog. */\n ariaLabel: string;\n /**\n * The element the popover is drawn in, such as the page's `main`, so it\n * belongs to that landmark; omitted or null means `document.body`. Inside\n * a container the popover is placed in the box of its nearest positioned\n * ancestor and follows the anchor as the container or the page scrolls.\n */\n container?: HTMLElement | null;\n /**\n * Whether opening moves focus into the popover. Turn it off for a popover\n * that opens with the page, such as one over a selection the address\n * names, so it does not take focus on load; Tab from the anchor still\n * enters it.\n */\n autoFocus?: boolean;\n className?: string;\n}\n\nconst TABBABLE =\n 'a[href], button:not(:disabled), input:not(:disabled):not([type=\"hidden\"]), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex=\"-1\"])';\n\ninterface Position {\n top: number;\n left: number;\n side: 'top' | 'bottom';\n}\n\nfunction place(\n anchor: DOMRect,\n panel: DOMRect,\n placement: NonNullable<AnchoredPopoverProps['placement']>,\n align: NonNullable<AnchoredPopoverProps['align']>,\n gap: number,\n): Position {\n const below = window.innerHeight - anchor.bottom;\n const above = anchor.top;\n const side =\n placement === 'auto'\n ? below >= panel.height + gap || below >= above\n ? 'bottom'\n : 'top'\n : placement;\n const top =\n side === 'bottom' ? anchor.bottom + gap : anchor.top - gap - panel.height;\n const preferred =\n align === 'start' ? anchor.left : anchor.right - panel.width;\n const maxLeft = window.innerWidth - panel.width - gap;\n return { top, left: Math.max(gap, Math.min(preferred, maxLeft)), side };\n}\n\n/**\n * The viewport position of the box a contained panel is placed in, less\n * that box's scroll: the panel's offset parent, or the document when that\n * is the unpositioned body.\n */\nfunction originOf(panel: HTMLElement): { top: number; left: number } {\n const parent = panel.offsetParent;\n if (\n !(parent instanceof HTMLElement) ||\n (parent === document.body && getComputedStyle(parent).position === 'static')\n ) {\n return { top: -window.scrollY, left: -window.scrollX };\n }\n const box = parent.getBoundingClientRect();\n return {\n top: box.top + parent.clientTop - parent.scrollTop,\n left: box.left + parent.clientLeft - parent.scrollLeft,\n };\n}\n\n/**\n * Arbitrary content in an overlay beside an anchor, e.g. what is known\n * about a selected code range. It follows the anchor as the page scrolls\n * and closes on Escape, a press outside it, or Tab past its last control.\n * Opening moves focus to its first control; Escape and Tab hand focus back\n * to where it was.\n */\nexport function AnchoredPopover({\n open,\n anchor,\n onClose,\n children,\n placement = 'auto',\n align = 'start',\n ariaLabel,\n container = null,\n autoFocus = true,\n className,\n}: AnchoredPopoverProps) {\n const panelRef = useRef<HTMLDivElement>(null);\n const returnFocus = useRef<HTMLElement | null>(null);\n const [position, setPosition] = useState<Position | null>(null);\n const shown = open && anchor !== null;\n\n const update = useCallback(() => {\n const panel = panelRef.current;\n if (!panel || !anchor) {\n return;\n }\n const gap = parseFloat(\n getComputedStyle(panel).getPropertyValue('--anchored-popover-gap'),\n );\n const next = place(\n anchor.getBoundingClientRect(),\n panel.getBoundingClientRect(),\n placement,\n align,\n Number.isNaN(gap) ? 0 : gap,\n );\n if (container === null) {\n setPosition(next);\n return;\n }\n const origin = originOf(panel);\n setPosition({\n ...next,\n top: next.top - origin.top,\n left: next.left - origin.left,\n });\n }, [anchor, placement, align, container]);\n\n useLayoutEffect(() => {\n if (!shown) {\n setPosition(null);\n return undefined;\n }\n update();\n let frame = 0;\n const schedule = (): void => {\n cancelAnimationFrame(frame);\n frame = requestAnimationFrame(update);\n };\n window.addEventListener('scroll', schedule, true);\n window.addEventListener('resize', schedule);\n return () => {\n cancelAnimationFrame(frame);\n window.removeEventListener('scroll', schedule, true);\n window.removeEventListener('resize', schedule);\n };\n }, [shown, update]);\n\n // Read by listeners that live as long as the popover is open.\n const latest = useRef({ anchor, onClose });\n latest.current = { anchor, onClose };\n\n const closeAndReturn = useCallback(() => {\n latest.current.onClose();\n returnFocus.current?.focus();\n }, []);\n\n useEffect(() => {\n if (!shown) {\n return undefined;\n }\n const active = document.activeElement;\n returnFocus.current = active instanceof HTMLElement ? active : null;\n const panel = panelRef.current;\n const onPointerDown = (event: PointerEvent): void => {\n const { target } = event;\n if (!(target instanceof Node) || panel?.contains(target)) {\n return;\n }\n if (latest.current.anchor?.contains?.(target)) {\n return;\n }\n latest.current.onClose();\n };\n const onKeyDown = (event: KeyboardEvent): void => {\n if (!panel) {\n return;\n }\n if (event.key !== 'Tab') {\n return;\n }\n const tabbable = Array.from(\n panel.querySelectorAll<HTMLElement>(TABBABLE),\n ).filter((element) => element.getClientRects().length > 0);\n const atEdge = event.shiftKey\n ? event.target === panel || event.target === tabbable[0]\n : tabbable.length === 0 ||\n event.target === tabbable[tabbable.length - 1];\n if (atEdge) {\n event.preventDefault();\n closeAndReturn();\n }\n };\n // Escape from the popover or its anchor, e.g. a line number just\n // pressed; Tab from the anchor enters the popover, which a portal puts\n // elsewhere in the tab order.\n const onEscape = (event: KeyboardEvent): void => {\n const { target } = event;\n if (!(target instanceof Node) || event.isComposing) {\n return;\n }\n if (\n event.key === 'Tab' &&\n !event.shiftKey &&\n panel &&\n !panel.contains(target) &&\n latest.current.anchor?.contains?.(target)\n ) {\n event.preventDefault();\n returnFocus.current = target instanceof HTMLElement ? target : null;\n (panel.querySelector<HTMLElement>(TABBABLE) ?? panel).focus();\n return;\n }\n if (event.key !== 'Escape') {\n return;\n }\n if (panel?.contains(target)) {\n event.preventDefault();\n event.stopPropagation();\n closeAndReturn();\n } else if (latest.current.anchor?.contains?.(target)) {\n event.preventDefault();\n event.stopPropagation();\n latest.current.onClose();\n }\n };\n document.addEventListener('pointerdown', onPointerDown, true);\n document.addEventListener('keydown', onEscape);\n panel?.addEventListener('keydown', onKeyDown);\n return () => {\n document.removeEventListener('pointerdown', onPointerDown, true);\n document.removeEventListener('keydown', onEscape);\n panel?.removeEventListener('keydown', onKeyDown);\n };\n }, [shown, closeAndReturn]);\n\n // Focus moves in once the panel is placed: while hidden it cannot take it.\n const placed = position !== null;\n const focused = useRef(false);\n useEffect(() => {\n if (!shown) {\n focused.current = false;\n return;\n }\n if (!autoFocus || !placed || focused.current) {\n return;\n }\n focused.current = true;\n const panel = panelRef.current;\n (panel?.querySelector<HTMLElement>(TABBABLE) ?? panel)?.focus({\n preventScroll: true,\n });\n }, [shown, placed, autoFocus]);\n\n if (!shown) {\n return null;\n }\n const cls = [\n 'aegis-anchored-popover',\n container === null ? '' : 'aegis-anchored-popover--contained',\n position ? `aegis-anchored-popover--${position.side}` : '',\n className ?? '',\n ]\n .filter(Boolean)\n .join(' ');\n const style: CSSProperties = position\n ? { top: position.top, left: position.left }\n : { visibility: 'hidden' };\n return createPortal(\n <div\n ref={panelRef}\n className={cls}\n style={style}\n role=\"dialog\"\n aria-label={ariaLabel}\n tabIndex={-1}\n >\n {children}\n </div>,\n container ?? document.body,\n );\n}\n"],"names":["TABBABLE","place","anchor","panel","placement","align","gap","below","above","side","top","preferred","maxLeft","originOf","parent","box","AnchoredPopover","open","onClose","children","ariaLabel","container","autoFocus","className","panelRef","useRef","returnFocus","position","setPosition","useState","shown","update","useCallback","next","origin","useLayoutEffect","frame","schedule","latest","closeAndReturn","useEffect","active","onPointerDown","event","target","onKeyDown","tabbable","element","onEscape","placed","focused","cls","style","createPortal","jsx"],"mappings":"oMAwDA,MAAMA,EACJ,6JAQF,SAASC,EACPC,EACAC,EACA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AS,oBAAoB,cAAeH,EAAe,EAAI,EAC/D,SAAS,oBAAoB,UAAWM,CAAQ,EAChD7C,GAAO,oBAAoB,UAAW0C,CAAS,CACjD,CACF,EAAG,CAACf,EAAOS,CAAc,CAAC,EAG1B,MAAMU,EAAStB,IAAa,KACtBuB,EAAUzB,EAAAA,OAAO,EAAK,EAgB5B,GAfAe,EAAAA,UAAU,IAAM,CACd,GAAI,CAACV,EAAO,CACVoB,EAAQ,QAAU,GAClB,MACF,CACA,GAAI,CAAC5B,GAAa,CAAC2B,GAAUC,EAAQ,QACnC,OAEFA,EAAQ,QAAU,GAClB,MAAM/C,EAAQqB,EAAS,SACtBrB,GAAO,cAA2BH,CAAQ,GAAKG,IAAQ,MAAM,CAC5D,cAAe,EAAA,CAChB,CACH,EAAG,CAAC2B,EAAOmB,EAAQ3B,CAAS,CAAC,EAEzB,CAACQ,EACH,OAAO,KAET,MAAMqB,EAAM,CACV,yBACA9B,IAAc,KAAO,GAAK,oCAC1BM,EAAW,2BAA2BA,EAAS,IAAI,GAAK,GACxDJ,GAAa,EAAA,EAEZ,OAAO,OAAO,EACd,KAAK,GAAG,EACL6B,EAAuBzB,EACzB,CAAE,IAAKA,EAAS,IAAK,KAAMA,EAAS,IAAA,EACpC,CAAE,WAAY,QAAA,EAClB,OAAO0B,EAAAA,aACLC,EAAAA,IAAC,MAAA,CACC,IAAK9B,EACL,UAAW2B,EACX,MAAAC,EACA,KAAK,SACL,aAAYhC,EACZ,SAAU,GAET,SAAAD,CAAA,CAAA,EAEHE,GAAa,SAAS,IAAA,CAE1B"}
|
|
@@ -23,6 +23,20 @@ export interface AnchoredPopoverProps {
|
|
|
23
23
|
align?: 'start' | 'end';
|
|
24
24
|
/** Accessible name of the popover, which is a non-modal dialog. */
|
|
25
25
|
ariaLabel: string;
|
|
26
|
+
/**
|
|
27
|
+
* The element the popover is drawn in, such as the page's `main`, so it
|
|
28
|
+
* belongs to that landmark; omitted or null means `document.body`. Inside
|
|
29
|
+
* a container the popover is placed in the box of its nearest positioned
|
|
30
|
+
* ancestor and follows the anchor as the container or the page scrolls.
|
|
31
|
+
*/
|
|
32
|
+
container?: HTMLElement | null;
|
|
33
|
+
/**
|
|
34
|
+
* Whether opening moves focus into the popover. Turn it off for a popover
|
|
35
|
+
* that opens with the page, such as one over a selection the address
|
|
36
|
+
* names, so it does not take focus on load; Tab from the anchor still
|
|
37
|
+
* enters it.
|
|
38
|
+
*/
|
|
39
|
+
autoFocus?: boolean;
|
|
26
40
|
className?: string;
|
|
27
41
|
}
|
|
28
42
|
/**
|
|
@@ -32,4 +46,4 @@ export interface AnchoredPopoverProps {
|
|
|
32
46
|
* Opening moves focus to its first control; Escape and Tab hand focus back
|
|
33
47
|
* to where it was.
|
|
34
48
|
*/
|
|
35
|
-
export declare function AnchoredPopover({ open, anchor, onClose, children, placement, align, ariaLabel, className, }: AnchoredPopoverProps): import('react').ReactPortal | null;
|
|
49
|
+
export declare function AnchoredPopover({ open, anchor, onClose, children, placement, align, ariaLabel, container, autoFocus, className, }: AnchoredPopoverProps): import('react').ReactPortal | null;
|
|
@@ -1,118 +1,144 @@
|
|
|
1
|
-
import { jsx as
|
|
2
|
-
import { useRef as
|
|
3
|
-
import { createPortal as
|
|
1
|
+
import { jsx as M } from "react/jsx-runtime";
|
|
2
|
+
import { useRef as b, useState as q, useCallback as B, useLayoutEffect as F, useEffect as R } from "react";
|
|
3
|
+
import { createPortal as H } from "react-dom";
|
|
4
4
|
/* empty css */
|
|
5
|
-
const
|
|
6
|
-
function
|
|
7
|
-
const
|
|
8
|
-
return { top:
|
|
5
|
+
const k = 'a[href], button:not(:disabled), input:not(:disabled):not([type="hidden"]), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])';
|
|
6
|
+
function K(i, t, s, y, c) {
|
|
7
|
+
const m = window.innerHeight - i.bottom, E = i.top, l = s === "auto" ? m >= t.height + c || m >= E ? "bottom" : "top" : s, w = l === "bottom" ? i.bottom + c : i.top - c - t.height, h = y === "start" ? i.left : i.right - t.width, f = window.innerWidth - t.width - c;
|
|
8
|
+
return { top: w, left: Math.max(c, Math.min(h, f)), side: l };
|
|
9
9
|
}
|
|
10
|
-
function
|
|
10
|
+
function j(i) {
|
|
11
|
+
const t = i.offsetParent;
|
|
12
|
+
if (!(t instanceof HTMLElement) || t === document.body && getComputedStyle(t).position === "static")
|
|
13
|
+
return { top: -window.scrollY, left: -window.scrollX };
|
|
14
|
+
const s = t.getBoundingClientRect();
|
|
15
|
+
return {
|
|
16
|
+
top: s.top + t.clientTop - t.scrollTop,
|
|
17
|
+
left: s.left + t.clientLeft - t.scrollLeft
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
function X({
|
|
11
21
|
open: i,
|
|
12
|
-
anchor:
|
|
13
|
-
onClose:
|
|
14
|
-
children:
|
|
15
|
-
placement:
|
|
16
|
-
align:
|
|
17
|
-
ariaLabel:
|
|
18
|
-
|
|
22
|
+
anchor: t,
|
|
23
|
+
onClose: s,
|
|
24
|
+
children: y,
|
|
25
|
+
placement: c = "auto",
|
|
26
|
+
align: m = "start",
|
|
27
|
+
ariaLabel: E,
|
|
28
|
+
container: l = null,
|
|
29
|
+
autoFocus: w = !0,
|
|
30
|
+
className: h
|
|
19
31
|
}) {
|
|
20
|
-
const
|
|
21
|
-
const
|
|
22
|
-
if (!
|
|
32
|
+
const f = b(null), v = b(null), [p, L] = q(null), u = i && t !== null, x = B(() => {
|
|
33
|
+
const r = f.current;
|
|
34
|
+
if (!r || !t)
|
|
23
35
|
return;
|
|
24
36
|
const e = parseFloat(
|
|
25
|
-
getComputedStyle(
|
|
26
|
-
)
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
f,
|
|
33
|
-
Number.isNaN(e) ? 0 : e
|
|
34
|
-
)
|
|
37
|
+
getComputedStyle(r).getPropertyValue("--anchored-popover-gap")
|
|
38
|
+
), d = K(
|
|
39
|
+
t.getBoundingClientRect(),
|
|
40
|
+
r.getBoundingClientRect(),
|
|
41
|
+
c,
|
|
42
|
+
m,
|
|
43
|
+
Number.isNaN(e) ? 0 : e
|
|
35
44
|
);
|
|
36
|
-
|
|
37
|
-
|
|
45
|
+
if (l === null) {
|
|
46
|
+
L(d);
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
const g = j(r);
|
|
50
|
+
L({
|
|
51
|
+
...d,
|
|
52
|
+
top: d.top - g.top,
|
|
53
|
+
left: d.left - g.left
|
|
54
|
+
});
|
|
55
|
+
}, [t, c, m, l]);
|
|
56
|
+
F(() => {
|
|
38
57
|
if (!u) {
|
|
39
|
-
|
|
58
|
+
L(null);
|
|
40
59
|
return;
|
|
41
60
|
}
|
|
42
|
-
|
|
43
|
-
let
|
|
61
|
+
x();
|
|
62
|
+
let r = 0;
|
|
44
63
|
const e = () => {
|
|
45
|
-
cancelAnimationFrame(
|
|
64
|
+
cancelAnimationFrame(r), r = requestAnimationFrame(x);
|
|
46
65
|
};
|
|
47
66
|
return window.addEventListener("scroll", e, !0), window.addEventListener("resize", e), () => {
|
|
48
|
-
cancelAnimationFrame(
|
|
67
|
+
cancelAnimationFrame(r), window.removeEventListener("scroll", e, !0), window.removeEventListener("resize", e);
|
|
49
68
|
};
|
|
50
|
-
}, [u,
|
|
51
|
-
const
|
|
52
|
-
|
|
53
|
-
const
|
|
54
|
-
|
|
69
|
+
}, [u, x]);
|
|
70
|
+
const a = b({ anchor: t, onClose: s });
|
|
71
|
+
a.current = { anchor: t, onClose: s };
|
|
72
|
+
const C = B(() => {
|
|
73
|
+
a.current.onClose(), v.current?.focus();
|
|
55
74
|
}, []);
|
|
56
|
-
|
|
75
|
+
R(() => {
|
|
57
76
|
if (!u)
|
|
58
77
|
return;
|
|
59
|
-
const
|
|
60
|
-
|
|
61
|
-
const e =
|
|
62
|
-
const { target: o } =
|
|
63
|
-
!(o instanceof Node) || e?.contains(o) ||
|
|
64
|
-
},
|
|
65
|
-
if (!e ||
|
|
78
|
+
const r = document.activeElement;
|
|
79
|
+
v.current = r instanceof HTMLElement ? r : null;
|
|
80
|
+
const e = f.current, d = (n) => {
|
|
81
|
+
const { target: o } = n;
|
|
82
|
+
!(o instanceof Node) || e?.contains(o) || a.current.anchor?.contains?.(o) || a.current.onClose();
|
|
83
|
+
}, g = (n) => {
|
|
84
|
+
if (!e || n.key !== "Tab")
|
|
66
85
|
return;
|
|
67
86
|
const o = Array.from(
|
|
68
|
-
e.querySelectorAll(
|
|
69
|
-
).filter((
|
|
70
|
-
(
|
|
71
|
-
},
|
|
72
|
-
const { target: o } =
|
|
73
|
-
|
|
87
|
+
e.querySelectorAll(k)
|
|
88
|
+
).filter((N) => N.getClientRects().length > 0);
|
|
89
|
+
(n.shiftKey ? n.target === e || n.target === o[0] : o.length === 0 || n.target === o[o.length - 1]) && (n.preventDefault(), C());
|
|
90
|
+
}, T = (n) => {
|
|
91
|
+
const { target: o } = n;
|
|
92
|
+
if (!(!(o instanceof Node) || n.isComposing)) {
|
|
93
|
+
if (n.key === "Tab" && !n.shiftKey && e && !e.contains(o) && a.current.anchor?.contains?.(o)) {
|
|
94
|
+
n.preventDefault(), v.current = o instanceof HTMLElement ? o : null, (e.querySelector(k) ?? e).focus();
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
n.key === "Escape" && (e?.contains(o) ? (n.preventDefault(), n.stopPropagation(), C()) : a.current.anchor?.contains?.(o) && (n.preventDefault(), n.stopPropagation(), a.current.onClose()));
|
|
98
|
+
}
|
|
74
99
|
};
|
|
75
|
-
return document.addEventListener("pointerdown",
|
|
76
|
-
document.removeEventListener("pointerdown",
|
|
100
|
+
return document.addEventListener("pointerdown", d, !0), document.addEventListener("keydown", T), e?.addEventListener("keydown", g), () => {
|
|
101
|
+
document.removeEventListener("pointerdown", d, !0), document.removeEventListener("keydown", T), e?.removeEventListener("keydown", g);
|
|
77
102
|
};
|
|
78
|
-
}, [u,
|
|
79
|
-
const
|
|
80
|
-
if (
|
|
103
|
+
}, [u, C]);
|
|
104
|
+
const P = p !== null, A = b(!1);
|
|
105
|
+
if (R(() => {
|
|
81
106
|
if (!u) {
|
|
82
|
-
|
|
107
|
+
A.current = !1;
|
|
83
108
|
return;
|
|
84
109
|
}
|
|
85
|
-
if (!
|
|
110
|
+
if (!w || !P || A.current)
|
|
86
111
|
return;
|
|
87
|
-
|
|
88
|
-
const
|
|
89
|
-
(
|
|
112
|
+
A.current = !0;
|
|
113
|
+
const r = f.current;
|
|
114
|
+
(r?.querySelector(k) ?? r)?.focus({
|
|
90
115
|
preventScroll: !0
|
|
91
116
|
});
|
|
92
|
-
}, [u,
|
|
117
|
+
}, [u, P, w]), !u)
|
|
93
118
|
return null;
|
|
94
|
-
const
|
|
119
|
+
const S = [
|
|
95
120
|
"aegis-anchored-popover",
|
|
96
|
-
|
|
97
|
-
p
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
121
|
+
l === null ? "" : "aegis-anchored-popover--contained",
|
|
122
|
+
p ? `aegis-anchored-popover--${p.side}` : "",
|
|
123
|
+
h ?? ""
|
|
124
|
+
].filter(Boolean).join(" "), D = p ? { top: p.top, left: p.left } : { visibility: "hidden" };
|
|
125
|
+
return H(
|
|
126
|
+
/* @__PURE__ */ M(
|
|
101
127
|
"div",
|
|
102
128
|
{
|
|
103
|
-
ref:
|
|
104
|
-
className:
|
|
105
|
-
style:
|
|
129
|
+
ref: f,
|
|
130
|
+
className: S,
|
|
131
|
+
style: D,
|
|
106
132
|
role: "dialog",
|
|
107
|
-
"aria-label":
|
|
133
|
+
"aria-label": E,
|
|
108
134
|
tabIndex: -1,
|
|
109
|
-
children:
|
|
135
|
+
children: y
|
|
110
136
|
}
|
|
111
137
|
),
|
|
112
|
-
document.body
|
|
138
|
+
l ?? document.body
|
|
113
139
|
);
|
|
114
140
|
}
|
|
115
141
|
export {
|
|
116
|
-
|
|
142
|
+
X as AnchoredPopover
|
|
117
143
|
};
|
|
118
144
|
//# sourceMappingURL=AnchoredPopover.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AnchoredPopover.js","sources":["../../../src/components/ui/AnchoredPopover.tsx"],"sourcesContent":["import {\n type CSSProperties,\n type ReactNode,\n useCallback,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n} from 'react';\n\nimport { createPortal } from 'react-dom';\n\nimport './AnchoredPopover.css';\n\n/**\n * What a popover stands beside: an element, or anything that reports a\n * rectangle in viewport coordinates, such as a range of selected lines.\n */\nexport interface PopoverAnchor {\n getBoundingClientRect: () => DOMRect;\n /** Presses inside the anchor leave the popover open, e.g. to move a selection. */\n contains?: (node: Node) => boolean;\n}\n\nexport interface AnchoredPopoverProps {\n open: boolean;\n anchor: PopoverAnchor | null;\n /** Fired by Escape, a press outside the popover and its anchor, or Tab out of it. */\n onClose: () => void;\n children: ReactNode;\n /**\n * `auto` opens below the anchor and flips above it when there is more\n * room there; `bottom` and `top` keep their side.\n */\n placement?: 'auto' | 'bottom' | 'top';\n /** `start` lines the popover up with the anchor's left edge, `end` with its right. */\n align?: 'start' | 'end';\n /** Accessible name of the popover, which is a non-modal dialog. */\n ariaLabel: string;\n className?: string;\n}\n\nconst TABBABLE =\n 'a[href], button:not(:disabled), input:not(:disabled):not([type=\"hidden\"]), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex=\"-1\"])';\n\ninterface Position {\n top: number;\n left: number;\n side: 'top' | 'bottom';\n}\n\nfunction place(\n anchor: DOMRect,\n panel: DOMRect,\n placement: NonNullable<AnchoredPopoverProps['placement']>,\n align: NonNullable<AnchoredPopoverProps['align']>,\n gap: number,\n): Position {\n const below = window.innerHeight - anchor.bottom;\n const above = anchor.top;\n const side =\n placement === 'auto'\n ? below >= panel.height + gap || below >= above\n ? 'bottom'\n : 'top'\n : placement;\n const top =\n side === 'bottom' ? anchor.bottom + gap : anchor.top - gap - panel.height;\n const preferred =\n align === 'start' ? anchor.left : anchor.right - panel.width;\n const maxLeft = window.innerWidth - panel.width - gap;\n return { top, left: Math.max(gap, Math.min(preferred, maxLeft)), side };\n}\n\n/**\n * Arbitrary content in an overlay beside an anchor, e.g. what is known\n * about a selected code range. It follows the anchor as the page scrolls\n * and closes on Escape, a press outside it, or Tab past its last control.\n * Opening moves focus to its first control; Escape and Tab hand focus back\n * to where it was.\n */\nexport function AnchoredPopover({\n open,\n anchor,\n onClose,\n children,\n placement = 'auto',\n align = 'start',\n ariaLabel,\n className,\n}: AnchoredPopoverProps) {\n const panelRef = useRef<HTMLDivElement>(null);\n const returnFocus = useRef<HTMLElement | null>(null);\n const [position, setPosition] = useState<Position | null>(null);\n const shown = open && anchor !== null;\n\n const update = useCallback(() => {\n const panel = panelRef.current;\n if (!panel || !anchor) {\n return;\n }\n const gap = parseFloat(\n getComputedStyle(panel).getPropertyValue('--anchored-popover-gap'),\n );\n setPosition(\n place(\n anchor.getBoundingClientRect(),\n panel.getBoundingClientRect(),\n placement,\n align,\n Number.isNaN(gap) ? 0 : gap,\n ),\n );\n }, [anchor, placement, align]);\n\n useLayoutEffect(() => {\n if (!shown) {\n setPosition(null);\n return undefined;\n }\n update();\n let frame = 0;\n const schedule = (): void => {\n cancelAnimationFrame(frame);\n frame = requestAnimationFrame(update);\n };\n window.addEventListener('scroll', schedule, true);\n window.addEventListener('resize', schedule);\n return () => {\n cancelAnimationFrame(frame);\n window.removeEventListener('scroll', schedule, true);\n window.removeEventListener('resize', schedule);\n };\n }, [shown, update]);\n\n // Read by listeners that live as long as the popover is open.\n const latest = useRef({ anchor, onClose });\n latest.current = { anchor, onClose };\n\n const closeAndReturn = useCallback(() => {\n latest.current.onClose();\n returnFocus.current?.focus();\n }, []);\n\n useEffect(() => {\n if (!shown) {\n return undefined;\n }\n const active = document.activeElement;\n returnFocus.current = active instanceof HTMLElement ? active : null;\n const panel = panelRef.current;\n const onPointerDown = (event: PointerEvent): void => {\n const { target } = event;\n if (!(target instanceof Node) || panel?.contains(target)) {\n return;\n }\n if (latest.current.anchor?.contains?.(target)) {\n return;\n }\n latest.current.onClose();\n };\n const onKeyDown = (event: KeyboardEvent): void => {\n if (!panel) {\n return;\n }\n if (event.key !== 'Tab') {\n return;\n }\n const tabbable = Array.from(\n panel.querySelectorAll<HTMLElement>(TABBABLE),\n ).filter((element) => element.getClientRects().length > 0);\n const atEdge = event.shiftKey\n ? event.target === panel || event.target === tabbable[0]\n : tabbable.length === 0 ||\n event.target === tabbable[tabbable.length - 1];\n if (atEdge) {\n event.preventDefault();\n closeAndReturn();\n }\n };\n // Escape from the popover or its anchor, e.g. a line number just pressed.\n const onEscape = (event: KeyboardEvent): void => {\n const { target } = event;\n if (event.key !== 'Escape' || event.isComposing) {\n return;\n }\n if (!(target instanceof Node)) {\n return;\n }\n if (panel?.contains(target)) {\n event.preventDefault();\n event.stopPropagation();\n closeAndReturn();\n } else if (latest.current.anchor?.contains?.(target)) {\n event.preventDefault();\n event.stopPropagation();\n latest.current.onClose();\n }\n };\n document.addEventListener('pointerdown', onPointerDown, true);\n document.addEventListener('keydown', onEscape);\n panel?.addEventListener('keydown', onKeyDown);\n return () => {\n document.removeEventListener('pointerdown', onPointerDown, true);\n document.removeEventListener('keydown', onEscape);\n panel?.removeEventListener('keydown', onKeyDown);\n };\n }, [shown, closeAndReturn]);\n\n // Focus moves in once the panel is placed: while hidden it cannot take it.\n const placed = position !== null;\n const focused = useRef(false);\n useEffect(() => {\n if (!shown) {\n focused.current = false;\n return;\n }\n if (!placed || focused.current) {\n return;\n }\n focused.current = true;\n const panel = panelRef.current;\n (panel?.querySelector<HTMLElement>(TABBABLE) ?? panel)?.focus({\n preventScroll: true,\n });\n }, [shown, placed]);\n\n if (!shown) {\n return null;\n }\n const cls = [\n 'aegis-anchored-popover',\n position ? `aegis-anchored-popover--${position.side}` : '',\n className ?? '',\n ]\n .filter(Boolean)\n .join(' ');\n const style: CSSProperties = position\n ? { top: position.top, left: position.left }\n : { visibility: 'hidden' };\n return createPortal(\n <div\n ref={panelRef}\n className={cls}\n style={style}\n role=\"dialog\"\n aria-label={ariaLabel}\n tabIndex={-1}\n >\n {children}\n </div>,\n document.body,\n );\n}\n"],"names":["TABBABLE","place","anchor","panel","placement","align","gap","below","above","side","top","preferred","maxLeft","AnchoredPopover","open","onClose","children","ariaLabel","className","panelRef","useRef","returnFocus","position","setPosition","useState","shown","update","useCallback","useLayoutEffect","frame","schedule","latest","closeAndReturn","useEffect","active","onPointerDown","event","target","onKeyDown","tabbable","element","onEscape","placed","focused","cls","style","createPortal","jsx"],"mappings":";;;;AA0CA,MAAMA,IACJ;AAQF,SAASC,EACPC,GACAC,GACAC,GACAC,GACAC,GACU;AACV,QAAMC,IAAQ,OAAO,cAAcL,EAAO,QACpCM,IAAQN,EAAO,KACfO,IACJL,MAAc,SACVG,KAASJ,EAAM,SAASG,KAAOC,KAASC,IACtC,WACA,QACFJ,GACAM,IACJD,MAAS,WAAWP,EAAO,SAASI,IAAMJ,EAAO,MAAMI,IAAMH,EAAM,QAC/DQ,IACJN,MAAU,UAAUH,EAAO,OAAOA,EAAO,QAAQC,EAAM,OACnDS,IAAU,OAAO,aAAaT,EAAM,QAAQG;AAClD,SAAO,EAAE,KAAAI,GAAK,MAAM,KAAK,IAAIJ,GAAK,KAAK,IAAIK,GAAWC,CAAO,CAAC,GAAG,MAAAH,EAAA;AACnE;AASO,SAASI,EAAgB;AAAA,EAC9B,MAAAC;AAAA,EACA,QAAAZ;AAAA,EACA,SAAAa;AAAA,EACA,UAAAC;AAAA,EACA,WAAAZ,IAAY;AAAA,EACZ,OAAAC,IAAQ;AAAA,EACR,WAAAY;AAAA,EACA,WAAAC;AACF,GAAyB;AACvB,QAAMC,IAAWC,EAAuB,IAAI,GACtCC,IAAcD,EAA2B,IAAI,GAC7C,CAACE,GAAUC,CAAW,IAAIC,EAA0B,IAAI,GACxDC,IAAQX,KAAQZ,MAAW,MAE3BwB,IAASC,EAAY,MAAM;AAC/B,UAAMxB,IAAQgB,EAAS;AACvB,QAAI,CAAChB,KAAS,CAACD;AACb;AAEF,UAAMI,IAAM;AAA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AU;AAClB;AAAA,IACF;AACA,QAAI,CAACD,KAAUC,EAAQ;AACrB;AAEF,IAAAA,EAAQ,UAAU;AAClB,UAAMxC,IAAQgB,EAAS;AACvB,KAAChB,GAAO,cAA2BH,CAAQ,KAAKG,IAAQ,MAAM;AAAA,MAC5D,eAAe;AAAA,IAAA,CAChB;AAAA,EACH,GAAG,CAACsB,GAAOiB,CAAM,CAAC,GAEd,CAACjB;AACH,WAAO;AAET,QAAMmB,IAAM;AAAA,IACV;AAAA,IACAtB,IAAW,2BAA2BA,EAAS,IAAI,KAAK;AAAA,IACxDJ,KAAa;AAAA,EAAA,EAEZ,OAAO,OAAO,EACd,KAAK,GAAG,GACL2B,IAAuBvB,IACzB,EAAE,KAAKA,EAAS,KAAK,MAAMA,EAAS,KAAA,IACpC,EAAE,YAAY,SAAA;AAClB,SAAOwB;AAAA,IACL,gBAAAC;AAAA,MAAC;AAAA,MAAA;AAAA,QACC,KAAK5B;AAAA,QACL,WAAWyB;AAAA,QACX,OAAAC;AAAA,QACA,MAAK;AAAA,QACL,cAAY5B;AAAA,QACZ,UAAU;AAAA,QAET,UAAAD;AAAA,MAAA;AAAA,IAAA;AAAA,IAEH,SAAS;AAAA,EAAA;AAEb;"}
|
|
1
|
+
{"version":3,"file":"AnchoredPopover.js","sources":["../../../src/components/ui/AnchoredPopover.tsx"],"sourcesContent":["import {\n type CSSProperties,\n type ReactNode,\n useCallback,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n} from 'react';\n\nimport { createPortal } from 'react-dom';\n\nimport './AnchoredPopover.css';\n\n/**\n * What a popover stands beside: an element, or anything that reports a\n * rectangle in viewport coordinates, such as a range of selected lines.\n */\nexport interface PopoverAnchor {\n getBoundingClientRect: () => DOMRect;\n /** Presses inside the anchor leave the popover open, e.g. to move a selection. */\n contains?: (node: Node) => boolean;\n}\n\nexport interface AnchoredPopoverProps {\n open: boolean;\n anchor: PopoverAnchor | null;\n /** Fired by Escape, a press outside the popover and its anchor, or Tab out of it. */\n onClose: () => void;\n children: ReactNode;\n /**\n * `auto` opens below the anchor and flips above it when there is more\n * room there; `bottom` and `top` keep their side.\n */\n placement?: 'auto' | 'bottom' | 'top';\n /** `start` lines the popover up with the anchor's left edge, `end` with its right. */\n align?: 'start' | 'end';\n /** Accessible name of the popover, which is a non-modal dialog. */\n ariaLabel: string;\n /**\n * The element the popover is drawn in, such as the page's `main`, so it\n * belongs to that landmark; omitted or null means `document.body`. Inside\n * a container the popover is placed in the box of its nearest positioned\n * ancestor and follows the anchor as the container or the page scrolls.\n */\n container?: HTMLElement | null;\n /**\n * Whether opening moves focus into the popover. Turn it off for a popover\n * that opens with the page, such as one over a selection the address\n * names, so it does not take focus on load; Tab from the anchor still\n * enters it.\n */\n autoFocus?: boolean;\n className?: string;\n}\n\nconst TABBABLE =\n 'a[href], button:not(:disabled), input:not(:disabled):not([type=\"hidden\"]), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex=\"-1\"])';\n\ninterface Position {\n top: number;\n left: number;\n side: 'top' | 'bottom';\n}\n\nfunction place(\n anchor: DOMRect,\n panel: DOMRect,\n placement: NonNullable<AnchoredPopoverProps['placement']>,\n align: NonNullable<AnchoredPopoverProps['align']>,\n gap: number,\n): Position {\n const below = window.innerHeight - anchor.bottom;\n const above = anchor.top;\n const side =\n placement === 'auto'\n ? below >= panel.height + gap || below >= above\n ? 'bottom'\n : 'top'\n : placement;\n const top =\n side === 'bottom' ? anchor.bottom + gap : anchor.top - gap - panel.height;\n const preferred =\n align === 'start' ? anchor.left : anchor.right - panel.width;\n const maxLeft = window.innerWidth - panel.width - gap;\n return { top, left: Math.max(gap, Math.min(preferred, maxLeft)), side };\n}\n\n/**\n * The viewport position of the box a contained panel is placed in, less\n * that box's scroll: the panel's offset parent, or the document when that\n * is the unpositioned body.\n */\nfunction originOf(panel: HTMLElement): { top: number; left: number } {\n const parent = panel.offsetParent;\n if (\n !(parent instanceof HTMLElement) ||\n (parent === document.body && getComputedStyle(parent).position === 'static')\n ) {\n return { top: -window.scrollY, left: -window.scrollX };\n }\n const box = parent.getBoundingClientRect();\n return {\n top: box.top + parent.clientTop - parent.scrollTop,\n left: box.left + parent.clientLeft - parent.scrollLeft,\n };\n}\n\n/**\n * Arbitrary content in an overlay beside an anchor, e.g. what is known\n * about a selected code range. It follows the anchor as the page scrolls\n * and closes on Escape, a press outside it, or Tab past its last control.\n * Opening moves focus to its first control; Escape and Tab hand focus back\n * to where it was.\n */\nexport function AnchoredPopover({\n open,\n anchor,\n onClose,\n children,\n placement = 'auto',\n align = 'start',\n ariaLabel,\n container = null,\n autoFocus = true,\n className,\n}: AnchoredPopoverProps) {\n const panelRef = useRef<HTMLDivElement>(null);\n const returnFocus = useRef<HTMLElement | null>(null);\n const [position, setPosition] = useState<Position | null>(null);\n const shown = open && anchor !== null;\n\n const update = useCallback(() => {\n const panel = panelRef.current;\n if (!panel || !anchor) {\n return;\n }\n const gap = parseFloat(\n getComputedStyle(panel).getPropertyValue('--anchored-popover-gap'),\n );\n const next = place(\n anchor.getBoundingClientRect(),\n panel.getBoundingClientRect(),\n placement,\n align,\n Number.isNaN(gap) ? 0 : gap,\n );\n if (container === null) {\n setPosition(next);\n return;\n }\n const origin = originOf(panel);\n setPosition({\n ...next,\n top: next.top - origin.top,\n left: next.left - origin.left,\n });\n }, [anchor, placement, align, container]);\n\n useLayoutEffect(() => {\n if (!shown) {\n setPosition(null);\n return undefined;\n }\n update();\n let frame = 0;\n const schedule = (): void => {\n cancelAnimationFrame(frame);\n frame = requestAnimationFrame(update);\n };\n window.addEventListener('scroll', schedule, true);\n window.addEventListener('resize', schedule);\n return () => {\n cancelAnimationFrame(frame);\n window.removeEventListener('scroll', schedule, true);\n window.removeEventListener('resize', schedule);\n };\n }, [shown, update]);\n\n // Read by listeners that live as long as the popover is open.\n const latest = useRef({ anchor, onClose });\n latest.current = { anchor, onClose };\n\n const closeAndReturn = useCallback(() => {\n latest.current.onClose();\n returnFocus.current?.focus();\n }, []);\n\n useEffect(() => {\n if (!shown) {\n return undefined;\n }\n const active = document.activeElement;\n returnFocus.current = active instanceof HTMLElement ? active : null;\n const panel = panelRef.current;\n const onPointerDown = (event: PointerEvent): void => {\n const { target } = event;\n if (!(target instanceof Node) || panel?.contains(target)) {\n return;\n }\n if (latest.current.anchor?.contains?.(target)) {\n return;\n }\n latest.current.onClose();\n };\n const onKeyDown = (event: KeyboardEvent): void => {\n if (!panel) {\n return;\n }\n if (event.key !== 'Tab') {\n return;\n }\n const tabbable = Array.from(\n panel.querySelectorAll<HTMLElement>(TABBABLE),\n ).filter((element) => element.getClientRects().length > 0);\n const atEdge = event.shiftKey\n ? event.target === panel || event.target === tabbable[0]\n : tabbable.length === 0 ||\n event.target === tabbable[tabbable.length - 1];\n if (atEdge) {\n event.preventDefault();\n closeAndReturn();\n }\n };\n // Escape from the popover or its anchor, e.g. a line number just\n // pressed; Tab from the anchor enters the popover, which a portal puts\n // elsewhere in the tab order.\n const onEscape = (event: KeyboardEvent): void => {\n const { target } = event;\n if (!(target instanceof Node) || event.isComposing) {\n return;\n }\n if (\n event.key === 'Tab' &&\n !event.shiftKey &&\n panel &&\n !panel.contains(target) &&\n latest.current.anchor?.contains?.(target)\n ) {\n event.preventDefault();\n returnFocus.current = target instanceof HTMLElement ? target : null;\n (panel.querySelector<HTMLElement>(TABBABLE) ?? panel).focus();\n return;\n }\n if (event.key !== 'Escape') {\n return;\n }\n if (panel?.contains(target)) {\n event.preventDefault();\n event.stopPropagation();\n closeAndReturn();\n } else if (latest.current.anchor?.contains?.(target)) {\n event.preventDefault();\n event.stopPropagation();\n latest.current.onClose();\n }\n };\n document.addEventListener('pointerdown', onPointerDown, true);\n document.addEventListener('keydown', onEscape);\n panel?.addEventListener('keydown', onKeyDown);\n return () => {\n document.removeEventListener('pointerdown', onPointerDown, true);\n document.removeEventListener('keydown', onEscape);\n panel?.removeEventListener('keydown', onKeyDown);\n };\n }, [shown, closeAndReturn]);\n\n // Focus moves in once the panel is placed: while hidden it cannot take it.\n const placed = position !== null;\n const focused = useRef(false);\n useEffect(() => {\n if (!shown) {\n focused.current = false;\n return;\n }\n if (!autoFocus || !placed || focused.current) {\n return;\n }\n focused.current = true;\n const panel = panelRef.current;\n (panel?.querySelector<HTMLElement>(TABBABLE) ?? panel)?.focus({\n preventScroll: true,\n });\n }, [shown, placed, autoFocus]);\n\n if (!shown) {\n return null;\n }\n const cls = [\n 'aegis-anchored-popover',\n container === null ? '' : 'aegis-anchored-popover--contained',\n position ? `aegis-anchored-popover--${position.side}` : '',\n className ?? '',\n ]\n .filter(Boolean)\n .join(' ');\n const style: CSSProperties = position\n ? { top: position.top, left: position.left }\n : { visibility: 'hidden' };\n return createPortal(\n <div\n ref={panelRef}\n className={cls}\n style={style}\n role=\"dialog\"\n aria-label={ariaLabel}\n tabIndex={-1}\n >\n {children}\n </div>,\n container ?? document.body,\n );\n}\n"],"names":["TABBABLE","place","anchor","panel","placement","align","gap","below","above","side","top","preferred","maxLeft","originOf","parent","box","AnchoredPopover","open","onClose","children","ariaLabel","container","autoFocus","className","panelRef","useRef","returnFocus","position","setPosition","useState","shown","update","useCallback","next","origin","useLayoutEffect","frame","schedule","latest","closeAndReturn","useEffect","active","onPointerDown","event","target","onKeyDown","tabbable","element","onEscape","placed","focused","cls","style","createPortal","jsx"],"mappings":";;;;AAwDA,MAAMA,IACJ;AAQF,SAASC,EACPC,GACAC,GACAC,GACAC,GACAC,GACU;AACV,QAAMC,IAAQ,OAAO,cAAcL,EAAO,QACpCM,IAAQN,EAAO,KACfO,IACJL,MAAc,SACVG,KAASJ,EAAM,SAASG,KAAOC,KAASC,IACtC,WACA,QACFJ,GACAM,IACJD,MAAS,WAAWP,EAAO,SAASI,IAAMJ,EAAO,MAAMI,IAAMH,EAAM,QAC/DQ,IACJN,MAAU,UAAUH,EAAO,OAAOA,EAAO,QAAQC,EAAM,OACnDS,IAAU,OAAO,aAAaT,EAAM,QAAQG;AAClD,SAAO,EAAE,KAAAI,GAAK,MAAM,KAAK,IAAI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WAAW0C,CAAS;AAAA,IACjD;AAAA,EACF,GAAG,CAACf,GAAOS,CAAc,CAAC;AAG1B,QAAMU,IAAStB,MAAa,MACtBuB,IAAUzB,EAAO,EAAK;AAgB5B,MAfAe,EAAU,MAAM;AACd,QAAI,CAACV,GAAO;AACV,MAAAoB,EAAQ,UAAU;AAClB;AAAA,IACF;AACA,QAAI,CAAC5B,KAAa,CAAC2B,KAAUC,EAAQ;AACnC;AAEF,IAAAA,EAAQ,UAAU;AAClB,UAAM/C,IAAQqB,EAAS;AACvB,KAACrB,GAAO,cAA2BH,CAAQ,KAAKG,IAAQ,MAAM;AAAA,MAC5D,eAAe;AAAA,IAAA,CAChB;AAAA,EACH,GAAG,CAAC2B,GAAOmB,GAAQ3B,CAAS,CAAC,GAEzB,CAACQ;AACH,WAAO;AAET,QAAMqB,IAAM;AAAA,IACV;AAAA,IACA9B,MAAc,OAAO,KAAK;AAAA,IAC1BM,IAAW,2BAA2BA,EAAS,IAAI,KAAK;AAAA,IACxDJ,KAAa;AAAA,EAAA,EAEZ,OAAO,OAAO,EACd,KAAK,GAAG,GACL6B,IAAuBzB,IACzB,EAAE,KAAKA,EAAS,KAAK,MAAMA,EAAS,KAAA,IACpC,EAAE,YAAY,SAAA;AAClB,SAAO0B;AAAA,IACL,gBAAAC;AAAA,MAAC;AAAA,MAAA;AAAA,QACC,KAAK9B;AAAA,QACL,WAAW2B;AAAA,QACX,OAAAC;AAAA,QACA,MAAK;AAAA,QACL,cAAYhC;AAAA,QACZ,UAAU;AAAA,QAET,UAAAD;AAAA,MAAA;AAAA,IAAA;AAAA,IAEHE,KAAa,SAAS;AAAA,EAAA;AAE1B;"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
2
|
-
`),
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("react/jsx-runtime"),o=require("react"),K=require("../../agent/core/usePrimitiveSurface.cjs"),L=require("../../hooks/useCopyToClipboard.cjs");;/* empty css */const z=require("./CopyGlyph.cjs"),I=require("../../locale/useStrings.cjs");function J({code:i,language:b="text",showLineNumbers:w=!1,maxHeight:_,className:N,surface:q,selectedLines:m,onSelectLines:g,onSelectedLinesAnchor:y}){const k=o.useRef(null),h=o.useRef(null),C=o.useRef(null),[M,B]=o.useState(null),n=m===void 0?M:m,x=g!==void 0,T=w||x,O=K.usePrimitiveSurface(q,{code:i,language:b},"code",k),{copied:j,copy:v}=L.useCopyToClipboard(1500),a=I.useStrings(),P=o.useCallback(()=>{v(i)},[v,i]),u=i.split(`
|
|
2
|
+
`),A=String(u.length).length,d=o.useCallback(t=>({getBoundingClientRect:()=>{const c=h.current?.querySelectorAll(".aegis-code-block__line"),e=c?.[t.start-1]?.getBoundingClientRect(),r=c?.[t.end-1]?.getBoundingClientRect();return!e||!r?new DOMRect:new DOMRect(e.left,e.top,e.width,r.bottom-e.top)},contains:c=>h.current?.contains(c)??!1}),[]),D=o.useCallback((t,c)=>{const e=c.shiftKey?C.current:null,l=n?.start===t&&n.end===t&&e===null?null:e===null?{start:t,end:t}:{start:Math.min(e,t),end:Math.max(e,t)};e===null&&(C.current=l?t:null),B(l),g?.(l,l?d(l):null)},[n,g,d]),p=n&&n.start<=u.length?n.start:null,f=n&&p!==null?Math.min(n.end,u.length):null,R=o.useMemo(()=>p===null||f===null?null:d({start:p,end:f}),[d,p,f]),S=o.useRef(y);S.current=y,o.useEffect(()=>{S.current?.(R)},[R]);const E=o.useMemo(()=>n?t=>t>=n.start&&t<=n.end:()=>!1,[n]),G=["aegis-code-block",N??""].filter(Boolean).join(" ");return s.jsxs("div",{ref:k,className:G,...O,children:[s.jsxs("div",{className:"aegis-code-block__header",children:[s.jsx("span",{className:"aegis-code-block__lang",children:b==="text"?a.plainTextLanguage:b}),s.jsxs("button",{type:"button",className:"aegis-code-block__copy",onClick:P,"aria-label":a.copyToClipboard,children:[s.jsx(z.CopyGlyph,{copied:j}),j?a.copied:a.copy]})]}),s.jsx("pre",{ref:h,className:"aegis-code-block__pre",style:_===void 0?void 0:{maxHeight:_},children:s.jsx("code",{children:u.map((t,c)=>{const e=c+1,r=E(e),l=String(e).padStart(A," ");return s.jsxs("div",{className:r?"aegis-code-block__line aegis-code-block__line--selected":"aegis-code-block__line",children:[T&&(x?s.jsx("button",{type:"button",className:"aegis-code-block__ln aegis-code-block__ln--button","aria-label":a.codeLine(e),"aria-pressed":r,onClick:F=>{D(e,F)},children:l}):s.jsx("span",{className:"aegis-code-block__ln",children:l})),s.jsx("span",{className:"aegis-code-block__body",children:t||" "})]},c)})})})]})}exports.CodeBlock=J;
|
|
3
3
|
//# sourceMappingURL=CodeBlock.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CodeBlock.cjs","sources":["../../../src/components/ui/CodeBlock.tsx"],"sourcesContent":["import { type MouseEvent, useCallback, useMemo, useRef, useState } from 'react';\n\nimport {\n type PrimitiveSurface,\n usePrimitiveSurface,\n} from '../../agent/core/usePrimitiveSurface';\nimport { useCopyToClipboard } from '../../hooks/useCopyToClipboard';\nimport { useStrings } from '../../locale';\nimport type { PopoverAnchor } from './AnchoredPopover';\nimport './CodeBlock.css';\nimport { CopyGlyph } from './CopyGlyph';\n\n/** Lines `start` to `end`, 1-based and inclusive. */\nexport interface CodeLineRange {\n start: number;\n end: number;\n}\n\nexport type CodeBlockSurface = PrimitiveSurface<{\n code: string;\n language: string;\n}>;\n\ninterface CodeBlockProps {\n code: string;\n /** Shown as the header label, e.g. `json`, `typescript`, `python`. */\n language?: string;\n showLineNumbers?: boolean;\n /** Caps the code area's height (number → px); longer code scrolls inside. */\n maxHeight?: number | string;\n className?: string;\n surface?: CodeBlockSurface;\n /**\n * The selected lines, drawn in the brand's soft surface with a brand rule\n * at their left. Leave it out to let the block keep its own selection.\n */\n selectedLines?: CodeLineRange | null;\n /**\n * Makes the line numbers buttons that select lines: a press selects its\n * line, Shift extends the range from the last line pressed, and pressing\n * the only selected line clears it. Receives the range and an anchor over\n * its lines, for an `AnchoredPopover`; turns line numbers on.\n */\n onSelectLines?: (\n range: CodeLineRange | null,\n anchor: PopoverAnchor | null,\n ) => void;\n}\n\nexport function CodeBlock({\n code,\n language = 'text',\n showLineNumbers = false,\n maxHeight,\n className,\n surface,\n selectedLines,\n onSelectLines,\n}: CodeBlockProps) {\n const wrapRef = useRef<HTMLDivElement>(null);\n const preRef = useRef<HTMLPreElement>(null);\n const pivot = useRef<number | null>(null);\n const [ownSelection, setOwnSelection] = useState<CodeLineRange | null>(null);\n const selection = selectedLines === undefined ? ownSelection : selectedLines;\n const selectable = onSelectLines !== undefined;\n const numbered = showLineNumbers || selectable;\n const agentAttrs = usePrimitiveSurface(\n surface,\n { code, language },\n 'code',\n wrapRef,\n );\n const { copied, copy } = useCopyToClipboard(1500);\n const strings = useStrings();\n\n const handleCopy = useCallback(() => {\n void copy(code);\n }, [copy, code]);\n\n const lines = code.split('\\n');\n const padLen = String(lines.length).length;\n\n const anchorFor = useCallback(\n (range: CodeLineRange): PopoverAnchor => ({\n getBoundingClientRect: () => {\n const rows = preRef.current?.querySelectorAll<HTMLElement>(\n '.aegis-code-block__line',\n );\n const first = rows?.[range.start - 1]?.getBoundingClientRect();\n const last = rows?.[range.end - 1]?.getBoundingClientRect();\n if (!first || !last) {\n return new DOMRect();\n }\n return new DOMRect(\n first.left,\n first.top,\n first.width,\n last.bottom - first.top,\n );\n },\n contains: (node) => preRef.current?.contains(node) ?? false,\n }),\n [],\n );\n\n const handleLinePress = useCallback(\n (line: number, event: MouseEvent<HTMLButtonElement>) => {\n const from = event.shiftKey ? pivot.current : null;\n const only =\n selection?.start === line && selection.end === line && from === null;\n const next: CodeLineRange | null = only\n ? null\n : from === null\n ? { start: line, end: line }\n : { start: Math.min(from, line), end: Math.max(from, line) };\n if (from === null) {\n pivot.current = next ? line : null;\n }\n setOwnSelection(next);\n onSelectLines?.(next, next ? anchorFor(next) : null);\n },\n [selection, onSelectLines, anchorFor],\n );\n\n const selectedSet = useMemo(\n () =>\n selection\n ? (line: number) => line >= selection.start && line <= selection.end\n : () => false,\n [selection],\n );\n\n const cls = ['aegis-code-block', className ?? ''].filter(Boolean).join(' ');\n\n return (\n <div ref={wrapRef} className={cls} {...agentAttrs}>\n <div className=\"aegis-code-block__header\">\n <span className=\"aegis-code-block__lang\">\n {language === 'text' ? strings.plainTextLanguage : language}\n </span>\n <button\n type=\"button\"\n className=\"aegis-code-block__copy\"\n onClick={handleCopy}\n aria-label={strings.copyToClipboard}\n >\n <CopyGlyph copied={copied} />\n {copied ? strings.copied : strings.copy}\n </button>\n </div>\n <pre\n ref={preRef}\n className=\"aegis-code-block__pre\"\n style={maxHeight === undefined ? undefined : { maxHeight }}\n >\n <code>\n {lines.map((line, i) => {\n const number = i + 1;\n const selected = selectedSet(number);\n const label = String(number).padStart(padLen, ' ');\n return (\n <div\n key={i}\n className={\n selected\n ? 'aegis-code-block__line aegis-code-block__line--selected'\n : 'aegis-code-block__line'\n }\n >\n {numbered &&\n (selectable ? (\n <button\n type=\"button\"\n className=\"aegis-code-block__ln aegis-code-block__ln--button\"\n aria-label={strings.codeLine(number)}\n aria-pressed={selected}\n onClick={(event) => {\n handleLinePress(number, event);\n }}\n >\n {label}\n </button>\n ) : (\n <span className=\"aegis-code-block__ln\">{label}</span>\n ))}\n <span className=\"aegis-code-block__body\">{line || ' '}</span>\n </div>\n );\n })}\n </code>\n </pre>\n </div>\n );\n}\n"],"names":["CodeBlock","code","language","showLineNumbers","maxHeight","className","surface","selectedLines","onSelectLines","wrapRef","useRef","preRef","pivot","ownSelection","setOwnSelection","useState","selection","selectable","numbered","agentAttrs","usePrimitiveSurface","copied","copy","useCopyToClipboard","strings","useStrings","handleCopy","useCallback","lines","padLen","anchorFor","range","rows","first","last","node","handleLinePress","line","event","from","next","selectedSet","useMemo","cls","jsxs","jsx","CopyGlyph","i","number","selected","label"],"mappings":"yVAiDO,SAASA,EAAU,CACxB,KAAAC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AM,EAAE,SAASnB,EAAQ,GAAG,EACjD,OACEe,EAAAA,KAAC,MAAA,CAEC,UACEK,EACI,0DACA,yBAGL,SAAA,CAAA/B,IACED,EACC4B,EAAAA,IAAC,SAAA,CACC,KAAK,SACL,UAAU,oDACV,aAAYrB,EAAQ,SAASwB,CAAM,EACnC,eAAcC,EACd,QAAUX,GAAU,CAClBF,EAAgBY,EAAQV,CAAK,CAC/B,EAEC,SAAAY,CAAA,CAAA,EAGHL,EAAAA,IAAC,OAAA,CAAK,UAAU,uBAAwB,SAAAK,CAAA,CAAM,GAElDL,EAAAA,IAAC,OAAA,CAAK,UAAU,yBAA0B,YAAQ,GAAA,CAAI,CAAA,CAAA,EAvBjDE,CAAA,CA0BX,CAAC,CAAA,CACH,CAAA,CAAA,CACF,EACF,CAEJ"}
|
|
1
|
+
{"version":3,"file":"CodeBlock.cjs","sources":["../../../src/components/ui/CodeBlock.tsx"],"sourcesContent":["import {\n type MouseEvent,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\n\nimport {\n type PrimitiveSurface,\n usePrimitiveSurface,\n} from '../../agent/core/usePrimitiveSurface';\nimport { useCopyToClipboard } from '../../hooks/useCopyToClipboard';\nimport { useStrings } from '../../locale';\nimport type { PopoverAnchor } from './AnchoredPopover';\nimport './CodeBlock.css';\nimport { CopyGlyph } from './CopyGlyph';\n\n/** Lines `start` to `end`, 1-based and inclusive. */\nexport interface CodeLineRange {\n start: number;\n end: number;\n}\n\nexport type CodeBlockSurface = PrimitiveSurface<{\n code: string;\n language: string;\n}>;\n\ninterface CodeBlockProps {\n code: string;\n /** Shown as the header label, e.g. `json`, `typescript`, `python`. */\n language?: string;\n showLineNumbers?: boolean;\n /** Caps the code area's height (number → px); longer code scrolls inside. */\n maxHeight?: number | string;\n className?: string;\n surface?: CodeBlockSurface;\n /**\n * The selected lines, drawn in the brand's soft surface with a brand rule\n * at their left. Leave it out to let the block keep its own selection.\n */\n selectedLines?: CodeLineRange | null;\n /**\n * Makes the line numbers buttons that select lines: a press selects its\n * line, Shift extends the range from the last line pressed, and pressing\n * the only selected line clears it. Receives the range and an anchor over\n * its lines, for an `AnchoredPopover`; turns line numbers on.\n */\n onSelectLines?: (\n range: CodeLineRange | null,\n anchor: PopoverAnchor | null,\n ) => void;\n /**\n * Receives an anchor over the selected lines as drawn, for an\n * `AnchoredPopover`, whenever the drawn selection changes: on mount, on a\n * press, and when a controlled `selectedLines` changes, such as one read\n * from the page's address. Receives null while no line in the code is\n * selected. The anchor measures the lines each time it is asked, so it\n * follows them as the page scrolls or reflows.\n */\n onSelectedLinesAnchor?: (anchor: PopoverAnchor | null) => void;\n}\n\nexport function CodeBlock({\n code,\n language = 'text',\n showLineNumbers = false,\n maxHeight,\n className,\n surface,\n selectedLines,\n onSelectLines,\n onSelectedLinesAnchor,\n}: CodeBlockProps) {\n const wrapRef = useRef<HTMLDivElement>(null);\n const preRef = useRef<HTMLPreElement>(null);\n const pivot = useRef<number | null>(null);\n const [ownSelection, setOwnSelection] = useState<CodeLineRange | null>(null);\n const selection = selectedLines === undefined ? ownSelection : selectedLines;\n const selectable = onSelectLines !== undefined;\n const numbered = showLineNumbers || selectable;\n const agentAttrs = usePrimitiveSurface(\n surface,\n { code, language },\n 'code',\n wrapRef,\n );\n const { copied, copy } = useCopyToClipboard(1500);\n const strings = useStrings();\n\n const handleCopy = useCallback(() => {\n void copy(code);\n }, [copy, code]);\n\n const lines = code.split('\\n');\n const padLen = String(lines.length).length;\n\n const anchorFor = useCallback(\n (range: CodeLineRange): PopoverAnchor => ({\n getBoundingClientRect: () => {\n const rows = preRef.current?.querySelectorAll<HTMLElement>(\n '.aegis-code-block__line',\n );\n const first = rows?.[range.start - 1]?.getBoundingClientRect();\n const last = rows?.[range.end - 1]?.getBoundingClientRect();\n if (!first || !last) {\n return new DOMRect();\n }\n return new DOMRect(\n first.left,\n first.top,\n first.width,\n last.bottom - first.top,\n );\n },\n contains: (node) => preRef.current?.contains(node) ?? false,\n }),\n [],\n );\n\n const handleLinePress = useCallback(\n (line: number, event: MouseEvent<HTMLButtonElement>) => {\n const from = event.shiftKey ? pivot.current : null;\n const only =\n selection?.start === line && selection.end === line && from === null;\n const next: CodeLineRange | null = only\n ? null\n : from === null\n ? { start: line, end: line }\n : { start: Math.min(from, line), end: Math.max(from, line) };\n if (from === null) {\n pivot.current = next ? line : null;\n }\n setOwnSelection(next);\n onSelectLines?.(next, next ? anchorFor(next) : null);\n },\n [selection, onSelectLines, anchorFor],\n );\n\n const drawnStart =\n selection && selection.start <= lines.length ? selection.start : null;\n const drawnEnd =\n selection && drawnStart !== null\n ? Math.min(selection.end, lines.length)\n : null;\n const drawnAnchor = useMemo(\n () =>\n drawnStart === null || drawnEnd === null\n ? null\n : anchorFor({ start: drawnStart, end: drawnEnd }),\n [anchorFor, drawnStart, drawnEnd],\n );\n // Read by the effect below, which runs only when the drawn selection does.\n const anchorListener = useRef(onSelectedLinesAnchor);\n anchorListener.current = onSelectedLinesAnchor;\n useEffect(() => {\n anchorListener.current?.(drawnAnchor);\n }, [drawnAnchor]);\n\n const selectedSet = useMemo(\n () =>\n selection\n ? (line: number) => line >= selection.start && line <= selection.end\n : () => false,\n [selection],\n );\n\n const cls = ['aegis-code-block', className ?? ''].filter(Boolean).join(' ');\n\n return (\n <div ref={wrapRef} className={cls} {...agentAttrs}>\n <div className=\"aegis-code-block__header\">\n <span className=\"aegis-code-block__lang\">\n {language === 'text' ? strings.plainTextLanguage : language}\n </span>\n <button\n type=\"button\"\n className=\"aegis-code-block__copy\"\n onClick={handleCopy}\n aria-label={strings.copyToClipboard}\n >\n <CopyGlyph copied={copied} />\n {copied ? strings.copied : strings.copy}\n </button>\n </div>\n <pre\n ref={preRef}\n className=\"aegis-code-block__pre\"\n style={maxHeight === undefined ? undefined : { maxHeight }}\n >\n <code>\n {lines.map((line, i) => {\n const number = i + 1;\n const selected = selectedSet(number);\n const label = String(number).padStart(padLen, ' ');\n return (\n <div\n key={i}\n className={\n selected\n ? 'aegis-code-block__line aegis-code-block__line--selected'\n : 'aegis-code-block__line'\n }\n >\n {numbered &&\n (selectable ? (\n <button\n type=\"button\"\n className=\"aegis-code-block__ln aegis-code-block__ln--button\"\n aria-label={strings.codeLine(number)}\n aria-pressed={selected}\n onClick={(event) => {\n handleLinePress(number, event);\n }}\n >\n {label}\n </button>\n ) : (\n <span className=\"aegis-code-block__ln\">{label}</span>\n ))}\n <span className=\"aegis-code-block__body\">{line || ' '}</span>\n </div>\n );\n })}\n </code>\n </pre>\n </div>\n );\n}\n"],"names":["CodeBlock","code","language","showLineNumbers","maxHeight","className","surface","selectedLines","onSelectLines","onSelectedLinesAnchor","wrapRef","useRef","preRef","pivot","ownSelection","setOwnSelection","useState","selection","selectable","numbered","agentAttrs","usePrimitiveSurface","copied","copy","useCopyToClipboard","strings","useStrings","handleCopy","useCallback","lines","padLen","anchorFor","range","rows","first","last","node","handleLinePress","line","event","from","next","drawnStart","drawnEnd","drawnAnchor","useMemo","anchorListener","useEffect","selectedSet","cls","jsxs","jsx","CopyGlyph","i","number","selected","label"],"mappings":"yVAiEO,SAASA,EAAU,CACxB,KAAAC,EACA,SAAAC,EAAW,OACX,gBAAAC,EAAkB,GAClB,UAAAC,EACA,UAAAC,EACA,QAAAC,EACA,cAAAC,EACA,cAAAC,EACA,sBAAAC,CACF,EAAmB,CACjB,MAAMC,EAAUC,EAAAA,OAAuB,IAAI,EACrCC,EAASD,EAAAA,OAAuB,IAAI,EACpCE,EAAQF,EAAAA,OAAsB,IAAI,EAClC,CAACG,EAAcC,CAAe,EAAIC,EAAAA,SAA+B,IAAI,EACrEC,EAAYV,IAAkB,OAAYO,EAAeP,EACzDW,EAAaV,IAAkB,OAC/BW,EAAWhB,GAAmBe,EAC9BE,EAAaC,EAAAA,oBACjBf,EACA,CAAE,KAAAL,EAAM,SAAAC,CAAA,EACR,OACAQ,CAAA,EAEI,CAAE,OAAAY,EAAQ,KAAAC,GAASC,EAAAA,mBAAmB,IAAI,EAC1CC,EAA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,UACEK,EACI,0DACA,yBAGL,SAAA,CAAApC,IACED,EACCiC,EAAAA,IAAC,SAAA,CACC,KAAK,SACL,UAAU,oDACV,aAAY1B,EAAQ,SAAS6B,CAAM,EACnC,eAAcC,EACd,QAAUhB,GAAU,CAClBF,EAAgBiB,EAAQf,CAAK,CAC/B,EAEC,SAAAiB,CAAA,CAAA,EAGHL,EAAAA,IAAC,OAAA,CAAK,UAAU,uBAAwB,SAAAK,CAAA,CAAM,GAElDL,EAAAA,IAAC,OAAA,CAAK,UAAU,yBAA0B,YAAQ,GAAA,CAAI,CAAA,CAAA,EAvBjDE,CAAA,CA0BX,CAAC,CAAA,CACH,CAAA,CAAA,CACF,EACF,CAEJ"}
|
|
@@ -30,6 +30,15 @@ interface CodeBlockProps {
|
|
|
30
30
|
* its lines, for an `AnchoredPopover`; turns line numbers on.
|
|
31
31
|
*/
|
|
32
32
|
onSelectLines?: (range: CodeLineRange | null, anchor: PopoverAnchor | null) => void;
|
|
33
|
+
/**
|
|
34
|
+
* Receives an anchor over the selected lines as drawn, for an
|
|
35
|
+
* `AnchoredPopover`, whenever the drawn selection changes: on mount, on a
|
|
36
|
+
* press, and when a controlled `selectedLines` changes, such as one read
|
|
37
|
+
* from the page's address. Receives null while no line in the code is
|
|
38
|
+
* selected. The anchor measures the lines each time it is asked, so it
|
|
39
|
+
* follows them as the page scrolls or reflows.
|
|
40
|
+
*/
|
|
41
|
+
onSelectedLinesAnchor?: (anchor: PopoverAnchor | null) => void;
|
|
33
42
|
}
|
|
34
|
-
export declare function CodeBlock({ code, language, showLineNumbers, maxHeight, className, surface, selectedLines, onSelectLines, }: CodeBlockProps): import("react/jsx-runtime").JSX.Element;
|
|
43
|
+
export declare function CodeBlock({ code, language, showLineNumbers, maxHeight, className, surface, selectedLines, onSelectLines, onSelectedLinesAnchor, }: CodeBlockProps): import("react/jsx-runtime").JSX.Element;
|
|
35
44
|
export {};
|