Repository navigation
fix: file preview width too narrow - #8303
Conversation
| background: var(--mk-primary); | ||
| } | ||
| } | ||
| </style> |
There was a problem hiding this comment.
Here's a review of the patch.
Bugs / irregularities
-
&::afterselector is corrupted —[IP]ter.
In the SCSS block the pseudo-element is written as&[IP]ter(and in the hover rules). This is invalid and the resize line will never render. It should be:&::after { ... } &:hover::after, .resizing &::after { background: var(--mk-primary); }
The
.resizing &::afterrule also requires an ancestor with.resizing, butright-resizingclass is applied to the<aside>, not the wrapper.mk-conversation-side-panel__inner. Verify the selector really matches; otherwise use.mk-conversation-side-panel.resizing .mk-conversation-resize-handle::after. -
@containeradded on the layout root, but no consumer. You referencecqwin the docs forrightWidth, but nothing declares a container query context name nor usescqwin this file. Either document how--mk-chat-right-widthconsumes it, or drop@containerhere (the class only establishes a container if something queries it). -
pointermoveon the handle without pointer capture flow verification.setPointerCaptureis called instartRightResize, sopointermove/pointerupwill fire on the handle element even outside it — good. But ifevent.currentTargetis typed loosely, guard against null. Also consider handlingpointerleaveonly when not captured (currently you rely solely on capture — fine, but note it). -
endRightResizeis attached to bothpointercancelandlostpointercapture— that's redundant but harmless; it just sets a boolean twice. -
No cleanup of capture on unmount. If the component unmounts mid-drag, the boolean stays true and the
select-noneclass relies on state that's gone. Minor, but aonBeforeUnmount(() => rightResizing.value = false)is cheap insurance. -
rightWidthStylecan returnundefined. WhenrightWidthisundefined, the computed returnsundefined, producing'--mk-chat-right-width': undefined. Confirm the CSS has a fallback/default, otherwise the variable may be set to empty unexpectedly. Prefer:const rightWidthStyle = computed(() => typeof props.rightWidth === 'number' ? `${props.rightWidth}px` : props.rightWidth ?? undefined)
-
layoutRefwithuseTemplateRef<HTMLElement>('layoutRef')— the generic should match the ref'd element;HTMLElementis fine for a<div>, just make sure the Vue version supportsuseTemplateRef(Vue 3.5+). If you're on <3.5, this breaks the build. -
emittype signature:'right-resize-reset': []is correct, but in the template you callemit('right-resize-reset')— fine. However the mask still uses$emitwhile others useemit; consistent enough but worth standardizing.
Potential issues
- Emitting raw pixel width without clamping here is intentional (outer layer clamps), but the outer must also handle a zero/negative value when the pointer passes the right edge (
rect.right - clientXcan go negative). Note this in the contract or clamp defensively. pointer-events-noneon the slot wrapper during resize prevents accidental iframe/text interaction — good, but users can't scroll the panel while dragging. Acceptable, just a UX note.getBoundingClientRect()on everypointermovecauses layout read each move. Pointer events can fire at high frequency; consider throttling viarequestAnimationFrame, or cacherect.right/rect.widthat drag start (only stale if the window resizes mid-drag, which is rare). This is the main perf optimization.rightResizablecombined withrightMode === 'push'only shows the handle in push mode. If drawer mode should also be resizable, the condition excludes it — verify that's intended.- Teleported drawer slot content also receives a nested
pointer-events-nonewrapper — same caveat as above.
Optimization suggestions
- Fix the
[IP]tercorruption first (functional bug). - Cache the layout rect at
pointerdown; recompute lazily (e.g., onresize) instead of every move. - Optionally rAF-throttle
emit('right-resize', ...)to reduce downstream re-renders. - Add
touch-action: noneon.mk-conversation-resize-handleso touch pointers don't scroll while resizing. - Consider
user-select: nonedirectly on the handle during drag rather than on the whole layout (select-noneon root is broad). - Standardize emit usage (
emit(...)everywhere vs$emit(...)) and add explicit default forrightResizableinwithDefaultsif it isn'tfalseby convention.
|
|
||
| export const RIGHT_SIDEBAR_KEY: InjectionKey<RightSidebarStore> = Symbol('right-sidebar') | ||
|
|
||
| export function useRightSidebarStore(): RightSidebarStore { |
There was a problem hiding this comment.
Code Review: Right Sidebar Store Changes
Overall Assessment
The changes are generally well-structured, but there are several issues worth addressing.
Issues & Potential Bugs
1. rightWidth returns mixed types (number | string) — Type inconsistency
const rightWidth = computed(() => {
if (!rightResizable.value) return RIGHT_SIDEBAR_WIDTH // number: 420
...
return `clamp(...)` // string
})The return type is number | string. Callers must handle both. Consider always returning a CSS string (e.g., '420px') for consistency, or documenting the union clearly.
2. readFilePreviewWidth misinterprets null in localStorage
const width = Number(localStorage.getItem(FILE_PREVIEW_WIDTH_STORAGE_KEY))
return width >= FILE_PREVIEW_MIN_WIDTH ? width : nulllocalStorage.getItemreturnsnullwhen unset →Number(null) === 0, so it's treated as invalid (fine).- But storing an empty string
""also becomes0(fine). - More importantly,
NaNfrom non-numeric storage → comparison isfalse→ returnsnull. OK, but fragile. Prefer:
const raw = localStorage.getItem(KEY)
if (raw == null) return null
const width = Number(raw)
return Number.isFinite(width) && width >= FILE_PREVIEW_MIN_WIDTH ? width : null3. bindFilePreviewLeftSide won't restore left sidebar if pushMode changes between open/close
Consider this sequence:
pushMode = true, preview opens →collapsedByPreview = true, left closes.- User toggles
pushModetofalsewhile preview is open. - Preview closes → watch fires but
pushModeisfalse, so enters the!toValue(pushMode)branch and resetscollapsedByPreview = falsewithout restoring the left sidebar.
The left sidebar stays collapsed unexpectedly. You likely want logic that still restores when not in push mode, or at least document this behavior.
4. watch(previewOpen, ...) lacks { immediate: true } — probably intentional
Since previewOpen starts false, no issue. But be aware if initial state ever changes.
5. resizeRight has an edge case when layoutWidth is 0 or invalid
const maxWidth = Math.max(FILE_PREVIEW_MIN_WIDTH, layoutWidth - CONVERSATION_MIN_WIDTH)If layoutWidth < CONVERSATION_MIN_WIDTH, maxWidth becomes 420, then Math.min(Math.max(width, 420), 420) = 420. That works but silently forces 420 even when conversation area can't hold it. Acceptable given the comment, but the writeFilePreviewWidth call will still persist that value, potentially overriding a legitimate larger remembered value with 420 on a transient/incorrect layout read. Consider skipping the persist if layoutWidth is suspiciously small.
6. Infinite loop risk between the two watchers
watch(previewOpen, (open) => { if (open && leftSideOpen.value) { ... leftSideOpen.value = false } })
watch(leftSideOpen, (open) => { if (!open || !previewOpen.value) return; ... closeRightSide() })Trace: preview opens → leftSideOpen = false → second watcher fires (open=false) → returns early. OK.
But consider: preview open + user sets leftSideOpen = true → second watcher fires → closeRightSide() → first watcher sees open=false, collapsedByPreview was set false just before, so no restore. Safe, but tightly coupled — easier to reason about with a single combined function or explicit state machine. Recommend adding a comment explaining why the ordering of collapsedByPreview = false before closeRightSide() matters.
7. cqw unit requires container query context
FILE_PREVIEW_DEFAULT_WIDTH = 'clamp(420px, 50cqw, 960px)' and 100cqw in rightWidth assume the component is inside a container query context. If container-type: inline-size isn't set on an ancestor, cqw resolves against the viewport (or falls back). This should be verified / documented.
8. RESET behavior doesn't re-clamp against current layout
resetRightWidth sets filePreviewWidth = null, which uses the default clamp(420px, 50cqw, 960px). Fine. But note: after reset, the effective width may exceed 100cqw - 360px on narrow screens in the default expression (since default clamp caps at 960px but not at 100cqw - 360px). Inconsistent clamping vs. the remembered-width branch. Consider unifying:
return filePreviewWidth.value == null
? `clamp(${MIN}px, min(50cqw, calc(100cqw - ${CONVERSATION_MIN_WIDTH}px)), 960px)`
: ...9. Minor: typo risk in comments — Chinese comments mention "可拖动" etc.; ensure team reads them. Not a bug.
10. No cleanup on unmount
createRightSidebarStore creates refs and (in bindFilePreviewLeftSide) watchers. If bindFilePreviewLeftSide is called inside a component setup, watchers auto-dispose. But if called outside a reactive effect scope, they leak. Confirm it's always invoked during setup or wrap in effectScope.
Optimization Suggestions
| Suggestion | Benefit |
|---|---|
Always return CSS-string rightWidth |
Simpler consumer code |
Use a STORAGE_KEY constant shared with tests |
Avoid magic strings |
Debounce writeFilePreviewWidth during drag |
Avoid excessive localStorage.setItem calls (storage API is synchronous) |
Use Number.isFinite guard in readFilePreviewWidth |
Robustness |
Combine two watchers into a single watch([previewOpen, leftSideOpen], ...) with clearer state transitions |
Easier reasoning |
Add explicit type: const filePreviewWidth = ref<number | null>(readFilePreviewWidth()) |
TS strict inference |
Export constants (RIGHT_SIDEBAR_WIDTH, etc.) for reuse/testing |
Testability |
Style Notes
- Consider extracting inline Chinese comments into English or maintain bilingual docs if this is a shared repo (review request is in English).
- The
@ -1,8 +1,8 @@diff header hints at a truncated diff; ensure the full file compiles (importstoValueandwatchare used only in the new helper — good).
Summary
Functional logic is sound, but I recommend: (1) fix the pushMode toggle edge case in bindFilePreviewLeftSide, (2) harden readFilePreviewWidth with Number.isFinite, (3) unify clamp behavior between default and remembered widths, and (4) debounce persistence writes during drag.
| @right-resize-reset="bundle.rightSidebar.resetRightWidth" | ||
| > | ||
| <template #left><ConversationList /></template> | ||
| <template #main><ChatPanel /></template> |
There was a problem hiding this comment.
Review of the diff:
1. Potential circular/tight coupling
bindFilePreviewLeftSide(bundle.rightSidebar, bundle.list.leftSideOpen, ...) creates a direct temporal dependency: the file preview state must be bound after both bundle.rightSidebar and bundle.list already exist. If initialization order changes (e.g. lazy init, or a refactor of the bundle factory), this silently breaks without a compile error. Consider having the binding logic live inside the bundle factory / right-sidebar module itself instead of the layout component.
2. Reactivity in the predicate
The third argument () => leftMode.value === 'push' is passed as a getter. Confirm the internal implementation calls it reactively (inside a computed/watchEffect) and not just once at bind time—otherwise "push vs drawer" switches won't re-evaluate, causing a stale squeeze behavior on device resize / orientation change.
3. Missing cleanup / unbind
There's no corresponding unbindFilePreviewLeftSide (or onUnmounted cleanup) shown. If the layout can mount/unmount multiple times (HMR, route switching, tests), the binding may leak or double-register. Verify idempotency or add cleanup.
4. Manual .value unwrapping in template
:left-open="bundle.list.leftSideOpen.value"
This forces Vue to touch a ref inside the render function rather than letting auto-unwrapping handle it, and is inconsistent with idiomatic usage. If these are plain refs, passing them in a way that preserves reactivity (e.g. toRef-based getters or keeping them reactive properties) is cleaner and avoids accidental non-reactive copies if someone later wraps them.
5. Event naming consistency
@right-resize and @right-resize-reset are custom events emitted by ConversationLayout; make sure they're declared via defineEmits in the child (and that resizeRight/resetRightWidth signatures match any payload the child emits, e.g. a pixel width). Passing the handler directly as bundle.rightSidebar.resizeRight relies on the method being pre-bound (no this); verify it doesn't depend on its binding context.
6. Width state ownership duplication
rightWidth is now read from bundle.rightSidebar and also presumably mutated via resizeRight. Ensure single source of truth — the resize handler should update the same ref that's fed into :right-width, and that clamping/bounds logic lives in one place (not split between layout and sidebar).
7. Minor style suggestion
Add an explicit return type / guard for the leftMode computed ('push' | 'drawer'), and document why push/drawer corresponds to desktop/mobile, since the inject comment ("左栏为抽屉即手机端") is in Chinese while the rest of the codebase comments appear mixed—consider standardizing.
No functional bugs are evident from the diff itself, but items 1–3 (binding lifecycle/reactivity/cleanup) are the highest-risk areas to verify.
fix: file preview width too narrow