All files / src/components BaseFormSidebar.vue

99.04% Statements 104/105
97.33% Branches 73/75
100% Functions 24/24
100% Lines 91/91

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484  1679x                                                   23x                     23x         23x                                                   269x       1694x                   7x 3x                     1247x   1247x                                                                       1247x               1247x 1247x     11x 10x       1247x 1247x             23x   13x 23x 23x 13x         423x 423x 423x 423x 423x         1247x       2x 1x 1x   1247x   1247x     18x 16x             23x 23x 23x   1247x 1247x 1247x     225x       214x 214x 204x 204x 214x     1x         11x 11x 10x 10x 7x             9x 9x       4x       5x   5x 5x       1611x 5x 5x 5x 5x 5x 5x       6x 5x 5x   5x 5x 5x 5x       2x 2x         6x 6x 4x 4x 4x 2x 1x 1x           1247x 1408x   1408x 1194x         1247x 413x 413x   413x                                                                                                                                                                                                                                                                                                                                                                        
<template>
  <Teleport to="body">
    <Transition name="sidebar">
      <!-- Clicking the backdrop intentionally does nothing: an accidental click
           outside the panel must not discard what the user typed in the form. -->
      <div v-if="isOpen" class="sidebar-overlay">
        <div
          ref="panelRef"
          class="sidebar-panel"
          :class="{ resizing }"
          :style="{ width: customWidth ? `${customWidth}px` : panelWidth }"
        >
          <!-- Left border handle: desktop only (hidden by CSS on small screens) -->
          <div
            class="sidebar-resize-handle"
            role="separator"
            aria-orientation="vertical"
            tabindex="0"
            :aria-label="t('common.resizePanel')"
            :title="t('common.resizePanel')"
            @pointerdown="startResize"
            @dblclick="resetWidth"
            @keydown="handleResizeKey"
          >
            <span class="sidebar-resize-grip" aria-hidden="true" />
          </div>
          <!-- Header -->
          <div class="sidebar-header">
            <h3>
              <font-awesome-icon v-if="icon" :icon="icon" class="me-2" />
              {{ title }}
            </h3>
            <button type="button" class="btn-close" aria-label="Close" @click="handleClose" />
          </div>
 
          <!-- Body + Footer wrapped in <form> so type="submit" triggers native HTML5 validation -->
          <form class="sidebar-form" @submit.prevent="handleSubmit">
            <!-- Body -->
            <div class="sidebar-body">
              <slot />
            </div>
 
            <!-- Footer -->
            <div class="sidebar-footer">
              <slot name="footer">
                <button
                  type="button"
                  class="btn btn-secondary"
                  :disabled="loading"
                  @click="handleClose"
                >
                  <font-awesome-icon icon="fa-solid fa-times" class="me-1" />
                  {{ cancelLabel }}
                </button>
                <button
                  type="submit"
                  class="btn"
                  :class="submitButtonClass"
                  :disabled="loading || submitDisabled"
                >
                  <span v-if="loading">
                    <span class="spinner-border spinner-border-sm me-2" />
                    {{ loadingLabel }}
                  </span>
                  <span v-else>
                    <font-awesome-icon v-if="submitIcon" :icon="submitIcon" class="me-1" />
                    {{ submitLabel }}
                  </span>
                </button>
              </slot>
            </div>
          </form>
        </div>
      </div>
    </Transition>
    <!-- Asked before dropping unsaved changes, over the panel: only while asking -->
    <ConfirmModal
      v-if="discardAsked"
      :is-open="true"
      :title="t('common.unsavedTitle')"
      :message="t('common.unsavedMessage')"
      :confirm-label="t('common.discardChanges')"
      variant="warning"
      @confirm="answerDiscard(true)"
      @cancel="answerDiscard(false)"
    />
  </Teleport>
</template>
 
<script setup lang="ts">
import { inject, onUnmounted, ref, watch } from 'vue'
import { matchedRouteKey, onBeforeRouteLeave } from 'vue-router'
import ConfirmModal from '@/components/ConfirmModal.vue'
import { useUILanguage } from '@/composables/useUILanguage'
 
const { t } = useUILanguage()
 
const props = withDefaults(
  defineProps<{
    isOpen: boolean
    title: string
    icon?: string
    panelWidth?: string
    /** Where the width the user dragged to is kept (localStorage); not kept when omitted */
    storageKey?: string
    loading?: boolean
    submitDisabled?: boolean
    submitLabel?: string
    submitIcon?: string
    submitButtonClass?: string
    cancelLabel?: string
    loadingLabel?: string
    /**
     * The form has unsaved changes (see composables/useUnsavedChanges.ts):
     * closing it, leaving the page or the tab asks first
     */
    dirty?: boolean
  }>(),
  {
    icon: undefined,
    panelWidth: '1400px',
    storageKey: undefined,
    loading: false,
    submitDisabled: false,
    submitLabel: undefined,
    submitIcon: undefined,
    submitButtonClass: 'btn-success',
    cancelLabel: undefined,
    loadingLabel: undefined,
    dirty: false
  }
)
 
const emit = defineEmits<{
  close: []
  submit: []
  /** The user chose to drop the unsaved changes */
  discard: []
}>()
 
// Use computed to provide fallback values for labels
const cancelLabel = props.cancelLabel || t('common.cancel')
const loadingLabel = props.loadingLabel || t('common.saving')
 
async function handleClose() {
  if (props.loading) return
  if (await confirmDiscard()) emit('close')
}
 
// --- Unsaved changes -------------------------------------------------------
const discardAsked = ref(false)
let discardAnswer: ((discard: boolean) => void) | null = null
 
/**
 * Asks before dropping unsaved changes; resolves true when there are none
 * left to lose. A promise, so that a route guard waits for the answer.
 */
function confirmDiscard(): Promise<boolean> {
  if (!props.isOpen || !props.dirty) return Promise.resolve(true)
  // Asked again while asking (a second navigation): the first question is dropped
  discardAnswer?.(false)
  discardAsked.value = true
  return new Promise((resolve) => {
    discardAnswer = resolve
  })
}
 
function answerDiscard(discard: boolean) {
  discardAsked.value = false
  if (discard) emit('discard')
  const answer = discardAnswer
  discardAnswer = null
  answer?.(discard)
}
 
// Leaving the page asks too, when the sidebar is shown by a route (not in a
// component test without a router)
if (inject(matchedRouteKey, null)) onBeforeRouteLeave(() => confirmDiscard())
 
// Closing or reloading the tab: only the browser may ask then
function warnBeforeUnload(event: BeforeUnloadEvent) {
  if (!props.isOpen || !props.dirty) return
  event.preventDefault()
  event.returnValue = ''
}
window.addEventListener('beforeunload', warnBeforeUnload)
 
defineExpose({ confirmDiscard })
 
function handleSubmit() {
  if (!props.loading && !props.submitDisabled) {
    emit('submit')
  }
}
 
// --- Resizable width -------------------------------------------------------
// The CSS max-width (84vw) still caps the panel, so a width saved on a large
// screen never overflows a smaller one; small screens force 100vw anyway.
const MIN_WIDTH = 360
const KEY_STEP = 32
const STORAGE_PREFIX = 'sidebarWidth:'
 
const panelRef = ref<HTMLElement | null>(null)
const customWidth = ref<number | null>(null)
const resizing = ref(false)
 
function storageKeyFull(): string | null {
  return props.storageKey ? STORAGE_PREFIX + props.storageKey : null
}
 
function loadWidth() {
  const key = storageKeyFull()
  if (!key) return
  try {
    const saved = parseInt(localStorage.getItem(key) ?? '', 10)
    customWidth.value = Number.isFinite(saved) && saved >= MIN_WIDTH ? saved : null
  } catch {
    // Storage unavailable (private mode): fall back to the default width
    customWidth.value = null
  }
}
 
function saveWidth() {
  const key = storageKeyFull()
  if (!key) return
  try {
    if (customWidth.value === null) localStorage.removeItem(key)
    else localStorage.setItem(key, String(customWidth.value))
  } catch {
    // Storage unavailable: the width only lasts until the panel closes
  }
}
 
function clampWidth(width: number): number {
  const max = Math.floor(window.innerWidth * 0.84)
  return Math.round(Math.max(MIN_WIDTH, Math.min(width, max)))
}
 
function currentWidth(): number {
  return customWidth.value ?? panelRef.value?.getBoundingClientRect().width ?? MIN_WIDTH
}
 
function onPointerMove(event: PointerEvent) {
  Iif (!panelRef.value) return
  // The panel is anchored to the right edge: its width is right edge - pointer
  const right = panelRef.value.getBoundingClientRect().right
  customWidth.value = clampWidth(right - event.clientX)
}
 
function stopResize() {
  if (!resizing.value) return
  resizing.value = false
  document.body.classList.remove('sidebar-resizing')
  window.removeEventListener('pointermove', onPointerMove)
  window.removeEventListener('pointerup', stopResize)
  window.removeEventListener('pointercancel', stopResize)
  saveWidth()
}
 
function startResize(event: PointerEvent) {
  if (event.button !== 0) return
  event.preventDefault()
  resizing.value = true
  // Listen on window: the pointer leaves the thin handle as soon as it moves
  document.body.classList.add('sidebar-resizing')
  window.addEventListener('pointermove', onPointerMove)
  window.addEventListener('pointerup', stopResize)
  window.addEventListener('pointercancel', stopResize)
}
 
function resetWidth() {
  customWidth.value = null
  saveWidth()
}
 
function handleResizeKey(event: KeyboardEvent) {
  // The handle is on the left edge: ArrowLeft widens, ArrowRight narrows
  const deltas: Record<string, number> = { ArrowLeft: KEY_STEP, ArrowRight: -KEY_STEP }
  if (event.key in deltas) {
    event.preventDefault()
    customWidth.value = clampWidth(currentWidth() + deltas[event.key])
    saveWidth()
  } else if (event.key === 'Home' || event.key === 'Escape') {
    event.preventDefault()
    resetWidth()
  }
}
 
// Re-read on every opening: another sidebar instance with the same key may
// have changed the width meanwhile.
watch(
  () => props.isOpen,
  (open) => {
    if (open) loadWidth()
    else stopResize()
  },
  { immediate: true }
)
 
onUnmounted(() => {
  stopResize()
  window.removeEventListener('beforeunload', warnBeforeUnload)
  // Unmounted while asking (a route left): the question has no answer
  answerDiscard(false)
})
</script>
 
<style scoped>
.sidebar-overlay {
  position: fixed;
  top: calc(74px + var(--bw-ribbons-height, 0px)); /* Header + ribbons banner on desktop */
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1050;
  display: flex;
  justify-content: flex-end;
}
 
.sidebar-panel {
  background: var(--bw-surface);
  color: var(--bw-text);
  max-width: 84vw;
  height: 100%;
  display: flex;
  flex-direction: column;
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.15);
  position: relative;
  /* Visible border that can be dragged; the grip and the highlight live in it */
  border-left: 4px solid var(--bw-border);
}
 
/* Grab zone: the 4px border plus 4px inside the panel, for easy grabbing.
   Absolute offsets start at the padding edge, so -4px is the border's left. */
.sidebar-resize-handle {
  position: absolute;
  top: 0;
  bottom: 0;
  left: -4px;
  width: 8px;
  cursor: col-resize;
  z-index: 1;
  touch-action: none;
}
 
/* Highlight: exactly covers the border */
.sidebar-resize-handle::after {
  content: '';
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  width: 4px;
  background: transparent;
  transition: background 0.15s;
}
 
.sidebar-resize-handle:hover::after,
.sidebar-resize-handle:focus-visible::after,
.sidebar-panel.resizing .sidebar-resize-handle::after {
  background: var(--bs-primary);
}
 
.sidebar-resize-handle:focus-visible {
  outline: none;
}
 
/* Discreet grip: three 2px dots centered inside the 4px border */
.sidebar-resize-grip {
  position: absolute;
  top: 50%;
  left: 1px;
  width: 2px;
  height: 14px;
  transform: translateY(-50%);
  color: var(--bw-main-content-bg);
  background: repeating-linear-gradient(to bottom, currentColor 0 2px, transparent 2px 6px);
  pointer-events: none;
  z-index: 1;
  transition: color 0.15s;
}
 
/* On the highlighted border, the dots turn to the surface color to stay visible */
.sidebar-resize-handle:hover .sidebar-resize-grip,
.sidebar-resize-handle:focus-visible .sidebar-resize-grip,
.sidebar-panel.resizing .sidebar-resize-grip {
  color: var(--bw-surface);
}
 
/* While dragging: no text selection and the resize cursor everywhere */
:global(body.sidebar-resizing) {
  user-select: none;
  cursor: col-resize;
}
 
.sidebar-header {
  padding: 1.5rem;
  border-bottom: 1px solid var(--bw-border);
  background: var(--bw-surface);
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-shrink: 0;
}
 
.sidebar-header h3 {
  margin: 0;
  font-size: 1.25rem;
  font-weight: 600;
}
 
.sidebar-body {
  flex: 1;
  overflow-y: auto;
  padding: 1.5rem;
  background: var(--bw-surface);
}
 
.sidebar-form {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}
 
.sidebar-footer {
  padding: 1rem 1.5rem;
  border-top: 1px solid var(--bw-border);
  background: var(--bw-surface-muted);
  display: flex;
  gap: 0.5rem;
  justify-content: flex-end;
  flex-shrink: 0;
}
 
/* Transitions */
.sidebar-enter-active,
.sidebar-leave-active {
  transition: all 0.3s ease;
}
 
.sidebar-enter-from,
.sidebar-leave-to {
  opacity: 0;
}
 
.sidebar-enter-from .sidebar-panel,
.sidebar-leave-to .sidebar-panel {
  transform: translateX(100%);
}
 
.sidebar-enter-active .sidebar-panel,
.sidebar-leave-active .sidebar-panel {
  transition: transform 0.3s ease;
}
 
/* Mobile */
@media (max-width: 767px) {
  .sidebar-overlay {
    top: calc(62px + var(--bw-ribbons-height, 0px)); /* Header + ribbons banner on mobile */
  }
 
  .sidebar-panel {
    width: 100vw !important;
    max-width: 100vw;
    border-left: none;
  }
 
  /* No resizing on small screens: the panel always takes the full width */
  .sidebar-resize-handle {
    display: none;
  }
 
  .sidebar-footer {
    flex-direction: column;
  }
 
  .sidebar-footer .btn {
    width: 100%;
  }
}
</style>