Skip to content

fix: file preview width too narrow - #8303

Merged
shaohuzhang1 merged 1 commit into
v3from
pr@v3@fix_file_preview
Dec 4, 2026
Merged

shaohuzhang1 merged 1 commit into
v3from
pr@v3@fix_file_preview

Conversation

@shaohuzhang1

Copy link
Copy Markdown
Contributor

fix: file preview width too narrow

background: var(--mk-primary);
}
}
</style>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here's a review of the patch.

Bugs / irregularities

  1. &::after selector 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 &::after rule also requires an ancestor with .resizing, but right-resizing class 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.

  2. @container added on the layout root, but no consumer. You reference cqw in the docs for rightWidth, but nothing declares a container query context name nor uses cqw in this file. Either document how --mk-chat-right-width consumes it, or drop @container here (the class only establishes a container if something queries it).

  3. pointermove on the handle without pointer capture flow verification. setPointerCapture is called in startRightResize, so pointermove/pointerup will fire on the handle element even outside it — good. But if event.currentTarget is typed loosely, guard against null. Also consider handling pointerleave only when not captured (currently you rely solely on capture — fine, but note it).

  4. endRightResize is attached to both pointercancel and lostpointercapture — that's redundant but harmless; it just sets a boolean twice.

  5. No cleanup of capture on unmount. If the component unmounts mid-drag, the boolean stays true and the select-none class relies on state that's gone. Minor, but a onBeforeUnmount(() => rightResizing.value = false) is cheap insurance.

  6. rightWidthStyle can return undefined. When rightWidth is undefined, the computed returns undefined, 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)
  7. layoutRef with useTemplateRef<HTMLElement>('layoutRef') — the generic should match the ref'd element; HTMLElement is fine for a <div>, just make sure the Vue version supports useTemplateRef (Vue 3.5+). If you're on <3.5, this breaks the build.

  8. emit type signature: 'right-resize-reset': [] is correct, but in the template you call emit('right-resize-reset') — fine. However the mask still uses $emit while others use emit; 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 - clientX can go negative). Note this in the contract or clamp defensively.
  • pointer-events-none on 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 every pointermove causes layout read each move. Pointer events can fire at high frequency; consider throttling via requestAnimationFrame, or cache rect.right/rect.width at drag start (only stale if the window resizes mid-drag, which is rare). This is the main perf optimization.
  • rightResizable combined with rightMode === '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-none wrapper — same caveat as above.

Optimization suggestions

  1. Fix the [IP]ter corruption first (functional bug).
  2. Cache the layout rect at pointerdown; recompute lazily (e.g., on resize) instead of every move.
  3. Optionally rAF-throttle emit('right-resize', ...) to reduce downstream re-renders.
  4. Add touch-action: none on .mk-conversation-resize-handle so touch pointers don't scroll while resizing.
  5. Consider user-select: none directly on the handle during drag rather than on the whole layout (select-none on root is broad).
  6. Standardize emit usage (emit(...) everywhere vs $emit(...)) and add explicit default for rightResizable in withDefaults if it isn't false by convention.

@shaohuzhang1
shaohuzhang1 merged commit 1c1ff72 into v3 Dec 4, 2026
3 of 4 checks passed
@shaohuzhang1
shaohuzhang1 deleted the pr@v3@fix_file_preview branch December 4, 2026 10:20

export const RIGHT_SIDEBAR_KEY: InjectionKey<RightSidebarStore> = Symbol('right-sidebar')

export function useRightSidebarStore(): RightSidebarStore {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 : null
  • localStorage.getItem returns null when unset → Number(null) === 0, so it's treated as invalid (fine).
  • But storing an empty string "" also becomes 0 (fine).
  • More importantly, NaN from non-numeric storage → comparison is false → returns null. 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 : null

3. bindFilePreviewLeftSide won't restore left sidebar if pushMode changes between open/close

Consider this sequence:

  1. pushMode = true, preview opens → collapsedByPreview = true, left closes.
  2. User toggles pushMode to false while preview is open.
  3. Preview closes → watch fires but pushMode is false, so enters the !toValue(pushMode) branch and resets collapsedByPreview = false without 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 (imports toValue and watch are 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>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant