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 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 | 146x 1x 4x 180x 1x 1x 1x 1x 4x 5x 1x 1x 11x 1x 1x 1x 5x 1x 1x 1x 1x 1x 1x 2x 2x 1x 323x 1x 5x 2x 1x 1x 4x 4631x 2x 274x 1x 1x 791x 2x 1x 1x 1x 1x 5x 1x 1740x 11x 180x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 33x 33x 74x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 37x 64x 59x 34x 36x 1x 34x 34x 34x 67x 50x 102x 50x 51x 63x 50x 50x 50x 34x 37x 3x 8x 8x 8x 7x 7x 7x 7x 34x 28x 12x 24x 23x 34x 48x 39x 34x 93x 47x 1x 34x 34x 34x 34x 4x 2x 2x 34x 41x 36x 36x 5x 2x 2x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 37x 37x 37x 37x 37x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 29x 29x 29x 29x 1x 1x 29x 34x 42x 42x 39x 42x 37x 29x 11x 11x 11x 11x 5x 5x 5x 11x 11x 34x 137x 7x 7x 7x 7x 7x 34x 7x 17x 7x 2x 2x 2x 2x 2x 3x 1x 15x 15x 15x 15x 12x 12x 28x 12x 12x 12x 15x 12x 12x 3x 3x 15x 4x 4x 1x 1x 4x 5x 4x 4x 4x 3x 3x 3x 3x 5x 1x 4x 34x 34x 34x 7x 3x 34x 140x 34x 61x 153x 153x 29x 29x 29x 34x 13x 34x 3x 9x 9x 9x 9x 34x 34x | <template>
<BaseFormSidebar
ref="baseSidebar"
:is-open="isOpen"
storage-key="space-page-form-sidebar"
:title="sidebarTitle"
icon="fa-solid fa-file-lines"
:loading="saving"
:submit-disabled="!canSave"
:dirty="dirty"
@close="emit('close')"
@discard="dirty = false"
@submit="save"
>
<LoadingSpinner v-if="loading" />
<EmptyState v-else-if="loadFailed" variant="info">{{ t('spacePages.notFound') }}</EmptyState>
<template v-else>
<div class="d-flex flex-wrap align-items-center gap-2 mb-3">
<template v-if="!creating">
<span v-if="published" class="badge bg-success">{{ t('spacePages.published') }}</span>
<span v-else class="badge bg-secondary">{{ t('spacePages.draftOnly') }}</span>
<span
v-if="published && (dirty || hasUnpublishedChanges)"
class="badge bg-warning text-dark"
data-testid="page-editor-unpublished"
>
{{ t('spacePages.unpublishedChanges') }}
</span>
<button
v-if="published"
type="button"
class="btn btn-sm btn-link"
:disabled="saving"
data-testid="page-editor-unpublish"
@click="unpublish"
>
{{ t('spacePages.unpublish') }}
</button>
</template>
<div class="ms-auto d-flex flex-wrap align-items-center gap-2">
<EditingLanguageSelector
v-if="languages.length > 1"
v-model="lang"
:languages="languages"
data-testid="page-editor-languages"
/>
<button
type="button"
class="btn btn-sm btn-outline-secondary"
:aria-pressed="previewing"
data-testid="page-editor-preview"
@click="previewing = !previewing"
>
<font-awesome-icon
:icon="previewing ? 'fa-solid fa-pen' : 'fa-solid fa-eye'"
class="me-1"
/>
{{ previewing ? t('spacePages.edit') : t('spacePages.preview') }}
</button>
</div>
</div>
<!-- Preview in the flow's look -->
<div
v-if="previewing"
class="border rounded overflow-hidden"
data-testid="page-editor-preview-frame"
>
<SpaceLayout
:space="previewSpace"
:compact="slug !== HOME_SLUG"
:current-page-slug="slug"
preview
>
<h1 v-if="slug !== HOME_SLUG" class="h2 fw-bold mb-4">{{ title[lang] }}</h1>
<SpaceBlocks
:blocks="previewBlocks"
:slug="flowSlug"
:lang="lang"
:fallback-lang="defaultLanguage"
:join-open="!!flow?.space?.join"
/>
</SpaceLayout>
</div>
<template v-else>
<div class="card card-body mb-3" data-testid="page-editor-settings">
<div class="row g-3">
<div class="col-md-6">
<label for="page-title" class="form-label small">
{{ t('spacePages.fields.pageTitle') }} ({{ lang.toUpperCase() }})
</label>
<input
id="page-title"
:value="title[lang] || ''"
type="text"
class="form-control"
maxlength="120"
@input="setTitle(($event.target as HTMLInputElement).value)"
/>
</div>
<div class="col-md-6">
<label for="page-slug" class="form-label small">{{ t('spacePages.slug') }}</label>
<div class="input-group has-validation">
<span class="input-group-text small">/space/{{ flowSlug }}/</span>
<input
id="page-slug"
v-model="slug"
type="text"
class="form-control"
:class="{ 'is-invalid': slug !== '' && slugError }"
maxlength="50"
:readonly="isHome"
@input="onSlugInput"
/>
<div v-if="slugTaken" class="invalid-feedback" data-testid="page-slug-taken">
{{ t('spacePages.slugTaken') }}
</div>
</div>
<!-- The space always has its home page: it keeps its address -->
<div class="form-text" data-testid="page-slug-hint">
{{ isHome ? t('spacePages.homePageKept') : t('spacePages.homeHint') }}
</div>
</div>
<div class="col-md-6">
<label for="page-visibility" class="form-label small">{{
t('spacePages.visibility')
}}</label>
<select
id="page-visibility"
v-model="visibility"
class="form-select"
@change="dirty = true"
>
<option value="everyone">{{ t('spacePages.everyone') }}</option>
<option value="members">{{ t('spacePages.membersOnly') }}</option>
</select>
</div>
</div>
</div>
<!-- The page in the space menu: shown or not, its place, its icon (UC-SPACE-015.1) -->
<div class="card card-body mb-3" data-testid="page-editor-menu">
<div class="form-check form-switch mb-0">
<input
id="page-in-menu"
v-model="showInMenu"
class="form-check-input"
type="checkbox"
role="switch"
@change="dirty = true"
/>
<label class="form-check-label" for="page-in-menu">{{
t('spacePages.showInMenu')
}}</label>
</div>
<div v-if="showInMenu" class="row g-3 mt-1">
<div class="col-lg-6">
<span id="page-menu-place-label" class="form-label small d-block">{{
t('spacePages.menuPlace')
}}</span>
<draggable
:model-value="menuEntries"
item-key="key"
handle=".page-menu-handle"
tag="ol"
class="list-group page-menu-list"
aria-labelledby="page-menu-place-label"
data-testid="page-menu-order"
@update:model-value="setMenuEntries"
>
<template #item="{ element, index }">
<li
class="list-group-item d-flex align-items-center gap-2 py-1"
:class="{ 'page-menu-current': element.current }"
:data-testid="`page-menu-entry-${element.key}`"
>
<span class="page-menu-handle text-muted" :title="t('spacePages.dragToPlace')">
<font-awesome-icon icon="fa-solid fa-grip-vertical" />
</span>
<PageIcon :name="element.current ? currentIcon : element.icon" fixed-width />
<span
class="flex-grow-1 text-truncate"
:class="{ 'fw-semibold': element.current }"
>
{{ element.current ? pageTitle || slug : element.title }}
</span>
<template v-if="element.current">
<span class="badge bg-primary">{{ t('spacePages.thisPage') }}</span>
<button
type="button"
class="btn btn-sm btn-outline-secondary py-0"
:title="t('spacePages.moveUp')"
:aria-label="t('spacePages.moveUp')"
:disabled="index === 0"
data-testid="page-menu-up"
@click="moveInMenu(index, -1)"
>
<font-awesome-icon icon="fa-solid fa-arrow-up" />
</button>
<button
type="button"
class="btn btn-sm btn-outline-secondary py-0"
:title="t('spacePages.moveDown')"
:aria-label="t('spacePages.moveDown')"
:disabled="index === menuEntries.length - 1"
data-testid="page-menu-down"
@click="moveInMenu(index, 1)"
>
<font-awesome-icon icon="fa-solid fa-arrow-down" />
</button>
</template>
</li>
</template>
</draggable>
<div class="form-text">{{ t('spacePages.menuPlaceHint') }}</div>
</div>
<div class="col-lg-6">
<span id="page-icon-label" class="form-label small d-block">{{
t('spacePages.icon')
}}</span>
<!-- Any Font Awesome solid icon: the suggested ones until a search -->
<input
v-model="iconQuery"
type="search"
class="form-control form-control-sm mb-2"
:placeholder="t('spacePages.iconSearch')"
:aria-label="t('spacePages.iconSearch')"
data-testid="page-icon-search"
/>
<div
class="d-flex flex-wrap gap-1"
role="radiogroup"
aria-labelledby="page-icon-label"
data-testid="page-icon-picker"
>
<button
v-for="name in iconChoices"
:key="name"
type="button"
class="btn btn-sm page-icon-choice"
:class="currentIcon === name ? 'btn-primary' : 'btn-outline-secondary'"
role="radio"
:aria-checked="currentIcon === name"
:aria-label="name"
:title="name"
:data-testid="`page-icon-${name}`"
@click="chooseIcon(name)"
>
<PageIcon :name="name" fixed-width />
</button>
</div>
<div
v-if="iconQuery.trim() && iconIndexLoaded && iconChoices.length === 0"
class="form-text"
data-testid="page-icon-no-match"
>
{{ t('spacePages.iconNoMatch') }}
</div>
</div>
</div>
</div>
<div
v-for="(block, index) in blocks"
:key="block.id"
class="card mb-3"
:data-testid="`page-block-${index}`"
>
<div class="card-header d-flex align-items-center gap-1 py-1">
<span class="fw-semibold small me-auto">{{
t(`spacePages.blocks.${block.type}`)
}}</span>
<!-- How the block's content is aligned (UC-SPACE-023.1) -->
<div
v-if="BLOCK_ALIGNS[block.type]"
class="btn-group btn-group-sm me-2"
role="group"
:aria-label="t('spacePages.align')"
:data-testid="`page-block-align-${index}`"
>
<button
v-for="align in BLOCK_ALIGNS[block.type]!.aligns"
:key="align"
type="button"
class="btn btn-outline-secondary"
:class="{ active: blockAlign(block) === align }"
:aria-pressed="blockAlign(block) === align"
:title="t(ALIGN_LABELS[align])"
:aria-label="t(ALIGN_LABELS[align])"
:data-testid="`page-block-align-${index}-${align}`"
@click="updateBlock(index, { ...block, align })"
>
<font-awesome-icon :icon="`fa-solid fa-align-${align}`" />
</button>
</div>
<button
type="button"
class="btn btn-sm btn-outline-secondary"
:title="t('spacePages.moveUp')"
:disabled="index === 0"
:data-testid="`page-block-up-${index}`"
@click="move(index, -1)"
>
<font-awesome-icon icon="fa-solid fa-arrow-up" />
</button>
<button
type="button"
class="btn btn-sm btn-outline-secondary"
:title="t('spacePages.moveDown')"
:disabled="index === blocks.length - 1"
:data-testid="`page-block-down-${index}`"
@click="move(index, 1)"
>
<font-awesome-icon icon="fa-solid fa-arrow-down" />
</button>
<button
type="button"
class="btn btn-sm btn-outline-danger"
:title="t('spacePages.removeBlock')"
:data-testid="`page-block-remove-${index}`"
@click="removeBlock(index)"
>
<font-awesome-icon icon="fa-solid fa-trash" />
</button>
</div>
<div class="card-body">
<SpaceBlockEditor
:block="block"
:lang="lang"
:flow-id="flowId"
:page-slugs="pageSlugs"
@update="updateBlock(index, $event)"
/>
</div>
</div>
<div class="d-flex flex-wrap gap-2 align-items-center" data-testid="page-editor-add-block">
<span class="small text-muted">{{ t('spacePages.addBlock') }}</span>
<button
v-for="type in BLOCK_TYPES"
:key="type"
type="button"
class="btn btn-sm btn-outline-primary"
:disabled="blocks.length >= 40 || (DATA_BLOCK_TYPES.includes(type) && dataBlocksFull)"
:data-testid="`page-add-${type}`"
@click="addBlock(type)"
>
<font-awesome-icon icon="fa-solid fa-plus" class="me-1" />{{
t(`spacePages.blocks.${type}`)
}}
</button>
</div>
</template>
</template>
<template #footer>
<button
type="button"
class="btn btn-secondary"
:disabled="saving"
data-testid="page-editor-close"
@click="handleClose"
>
<font-awesome-icon icon="fa-solid fa-times" class="me-1" />
{{ t('common.cancel') }}
</button>
<button
type="submit"
class="btn"
:class="creating ? 'btn-success' : 'btn-primary'"
:disabled="!canSave || saving"
data-testid="page-editor-save"
>
<span v-if="saving" class="spinner-border spinner-border-sm me-2" />
<font-awesome-icon
v-else
:icon="creating ? 'fa-solid fa-plus' : 'fa-solid fa-floppy-disk'"
class="me-1"
/>
{{ creating ? t('spacePages.create') : t('spacePages.saveDraft') }}
</button>
<button
v-if="!creating"
type="button"
class="btn btn-success"
:disabled="!canSave || saving || (!dirty && !hasUnpublishedChanges)"
data-testid="page-editor-publish"
@click="publish"
>
<font-awesome-icon icon="fa-solid fa-globe" class="me-1" />
{{ t('spacePages.publish') }}
</button>
</template>
</BaseFormSidebar>
</template>
<script setup lang="ts">
// @implements UC-SPACE-009.1, UC-SPACE-011.1, UC-SPACE-012.1, UC-SPACE-015.1
/**
* The create / edit sidebar of a space page: its title, address and settings,
* its blocks in each flow language, a preview in the flow's look. Saving keeps
* a draft, publishing makes the saved draft what visitors see. The preview
* shows the items of the data blocks as last saved: a changed data block shows
* them again once saved.
*
* `pageSlug` null opens it on a new page; once created, the parent passes the
* new page's slug and the sidebar goes on editing it without reloading it.
*/
import { computed, reactive, ref, watch } from 'vue'
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
import draggable from 'vuedraggable'
import BaseFormSidebar from '@/components/BaseFormSidebar.vue'
import EmptyState from '@/components/EmptyState.vue'
import LoadingSpinner from '@/components/LoadingSpinner.vue'
import SpaceLayout, { type PublicSpace } from '@/components/SpaceLayout.vue'
import SpaceBlocks from '@/components/SpaceBlocks.vue'
import SpaceBlockEditor from '@/components/SpaceBlockEditor.vue'
import PageIcon from '@/components/PageIcon.vue'
import EditingLanguageSelector from '@/components/EditingLanguageSelector.vue'
import { loadPageIconIndex, searchPageIcons, type PageIconEntry } from '@/utils/pageIcons'
import { useAuthStore } from '@/stores/auth'
import { useFlowsStore } from '@/stores/flows'
import { useToastStore } from '@/stores/toast'
import { useUILanguage } from '@/composables/useUILanguage'
import { resolveImageUrl } from '@/composables/useImageUrlCache'
import { getErrorMessage } from '@/utils/errors'
import {
BLOCK_ALIGNS,
BLOCK_TYPES,
DATA_BLOCK_TYPES,
DATA_BLOCKS_PER_PAGE,
HOME_SLUG,
SUGGESTED_PAGE_ICONS,
isPageSlug,
localize,
newBlock,
pageIcon,
pageLinkConflictMessage,
blockAlign,
slugify,
type BlockAlign,
type LocalizedText,
type PageVisibility,
type SpaceBlock,
type SpaceBlockType,
type SpacePageDraft,
type SpacePageSummary
} from '@/utils/spacePages'
import {
getSpacePageDraft,
orderSpacePages,
publishSpacePage,
saveSpacePage
} from '@/services/spacePagesApi'
const props = defineProps<{
isOpen: boolean
/** The page edited; null for a new page */
pageSlug: string | null
/** The flow's pages: the addresses taken, and where a block button can lead */
pages: SpacePageSummary[]
}>()
const emit = defineEmits<{
close: []
/** The page was created, saved, published or unpublished; carries the API's page */
saved: [page: SpacePageDraft]
}>()
const authStore = useAuthStore()
const flowsStore = useFlowsStore()
const toastStore = useToastStore()
const { t, uiLanguage } = useUILanguage()
const flowId = computed(() => authStore.currentFlow || '')
const flow = computed(() => flowsStore.myFlows.find((f) => f.flowId === flowId.value))
const flowSlug = computed(() => flow.value?.flowSlug || '')
const defaultLanguage = computed(() => flow.value?.defaultLanguage || 'en')
const languages = computed(() => {
const enabled = flow.value?.enabledLanguages?.length ? flow.value.enabledLanguages : []
return [...new Set([defaultLanguage.value, ...enabled])]
})
const pageSlugs = computed(() => props.pages.map((page) => page.slug))
/** The slug the page is saved under; null until a new page is created */
const loadedSlug = ref<string | null>(null)
const slug = ref('')
/** A new page's address follows its title until typed in */
const slugEdited = ref(false)
const title = ref<LocalizedText>({})
const blocks = ref<SpaceBlock[]>([])
const visibility = ref<PageVisibility>('everyone')
const showInMenu = ref(true)
const menuOrder = ref(0)
const icon = ref<string | null>(null)
const updatedAt = ref<string | undefined>()
const published = ref<SpacePageDraft['published']>(null)
const hasUnpublishedChanges = ref(false)
const lang = ref(defaultLanguage.value)
const loading = ref(false)
const loadFailed = ref(false)
const saving = ref(false)
const dirty = ref(false)
const previewing = ref(false)
/** The space's home page, once saved: it can't change its address */
const isHome = computed(() => loadedSlug.value === HOME_SLUG)
/** A new page, until created; a page being loaded is not one */
const creating = computed(() => loadedSlug.value === null && props.pageSlug === null)
const pageTitle = computed(() => title.value[lang.value] || title.value[defaultLanguage.value])
const sidebarTitle = computed(() =>
creating.value ? t('spacePages.newPage') : t('spacePages.editPage')
)
// --- The place of the page in the space menu, among the other pages shown --
interface MenuEntry {
/** The page's slug; CURRENT_KEY for the page edited, whose slug may change */
key: string
title: string
icon: string
current: boolean
}
const CURRENT_KEY = 'current'
const menuEntries = ref<MenuEntry[]>([])
/** Dragged since the menu was read: keep the order instead of reading it again */
const menuMoved = ref(false)
const byMenuOrder = (
a: { menuOrder: number; slug: string },
b: { menuOrder: number; slug: string }
) => a.menuOrder - b.menuOrder || a.slug.localeCompare(b.slug)
/** The menu as saved, the page edited at its place (a new page last) */
function buildMenuEntries() {
const others = props.pages
.filter((page) => page.showInMenu && page.slug !== loadedSlug.value)
.sort(byMenuOrder)
const mine = { menuOrder: menuOrder.value, slug: loadedSlug.value ?? '' }
const at =
loadedSlug.value === null ? -1 : others.findIndex((page) => byMenuOrder(page, mine) > 0)
const entries: MenuEntry[] = others.map((page) => ({
key: page.slug,
title: localize(page.title, uiLanguage.value, defaultLanguage.value) || page.slug,
icon: pageIcon(page),
current: false
}))
entries.splice(at === -1 ? entries.length : at, 0, {
key: CURRENT_KEY,
title: '',
icon: '',
current: true
})
menuEntries.value = entries
menuMoved.value = false
}
// The pages may arrive after the sidebar opened (a link to a page), or change
watch(
() => props.pages,
() => {
if (!menuMoved.value) buildMenuEntries()
}
)
function setMenuEntries(entries: MenuEntry[]) {
menuEntries.value = entries
menuMoved.value = true
dirty.value = true
}
function moveInMenu(index: number, offset: number) {
const next = [...menuEntries.value]
const [entry] = next.splice(index, 1)
next.splice(index + offset, 0, entry)
setMenuEntries(next)
}
/** The page's menuOrder: its place in the menu, or the one it had when not in it */
const savedMenuOrder = () =>
showInMenu.value ? menuEntries.value.findIndex((entry) => entry.current) : menuOrder.value
/** The other pages of the menu no longer at their index: their order is saved too */
function menuNeedsOrdering() {
if (!showInMenu.value) return false
const saved = new Map(props.pages.map((page) => [page.slug, page.menuOrder]))
return menuEntries.value.some((entry, index) => !entry.current && saved.get(entry.key) !== index)
}
/** Another page has this address: saving would overwrite it, or be refused */
const slugTaken = computed(
() => slug.value !== loadedSlug.value && pageSlugs.value.includes(slug.value)
)
const slugError = computed(() => !isPageSlug(slug.value) || slugTaken.value)
const canSave = computed(
() =>
!loading.value && !loadFailed.value && Object.keys(title.value).length > 0 && !slugError.value
)
/** The page's menu icon, its default one until another is chosen */
const currentIcon = computed(() => pageIcon({ slug: slug.value, icon: icon.value }))
/** Search results shown at once in the picker, enough without a long grid */
const ICON_SEARCH_LIMIT = 60
const iconQuery = ref('')
const iconIndex = ref<PageIconEntry[]>([])
const iconIndexLoaded = ref(false)
// The index of every icon loads on the first search only
watch(iconQuery, async (query) => {
if (!query.trim() || iconIndexLoaded.value) return
iconIndex.value = await loadPageIconIndex()
iconIndexLoaded.value = iconIndex.value.length > 0
})
/** The suggested icons (the current one first when it is another), or the search's */
const iconChoices = computed(() => {
if (!iconQuery.value.trim()) {
const suggested: readonly string[] = SUGGESTED_PAGE_ICONS
return suggested.includes(currentIcon.value)
? [...suggested]
: [currentIcon.value, ...suggested]
}
return searchPageIcons(iconIndex.value, iconQuery.value, ICON_SEARCH_LIMIT)
})
function chooseIcon(name: string) {
icon.value = name
dirty.value = true
}
function apply(page: SpacePageDraft) {
loadedSlug.value = page.slug
slug.value = page.slug
title.value = page.draft.title
blocks.value = page.draft.blocks
visibility.value = page.visibility
showInMenu.value = page.showInMenu
menuOrder.value = page.menuOrder
icon.value = page.icon ?? null
updatedAt.value = page.updatedAt
published.value = page.published
hasUnpublishedChanges.value = page.hasUnpublishedChanges
dirty.value = false
buildMenuEntries()
}
/** What every opening starts from: the edit tab, the flow's default language */
function resetView() {
lang.value = defaultLanguage.value
previewing.value = false
iconQuery.value = ''
loadFailed.value = false
dirty.value = false
}
/** A blank page; the space's first one is suggested as its home page */
function startNew() {
resetView()
loadedSlug.value = null
slug.value = props.pages.length === 0 ? HOME_SLUG : ''
slugEdited.value = false
title.value = {}
blocks.value = []
visibility.value = 'everyone'
showInMenu.value = true
menuOrder.value = props.pages.length
icon.value = null
updatedAt.value = undefined
published.value = null
hasUnpublishedChanges.value = false
buildMenuEntries()
}
async function load(pageSlug: string) {
resetView()
loading.value = true
try {
apply(await getSpacePageDraft(flowId.value, pageSlug))
} catch (err) {
console.error('[SpacePageFormSidebar] failed to load the page:', err)
loadFailed.value = true
} finally {
loading.value = false
}
}
// Every opening starts afresh; while open, another page loads, except the
// one just saved under its new address (created or renamed)
watch(
() => [props.isOpen, props.pageSlug] as const,
([open, pageSlug], previous) => {
if (!open) return
const wasOpen = previous?.[0] === true
if (wasOpen && pageSlug !== null && pageSlug === loadedSlug.value) return
if (pageSlug === null) startNew()
else void load(pageSlug)
},
{ immediate: true }
)
function setTitle(value: string) {
const { [lang.value]: _previous, ...others } = title.value
title.value = value.trim() ? { ...others, [lang.value]: value } : others
dirty.value = true
if (creating.value && !slugEdited.value && props.pages.length > 0) {
slug.value = slugify(title.value[lang.value] || '')
}
}
function onSlugInput() {
slugEdited.value = true
dirty.value = true
}
function addBlock(type: SpaceBlockType) {
blocks.value = [...blocks.value, newBlock(type)]
dirty.value = true
}
const dataBlocksFull = computed(
() =>
blocks.value.filter((block) => DATA_BLOCK_TYPES.includes(block.type)).length >=
DATA_BLOCKS_PER_PAGE
)
/** The items and count read with a block no longer match it once changed */
function withoutResolvedData(block: SpaceBlock): SpaceBlock {
const changed: Record<string, unknown> = { ...block }
delete changed.data
delete changed.count
delete changed.unavailable
return changed as unknown as SpaceBlock
}
const ALIGN_LABELS: Record<BlockAlign, string> = {
left: 'spacePages.alignLeft',
center: 'spacePages.alignCenter',
right: 'spacePages.alignRight',
justify: 'spacePages.alignJustify'
}
function updateBlock(index: number, block: SpaceBlock) {
blocks.value = blocks.value.map((current, i) =>
i === index ? withoutResolvedData(block) : current
)
dirty.value = true
}
function move(index: number, offset: number) {
const next = [...blocks.value]
const [block] = next.splice(index, 1)
next.splice(index + offset, 0, block)
blocks.value = next
dirty.value = true
}
function removeBlock(index: number) {
blocks.value = blocks.value.filter((_, i) => i !== index)
dirty.value = true
}
/** Creates the page, or saves its draft; true when saved */
async function save(): Promise<boolean> {
const isNew = creating.value
saving.value = true
try {
const saved = await saveSpacePage(flowId.value, loadedSlug.value ?? slug.value, {
title: title.value,
blocks: blocks.value,
visibility: visibility.value,
showInMenu: showInMenu.value,
menuOrder: savedMenuOrder(),
icon: icon.value,
...(!isNew && slug.value !== loadedSlug.value && { slug: slug.value }),
...(!isNew && { expectedUpdatedAt: updatedAt.value })
})
const reorder = menuNeedsOrdering()
const entries = menuEntries.value
const order = entries.map((entry) => (entry.current ? saved.slug : entry.key))
apply(saved)
// As placed, not as the pages read before saving were
menuEntries.value = entries
toastStore.success(isNew ? t('spacePages.created') : t('spacePages.saved'))
if (reorder) await saveMenuOrder(order)
emit('saved', saved)
return true
} catch (err) {
toastStore.error(saveErrorMessage(err))
return false
} finally {
saving.value = false
}
}
/** The other pages move around the page saved; the page itself is saved already */
async function saveMenuOrder(order: string[]) {
try {
await orderSpacePages(flowId.value, order)
} catch (err) {
console.error('[SpacePageFormSidebar] failed to order the menu:', err)
toastStore.error(t('spacePages.orderError'))
}
}
/** Why a change was refused: the pages it would break a link with, or the API's error */
function saveErrorMessage(err: unknown) {
return (
pageLinkConflictMessage(err, t, uiLanguage.value, defaultLanguage.value) ??
getErrorMessage(err, t('spacePages.saveError'), t)
)
}
/**
* Publishing publishes the saved draft, so unsaved changes are saved first;
* unpublishing leaves the draft, and the changes being made, as they are.
*/
async function setPublished(publish: boolean) {
if (publish && dirty.value && !(await save())) return
saving.value = true
try {
const page = await publishSpacePage(flowId.value, loadedSlug.value!, publish)
published.value = page.published
hasUnpublishedChanges.value = page.hasUnpublishedChanges
updatedAt.value = page.updatedAt
toastStore.success(publish ? t('spacePages.publishedToast') : t('spacePages.unpublished'))
emit('saved', page)
} catch (err) {
toastStore.error(saveErrorMessage(err))
} finally {
saving.value = false
}
}
const publish = () => setPublished(true)
const unpublish = () => setPublished(false)
// --- Unsaved changes: BaseFormSidebar asks, in the app's own modal
const baseSidebar = ref<InstanceType<typeof BaseFormSidebar> | null>(null)
/**
* Asks before dropping unsaved changes; resolves true when there are none left
* to lose. For the page's guard when another page's sidebar opens; leaving
* the page is guarded by BaseFormSidebar itself.
*/
async function confirmDiscard(): Promise<boolean> {
return (await baseSidebar.value?.confirmDiscard()) ?? true
}
/** The footer's Cancel: the header's close cross asks in BaseFormSidebar */
async function handleClose() {
if (await confirmDiscard()) emit('close')
}
// The preview's images: read URLs of the images just uploaded, not yet saved
const uploadedImageUrls = reactive<Record<string, string>>({})
type Picture = { imageKey?: string; imageUrl?: string }
/** The block itself and the entries of a gallery or columns block: what holds an image */
const picturesOf = (block: SpaceBlock): Picture[] => [
block as Picture,
...((block as { images?: Picture[] }).images || []),
...((block as { columns?: Picture[] }).columns || [])
]
watch(
blocks,
(current) => {
for (const picture of current.flatMap(picturesOf)) {
const key = picture.imageKey
if (!key || picture.imageUrl || key in uploadedImageUrls) continue
uploadedImageUrls[key] = ''
void resolveImageUrl(key).then((url) => {
uploadedImageUrls[key] = url
})
}
},
{ deep: true }
)
const withPreviewUrl = <T extends Picture>(picture: T): T =>
picture.imageKey && !picture.imageUrl
? { ...picture, imageUrl: uploadedImageUrls[picture.imageKey] || undefined }
: picture
const previewBlocks = computed(() =>
blocks.value.map((block) => {
const result: Record<string, unknown> = withPreviewUrl(block as Picture)
if (block.type === 'gallery') result.images = block.images.map(withPreviewUrl)
if (block.type === 'columns') result.columns = block.columns.map(withPreviewUrl)
return result as unknown as SpaceBlock
})
)
const previewSpace = computed<PublicSpace>(() => ({
slug: flowSlug.value,
name: flow.value?.flowName || '',
defaultLanguage: defaultLanguage.value,
theme: flow.value?.space?.theme || {},
joinOpen: !!flow.value?.space?.join
}))
defineExpose({ confirmDiscard })
</script>
<style scoped>
.page-menu-handle {
cursor: grab;
}
.page-menu-current {
background-color: var(--bw-surface-muted);
}
</style>
|