Unverified Commit 27250721 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

[segment explorer] redesign file pills and boundary trigger (#81302)

parent f0241781
......@@ -10,7 +10,6 @@
border-radius: 8px;
font-size: 14px;
line-height: 1.4;
min-width: 200px;
pointer-events: none;
}
......
import { forwardRef } from 'react'
import { forwardRef, useRef, useState } from 'react'
import { Tooltip as BaseTooltip } from '@base-ui-components/react/tooltip'
import { cx } from '../dev-overlay/utils/cx'
import './tooltip.css'
......@@ -7,22 +7,22 @@ type TooltipDirection = 'top' | 'bottom' | 'left' | 'right'
interface TooltipProps {
children: React.ReactNode
title: string
title: string | null
direction?: TooltipDirection
container?: HTMLElement | React.RefObject<HTMLElement>
arrowSize?: number
offset?: number
bgcolor?: string
color?: string
className?: string
}
export const Tooltip = forwardRef<HTMLDivElement, TooltipProps>(
function Tooltip(
{
className,
children,
title,
direction = 'top',
container,
arrowSize = 6,
offset = 8,
bgcolor = '#000',
......@@ -30,9 +30,18 @@ export const Tooltip = forwardRef<HTMLDivElement, TooltipProps>(
},
ref
) {
const [shadowRoot] = useState<ShadowRoot>(() => {
const ownerDocument = document
const portalNode = ownerDocument.querySelector('nextjs-portal')!
return portalNode.shadowRoot! as ShadowRoot
})
const shadowRootRef = useRef<ShadowRoot>(shadowRoot)
if (!title) {
return children
}
return (
<BaseTooltip.Provider>
<BaseTooltip.Root delay={0}>
<BaseTooltip.Root delay={400}>
<BaseTooltip.Trigger
ref={ref}
render={(triggerProps) => {
......@@ -40,7 +49,9 @@ export const Tooltip = forwardRef<HTMLDivElement, TooltipProps>(
}}
/>
<BaseTooltip.Portal {...(container && { container })}>
{/* x-ref: https://github.com/mui/base-ui/issues/2224 */}
{/* @ts-expect-error remove this expect-error once shadowRoot is supported as container */}
<BaseTooltip.Portal container={shadowRootRef}>
<BaseTooltip.Positioner
side={direction}
sideOffset={offset + arrowSize}
......@@ -53,7 +64,7 @@ export const Tooltip = forwardRef<HTMLDivElement, TooltipProps>(
}
>
<BaseTooltip.Popup
className="tooltip"
className={cx('tooltip', className)}
style={
{
backgroundColor: bgcolor,
......
......@@ -84,14 +84,15 @@ export function useClickOutside(
rootRef: React.RefObject<HTMLElement | null>,
triggerRef: React.RefObject<HTMLButtonElement | null>,
active: boolean,
close: () => void
close: () => void,
ownerDocument?: Document
) {
useEffect(() => {
if (!active) {
return
}
const ownerDocument = rootRef.current?.ownerDocument
const ownerDocumentEl = ownerDocument || rootRef.current?.ownerDocument
function handleClickOutside(event: MouseEvent) {
const target = event.target as HTMLElement
......@@ -124,15 +125,15 @@ export function useClickOutside(
}
}
ownerDocument?.addEventListener('mousedown', handleClickOutside)
ownerDocument?.addEventListener('keydown', handleKeyDown)
ownerDocumentEl?.addEventListener('mousedown', handleClickOutside)
ownerDocumentEl?.addEventListener('keydown', handleKeyDown)
return () => {
ownerDocument?.removeEventListener('mousedown', handleClickOutside)
ownerDocument?.removeEventListener('keydown', handleKeyDown)
ownerDocumentEl?.removeEventListener('mousedown', handleClickOutside)
ownerDocumentEl?.removeEventListener('keydown', handleKeyDown)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [active])
}, [active, rootRef, triggerRef])
}
//////////////////////////////////////////////////////////////////////////////////////
......
.segment-boundary-trigger {
margin-left: auto;
gap: 8px;
}
.segment-boundary-trigger-button {
width: 24px;
height: 24px;
display: flex;
align-items: center;
justify-content: center;
gap: 4px;
padding: 4px 6px;
line-height: 16px;
font-weight: 500;
color: var(--color-gray-1000);
border-radius: 6px;
background: transparent;
border-radius: 999px;
border: none;
font-size: var(--size-12);
cursor: pointer;
transition: background-color 0.15s ease;
}
.segment-boundary-trigger-text {
font-size: var(--size-12);
font-weight: 500;
user-select: none;
display: inline-flex;
align-items: center;
justify-content: center;
}
.segment-boundary-trigger-button svg {
width: 20px;
height: 20px;
.segment-boundary-trigger-text .plus-icon {
transition: transform 0.25s ease;
}
.segment-boundary-trigger-button:hover {
background: var(--color-gray-400);
color: var(--color-gray-1000);
.segment-boundary-trigger-text:hover .plus-icon {
color: var(--color-gray-800);
}
.segment-boundary-trigger svg {
width: 14px;
height: 14px;
flex-shrink: 0;
vertical-align: middle;
}
.segment-boundary-trigger:hover svg {
color: var(--color-gray-700);
}
.segment-boundary-trigger[disabled] svg,
.segment-boundary-trigger[disabled]:hover svg {
color: var(--color-gray-400);
cursor: not-allowed;
}
.segment-boundary-trigger--boundary {
background: var(--color-background-100);
box-shadow: inset 0 0 0 1px var(--color-gray-400);
}
.segment-boundary-trigger--boundary:hover {
background: var(--color-gray-200);
}
.segment-boundary-dropdown {
padding: 8px;
background: var(--color-background-100);
border: 1px solid var(--color-gray-400);
border-radius: 6px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
border-radius: 16px;
min-width: 120px;
user-select: none;
cursor: default;
box-shadow: 0px 4px 8px -4px color-mix(in srgb, var(--color-gray-900) 4%, transparent);
}
.segment-boundary-dropdown-positioner {
z-index: 2147483648;
z-index: var(--top-z-index);
}
.segment-boundary-dropdown-item {
display: flex;
align-items: center;
padding: 10px 8px;
padding: 8px;
line-height: 20px;
font-size: 14px;
border-radius: 6px;
......@@ -78,8 +110,10 @@
border-bottom-right-radius: 4px;
}
.segment-boundary-dropdown-divider {
height: 1px;
background: var(--color-gray-400);
margin: 8px 0;
.segment-boundary-group-label {
padding: 8px;
font-size: 13px;
line-height: 16px;
font-weight: 400;
color: var(--color-gray-900);
}
import './segment-boundary-trigger.css'
import { useCallback, useState, useRef } from 'react'
import { useCallback, useState, useRef, useMemo } from 'react'
import { Menu } from '@base-ui-components/react/menu'
import type { SegmentNodeState } from '../../../userspace/app/segment-explorer-node'
import {
isBoundaryFile,
normalizeBoundaryFilename,
} from '../../../../server/app-render/segment-explorer-path'
import { cx } from '../../utils/cx'
import { useClickOutside } from '../errors/dev-tools-indicator/utils'
const composeRefs = (...refs: (React.Ref<HTMLButtonElement> | undefined)[]) => {
return (node: HTMLButtonElement | null) => {
refs.forEach((ref) => {
if (typeof ref === 'function') {
ref(node)
} else if (ref) {
ref.current = node
}
})
}
}
export function SegmentBoundaryTrigger({
onSelectBoundary,
offset,
nodeState,
boundaries,
}: {
onSelectBoundary: SegmentNodeState['setBoundaryType']
offset: number
nodeState: SegmentNodeState
boundaries: Record<'not-found' | 'loading' | 'error', string | null>
}) {
const currNode = nodeState
const {
pagePath,
boundaryType,
type,
setBoundaryType: onSelectBoundary,
} = currNode
const fileType = type
const [isOpen, setIsOpen] = useState(false)
// TODO: move this shadowRoot ref util to a shared hook or into context
const [shadowRoot] = useState<ShadowRoot>(() => {
const ownerDocument = document
const portalNode = ownerDocument.querySelector('nextjs-portal')!
return portalNode.shadowRoot! as ShadowRoot
})
const shadowRootRef = useRef<ShadowRoot>(shadowRoot)
const triggerRef = useRef<HTMLButtonElement>(null)
const popupRef = useRef<HTMLDivElement>(null)
// Click outside of popup should close the menu
useClickOutside(
popupRef,
triggerRef,
isOpen,
() => {
setIsOpen(false)
},
triggerRef.current?.ownerDocument
)
const firstDefinedBoundary = Object.values(boundaries).find((v) => v !== null)
const possibleExtension = firstDefinedBoundary
? firstDefinedBoundary.split('.')?.pop()
: 'js'
const fileNames = useMemo(() => {
return Object.fromEntries(
Object.entries(boundaries).map(([key, filePath]) => {
const fileName = normalizeBoundaryFilename(
(filePath || '').split('/').pop() || `${key}.${possibleExtension}`
)
return [key, fileName]
})
) as Record<keyof typeof boundaries, string>
}, [boundaries, possibleExtension])
const fileName = (pagePath || '').split('/').pop() || ''
const isBoundary = isBoundaryFile(fileType)
const pageFileName = normalizeBoundaryFilename(
boundaryType
? `page.${possibleExtension}`
: fileName || `page.${possibleExtension}`
)
const isPageOrBoundary = fileType && !isBoundary
const triggerOptions = [
{
label: 'Trigger Loading',
label: fileNames.loading,
value: 'loading',
icon: <LoadingIcon />,
disabled: !boundaries.loading,
},
{
label: 'Trigger Error',
label: fileNames.error,
value: 'error',
icon: <ErrorIcon />,
disabled: !boundaries.error,
},
{
label: 'Trigger Not Found',
label: fileNames['not-found'],
value: 'not-found',
icon: <NotFoundIcon />,
disabled: !boundaries['not-found'],
......@@ -41,11 +107,25 @@ export function SegmentBoundaryTrigger({
]
const resetOption = {
label: 'Reset',
label: boundaryType ? 'Reset' : pageFileName,
value: 'reset',
icon: <ResetIcon />,
disabled: boundaryType === null,
}
const openInEditor = useCallback(({ filePath }: { filePath: string }) => {
const params = new URLSearchParams({
file: filePath,
isAppRelativePath: '1',
})
fetch(
`${
process.env.__NEXT_ROUTER_BASEPATH || ''
}/__nextjs_launch-editor?${params.toString()}`
// Log the failures to console, not track them as console errors in error overlay
).catch(console.warn)
}, [])
const handleSelect = useCallback(
(value: string) => {
switch (value) {
......@@ -57,24 +137,36 @@ export function SegmentBoundaryTrigger({
case 'reset':
onSelectBoundary(null)
break
case 'open-editor':
if (pagePath) {
openInEditor({ filePath: pagePath })
}
break
default:
break
}
},
[onSelectBoundary]
[onSelectBoundary, pagePath, openInEditor]
)
const MergedRefTrigger = (
triggerProps: React.ComponentProps<'button'> & {
ref?: React.Ref<HTMLButtonElement>
}
) => {
const mergedRef = composeRefs(triggerProps.ref, triggerRef)
return <Trigger {...triggerProps} ref={mergedRef} />
}
return (
<div className="segment-boundary-trigger">
<Menu.Root delay={0}>
<Menu.Root delay={0} modal={false} open={isOpen} onOpenChange={setIsOpen}>
<Menu.Trigger
className="segment-boundary-trigger-button"
data-nextjs-dev-overlay-segment-boundary-trigger-button
render={(triggerProps) => (
<button {...triggerProps} type="button">
<DropdownIcon />
</button>
className={cx(
'segment-boundary-trigger',
!isPageOrBoundary && 'segment-boundary-trigger--boundary'
)}
data-nextjs-dev-overlay-segment-boundary-trigger-button
render={MergedRefTrigger}
/>
{/* @ts-expect-error remove this expect-error once shadowRoot is supported as container */}
......@@ -83,10 +175,16 @@ export function SegmentBoundaryTrigger({
className="segment-boundary-dropdown-positioner"
side="bottom"
align="center"
sideOffset={offset}
sideOffset={6}
arrowPadding={8}
ref={popupRef}
>
<Menu.Popup className="segment-boundary-dropdown">
{
<Menu.Group>
<Menu.GroupLabel className="segment-boundary-group-label">
Toggle Overrides
</Menu.GroupLabel>
{triggerOptions.map((option) => (
<Menu.Item
key={option.value}
......@@ -98,43 +196,26 @@ export function SegmentBoundaryTrigger({
{option.label}
</Menu.Item>
))}
</Menu.Group>
}
<div className="segment-boundary-dropdown-divider" />
<Menu.Group>
{
<Menu.Item
key={resetOption.value}
className="segment-boundary-dropdown-item"
onClick={() => handleSelect(resetOption.value)}
disabled={resetOption.disabled}
>
{resetOption.icon}
{resetOption.label}
</Menu.Item>
}
</Menu.Group>
</Menu.Popup>
</Menu.Positioner>
</Menu.Portal>
</Menu.Root>
</div>
)
}
/**
* Inline svg icons for the dropdown trigger.
* The child svg icons like `rect` are fixed size, so they can be used as shared scalable icons.
*/
function DropdownIcon() {
return (
<svg
width="20px"
height="20px"
viewBox="0 0 16 16"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M2.5 6.5C3.32843 6.5 4 7.17157 4 8C4 8.82843 3.32843 9.5 2.5 9.5C1.67157 9.5 1 8.82843 1 8C1 7.17157 1.67157 6.5 2.5 6.5ZM8 6.5C8.82843 6.5 9.5 7.17157 9.5 8C9.5 8.82843 8.82843 9.5 8 9.5C7.17157 9.5 6.5 8.82843 6.5 8C6.5 7.17157 7.17157 6.5 8 6.5ZM13.5 6.5C14.3284 6.5 15 7.17157 15 8C15 8.82843 14.3284 9.5 13.5 9.5C12.6716 9.5 12 8.82843 12 8C12 7.17157 12.6716 6.5 13.5 6.5Z"
fill="currentColor"
/>
</svg>
)
}
......@@ -235,3 +316,30 @@ function ResetIcon() {
</svg>
)
}
function SwitchIcon(props: React.SVGProps<SVGSVGElement>) {
return (
<svg strokeLinejoin="round" viewBox="0 0 16 16" {...props}>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M8.7071 2.39644C8.31658 2.00592 7.68341 2.00592 7.29289 2.39644L4.46966 5.21966L3.93933 5.74999L4.99999 6.81065L5.53032 6.28032L7.99999 3.81065L10.4697 6.28032L11 6.81065L12.0607 5.74999L11.5303 5.21966L8.7071 2.39644ZM5.53032 9.71966L4.99999 9.18933L3.93933 10.25L4.46966 10.7803L7.29289 13.6035C7.68341 13.9941 8.31658 13.9941 8.7071 13.6035L11.5303 10.7803L12.0607 10.25L11 9.18933L10.4697 9.71966L7.99999 12.1893L5.53032 9.71966Z"
fill="currentColor"
></path>
</svg>
)
}
export function Trigger(props: React.ComponentProps<'button'>) {
return (
<button
{...props}
className={cx('segment-boundary-trigger', props.className)}
role="button"
>
<span className="segment-boundary-trigger-text">
<SwitchIcon className="plus-icon" />
</span>
</button>
)
}
.segment-explorer-content {
font-size: var(--size-14);
padding: 0 8px;
width: 700px;
height: 400px;
max-width: calc(100vw - 40px);
max-height: calc(100vh - 240px);
}
.segment-explorer-page-route-bar {
......@@ -17,6 +21,7 @@
color: var(--color-gray-1000);
font-family: var(--font-mono);
white-space: nowrap;
line-height: 20px;
}
.segment-explorer-item {
......@@ -54,7 +59,7 @@
}
.segment-explorer-filename--path {
margin-right: 8px;
margin-right: auto;
}
.segment-explorer-filename--path small {
display: inline-block;
......@@ -68,57 +73,118 @@
.segment-explorer-files {
display: inline-flex;
gap: 8px;
margin-left: auto;
}
.segment-explorer-files + .segment-boundary-trigger {
margin-left: 8px;
}
.segment-explorer-file-label {
display: inline-flex;
align-items: center;
justify-content: center;
height: 20px;
padding: 2px 6px;
padding: 4px 6px;
border-radius: 16px;
line-height: 16px;
font-size: var(--size-12);
font-weight: 500;
user-select: none;
cursor: pointer;
}
.segment-explorer-file-label:hover {
filter: brightness(1.05);
}
.segment-explorer-file-label--layout,
.segment-explorer-file-label--template,
.segment-explorer-file-label--default {
background-color: var(--color-gray-300);
color: var(--color-gray-1000);
}
.segment-explorer-file-label--page {
background-color: var(--color-blue-300);
color: var(--color-blue-900);
}
.segment-explorer-file-label--not-found,
.segment-explorer-file-label--forbidden,
.segment-explorer-file-label--unauthorized {
.segment-explorer-file-label--overridden {
background-color: var(--color-amber-300);
color: var(--color-amber-900);
}
.segment-explorer-file-label--loading {
background-color: var(--color-green-300);
color: var(--color-green-900);
.segment-explorer-file-label .code-icon {
opacity: 0;
margin-left: 0;
width: 0;
transition: all 0.15s ease-in-out;
}
.segment-explorer-file-label--error,
.segment-explorer-file-label--global-error {
background-color: var(--color-red-300);
color: var(--color-red-900);
.segment-explorer-file-label:hover .code-icon {
opacity: 1;
width: 12px;
margin-left: 4px;
}
.segment-explorer-file-label:hover {
filter: brightness(0.95);
}
.segment-explorer-file-label--builtin {
background-color: transparent;
color: var(--color-gray-900);
border: 1px dashed var(--color-gray-500);
height: 24px;
cursor: default;
}
.segment-explorer-file-label--builtin svg {
margin-left: 4px;
margin-right: -4px;
}
/* Footer styles */
.segment-explorer-footer {
padding: 8px;
border-top: 1px solid var(--color-gray-400);
background-color: var(--color-background-100);
user-select: none;
}
.segment-explorer-footer-button {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
width: 100%;
padding: 6px;
background: var(--color-background-100);
border: 1px solid var(--color-gray-400);
border-radius: 6px;
color: var(--color-gray-1000);
font-size: var(--size-14);
font-weight: 500;
cursor: pointer;
transition: background-color 0.15s ease;
}
.segment-explorer-footer-button:hover:not(:disabled) {
background: var(--color-gray-200);
}
.segment-explorer-footer-button--disabled {
opacity: 0.5;
cursor: not-allowed;
}
.segment-explorer-footer-text {
text-align: center;
}
.segment-explorer-footer-badge {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 20px;
height: 20px;
padding: 0 6px;
background: var(--color-amber-300);
color: var(--color-amber-900);
border-radius: 10px;
font-size: var(--size-12);
font-weight: 600;
line-height: 1;
}
.segment-explorer-file-label-tooltip--sm {
white-space: nowrap;
}
.segment-explorer-file-label-tooltip--lg {
min-width: 200px;
}
......@@ -28,6 +28,7 @@ import type {
import { DEFAULT_SEGMENT_KEY } from '../../shared/lib/segment'
import {
BOUNDARY_PREFIX,
BOUNDARY_SUFFIX,
getConventionPathByType,
} from './segment-explorer-path'
......@@ -565,7 +566,7 @@ async function createComponentTreeInternal({
// Add a suffix to avoid conflict with the segment view node representing rendered file.
// existence: not-found.tsx@boundary
// rendered: not-found.tsx
const fileNameSuffix = '@boundary'
const fileNameSuffix = BOUNDARY_SUFFIX
const segmentViewBoundaries = isSegmentViewEnabled ? (
<>
{notFoundFilePath && (
......
import Link from 'next/link'
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<div>
<h2>Layout - /no-layout/framework/blog</h2>
{children}
<Link href="/no-layout/framework">To /no-layout/framework</Link>
</div>
)
}
export default function NotFound() {
return <div>Not Found - /no-layout/framework/blog/not-found</div>
}
export default function Page() {
return <div>Page - /no-layout/framework/blog</div>
}
import Link from 'next/link'
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<div>
<h1>Layout - /no-layout/framework</h1>
{children}
<Link href="/no-layout">To /no-layout</Link>
</div>
)
}
export default function NotFound() {
return <div>Not Found - /no-layout</div>
}
'use client'
export default function Error() {
return <div>Error @bar</div>
}
......@@ -206,4 +206,18 @@ describe('segment-explorer', () => {
default.tsx"
`)
})
it('should display boundary selector when a segment has only boundary files', async () => {
const browser = await next.browser('/no-layout/framework/blog')
expect(await getSegmentExplorerContent(browser)).toMatchInlineSnapshot(`
"app/
layout.tsx
no-layout/
framework/
layout.tsx
blog/
layout.tsx
page.tsx"
`)
})
})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment