All files / src/utils spacePages.ts

100% Statements 74/74
100% Branches 51/51
100% Functions 15/15
100% Lines 62/62

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                                                                                                                                                                                                                                                                                                                                                        19x                             19x 19x               19x                           1628x 1628x 1627x       19x 19x 19x 19x 19x   19x 19x                     19x                                                                                         19x               19x                                                                             278x         240x   19x 19x   19x 44x       8x                     1599x               1080x 959x 636x 20x     30x       30x 30x   1x   2x   2x   5x   1x   5x   2x   3x   3x   2x   2x   2x                 6x 24x 6x 1x   6x 2x   6x         47x 47x 36x 26x     19x                             12x 12x 12x 3x     4x     3x    
// @implements UC-SPACE-009.1, UC-SPACE-010.1, UC-SPACE-011.1, UC-SPACE-012.1, UC-SPACE-013.1, UC-SPACE-014.1, UC-SPACE-016.1, UC-SPACE-023.1
/**
 * The pages of a flow's public space, made of blocks — mirrors flows-api
 * utils/spacePages.js and utils/spaceData.js. See docs/architecture/FLOW_SPACE.md
 * "Pages and content blocks" and "Data blocks and more content blocks".
 */
 
import { isPageIcon } from '@/utils/pageIcons'
 
/** A text in each language, by two-letter language code */
export type LocalizedText = Record<string, string>
 
/** A TipTap JSON node, limited server-side to the nodes and marks of richText.ts */
export interface RichTextNode {
  type: string
  text?: string
  attrs?: Record<string, any>
  marks?: { type: string; attrs?: Record<string, any> }[]
  content?: RichTextNode[]
}
export type LocalizedRichText = Record<string, RichTextNode>
 
export type PageLink =
  { type: 'join' } | { type: 'page'; slug: string } | { type: 'url'; url: string }
 
/** How a block's content is aligned (UC-SPACE-023.1) */
export type BlockAlign = 'left' | 'center' | 'right' | 'justify'
 
interface BlockBase {
  id: string
  /** Not set: the block's default (BLOCK_ALIGNS) */
  align?: BlockAlign
  /** Present in responses next to an image key: a one-hour read URL */
  imageUrl?: string
}
export interface HeroBlock extends BlockBase {
  type: 'hero'
  title: LocalizedText
  text?: LocalizedText
  imageKey?: string
  button?: { label: LocalizedText; link: PageLink }
}
export interface RichTextBlock extends BlockBase {
  type: 'richText'
  content: LocalizedRichText
}
export interface ImageBlock extends BlockBase {
  type: 'image'
  imageKey: string
  alt?: LocalizedText
  caption?: LocalizedText
}
export interface FaqBlock extends BlockBase {
  type: 'faq'
  entries: { question: LocalizedText; answer: LocalizedRichText }[]
}
export interface ContactBlock extends BlockBase {
  type: 'contact'
  email?: string
  phone?: string
  address?: LocalizedText
}
export interface JoinBlock extends BlockBase {
  type: 'join'
  label?: LocalizedText
}
export interface PictureEntry {
  imageKey: string
  alt?: LocalizedText
  caption?: LocalizedText
  /** In responses: a one-hour read URL */
  imageUrl?: string
}
export interface GalleryBlock extends BlockBase {
  type: 'gallery'
  images: PictureEntry[]
}
export interface ColumnEntry {
  imageKey?: string
  alt?: LocalizedText
  content?: LocalizedRichText
  imageUrl?: string
}
export interface ColumnsBlock extends BlockBase {
  type: 'columns'
  columns: ColumnEntry[]
}
 
/** A field a data block shows: its form placement, type and name */
export interface DataField {
  fieldId: string
  type: string
  name: string | LocalizedText
  labelOverride?: LocalizedText
  x?: number
  y?: number
  w?: number
  h?: number
}
/** An item as a data block shows it: display values of the shown fields only */
export interface DataItem {
  id: string
  createdAt: string
  /** Agenda only: the date the item is placed on (YYYY-MM-DD, or the creation date) */
  date?: string
  values: Record<string, any>
}
/** The next items of an item list ("load more", UC-SPACE-019.1) */
export interface ListItemsPage {
  items: DataItem[]
  hasMore: boolean
}
/** Reads the items of an item list from `offset`: the visitor's or the member's endpoint */
export type LoadListItems = (blockId: string, offset: number) => Promise<ListItemsPage>
export interface ListFilter {
  fieldId: string
  values: (string | number | boolean)[]
}
export interface ListSort {
  fieldId: string
  direction: 'asc' | 'desc'
}
interface EntityBlockBase extends BlockBase {
  entityId: string
  formId: string
  /** Editor's draft only: the entity, form or item is gone */
  unavailable?: boolean
}
export interface ItemListBlock extends EntityBlockBase {
  type: 'itemList'
  title?: LocalizedText
  filters: ListFilter[]
  upcomingFieldId?: string
  sort?: ListSort
  limit: number
  /** `agenda`: grouped by month and day of the date the list is sorted on (UC-SPACE-019.1) */
  layout: 'cards' | 'list' | 'agenda' | 'map'
  /** In responses; `hasMore`: more items follow, read by "load more" */
  data?: { fields: DataField[]; items: DataItem[]; hasMore?: boolean }
}
export interface ItemCardBlock extends EntityBlockBase {
  type: 'itemCard'
  itemId: string
  data?: { fields: DataField[]; item: DataItem }
}
export interface MemberCountBlock extends BlockBase {
  type: 'memberCount'
  label?: LocalizedText
  /** In responses */
  count?: number
}
export interface ItemFormBlock extends EntityBlockBase {
  type: 'itemForm'
  label: LocalizedText
  text?: LocalizedText
}
 
export type SpaceBlock =
  | HeroBlock
  | RichTextBlock
  | ImageBlock
  | FaqBlock
  | ContactBlock
  | JoinBlock
  | GalleryBlock
  | ColumnsBlock
  | ItemListBlock
  | ItemCardBlock
  | MemberCountBlock
  | ItemFormBlock
export type SpaceBlockType = SpaceBlock['type']
 
export const BLOCK_TYPES: SpaceBlockType[] = [
  'hero',
  'richText',
  'image',
  'gallery',
  'columns',
  'faq',
  'contact',
  'join',
  'itemList',
  'itemCard',
  'memberCount',
  'itemForm'
]
 
const SIDE_ALIGNS: BlockAlign[] = ['left', 'center', 'right']
const TEXT_ALIGNS: BlockAlign[] = [...SIDE_ALIGNS, 'justify']
/**
 * The alignments each block takes, its default first (mirrors flows-api
 * utils/spacePages.js): `justify` only where paragraphs are written; none for
 * galleries, item lists and item cards
 */
export const BLOCK_ALIGNS: Partial<
  Record<SpaceBlockType, { aligns: BlockAlign[]; default: BlockAlign }>
> = {
  hero: { aligns: TEXT_ALIGNS, default: 'center' },
  richText: { aligns: TEXT_ALIGNS, default: 'left' },
  image: { aligns: SIDE_ALIGNS, default: 'center' },
  faq: { aligns: TEXT_ALIGNS, default: 'left' },
  contact: { aligns: SIDE_ALIGNS, default: 'left' },
  join: { aligns: SIDE_ALIGNS, default: 'left' },
  columns: { aligns: TEXT_ALIGNS, default: 'left' },
  memberCount: { aligns: SIDE_ALIGNS, default: 'center' },
  itemForm: { aligns: TEXT_ALIGNS, default: 'center' }
}
 
/** How a block shows: its own alignment, else its default; null for a block without */
export function blockAlign(block: SpaceBlock): BlockAlign | null {
  const spec = BLOCK_ALIGNS[block.type]
  if (!spec) return null
  return block.align && spec.aligns.includes(block.align) ? block.align : spec.default
}
 
/** Blocks showing a flow's items (at most DATA_BLOCKS_PER_PAGE a page) */
export const DATA_BLOCK_TYPES: SpaceBlockType[] = ['itemList', 'itemCard']
export const DATA_BLOCKS_PER_PAGE = 6
export const GALLERY_MAX_IMAGES = 30
export const LIST_MAX_ITEMS = 50
export const LIST_MAX_FILTERS = 5
/** Field types never shown on a page (mirrors flows-api utils/spaceData.js) */
export const HIDDEN_FIELD_TYPES = ['user', 'password', 'relation']
export const FILTER_FIELD_TYPES = [
  'text',
  'email',
  'number',
  'date',
  'boolean',
  'select',
  'multiselect',
  'workflow',
  'entity_ref'
]
export const SORT_FIELD_TYPES = ['text', 'textarea', 'email', 'number', 'date']
 
export type PageVisibility = 'everyone' | 'members'
 
export interface SpacePageMenuEntry {
  slug: string
  title: LocalizedText
  membersOnly?: boolean
  icon?: string
}
 
/** A published page, as visitors read it */
export interface SpacePageContent {
  slug: string
  visibility?: PageVisibility
  title: LocalizedText
  blocks: SpaceBlock[]
  publishedAt?: string
}
 
/** A page's settings and draft, for its editor */
export interface SpacePageDraft {
  slug: string
  visibility: PageVisibility
  showInMenu: boolean
  menuOrder: number
  icon?: string
  draft: { title: LocalizedText; blocks: SpaceBlock[] }
  published: { title: LocalizedText; publishedAt: string } | null
  hasUnpublishedChanges: boolean
  updatedAt: string
}
 
export interface SpacePageSummary {
  slug: string
  visibility: PageVisibility
  showInMenu: boolean
  menuOrder: number
  icon?: string
  title: LocalizedText
  published: { title: LocalizedText; publishedAt: string } | null
  hasUnpublishedChanges?: boolean
  updatedAt?: string
}
 
export const HOME_SLUG = 'home'
 
/**
 * The icons the editor suggests for the space menu (UC-SPACE-015.1), before
 * any search. A page can use any Font Awesome free solid icon (see
 * utils/pageIcons.ts); these ones are registered in main.ts, so they show
 * without any request.
 */
export const SUGGESTED_PAGE_ICONS = [
  'house',
  'file-lines',
  'circle-info',
  'users',
  'user-plus',
  'calendar',
  'calendar-days',
  'clock',
  'trophy',
  'medal',
  'star',
  'heart',
  'image',
  'images',
  'camera',
  'newspaper',
  'bullhorn',
  'book',
  'graduation-cap',
  'list',
  'table',
  'location-dot',
  'map',
  'envelope',
  'phone',
  'comments',
  'euro-sign',
  'tag',
  'handshake',
  'shield-halved',
  'futbol',
  'person-running',
  'music',
  'link'
] as const
 
/** A page's default menu icon: `house` for the home page, `file-lines` for others */
export function defaultPageIcon(page: { slug: string }): string {
  return page.slug === HOME_SLUG ? 'house' : 'file-lines'
}
 
/** A page's menu icon: its own (any well-formed name), else its default one */
export function pageIcon(page: { slug: string; icon?: string | null }): string {
  return isPageIcon(page.icon) ? page.icon : defaultPageIcon(page)
}
export const PAGE_SLUG_REGEX = /^[a-z0-9](?:[a-z0-9-]{0,48}[a-z0-9])?$/
const RESERVED_SLUGS = ['join']
 
export const isPageSlug = (slug: string) =>
  PAGE_SLUG_REGEX.test(slug) && !RESERVED_SLUGS.includes(slug)
 
/** A page slug from a title: lowercase ASCII, dashes, at most 50 characters */
export function slugify(title: string): string {
  return title
    .normalize('NFD')
    .replace(/[̀-ͯ]/g, '')
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-+|-+$/g, '')
    .slice(0, 50)
    .replace(/-+$/g, '')
}
 
/** An empty string is an untranslated text (the editors store `""`), not a translation */
const isTranslated = (text: unknown) => text !== undefined && text !== null && text !== ''
 
/** The text in `lang`, else in `fallback`, else in any language */
export function localize<T>(
  value: Record<string, T> | undefined | null,
  lang: string,
  fallback?: string
): T | undefined {
  if (!value) return undefined
  if (isTranslated(value[lang])) return value[lang]
  if (fallback && isTranslated(value[fallback])) return value[fallback]
  return Object.values(value).find(isTranslated)
}
 
const newId = () => crypto.randomUUID().replace(/-/g, '').slice(0, 12)
 
/** A new, empty block of `type` (the editor fills it before saving) */
export function newBlock(type: SpaceBlockType): SpaceBlock {
  const id = newId()
  switch (type) {
    case 'hero':
      return { id, type, title: {} }
    case 'richText':
      return { id, type, content: {} }
    case 'image':
      return { id, type, imageKey: '' }
    case 'faq':
      return { id, type, entries: [{ question: {}, answer: {} }] }
    case 'contact':
      return { id, type }
    case 'join':
      return { id, type }
    case 'gallery':
      return { id, type, images: [] }
    case 'columns':
      return { id, type, columns: [{}, {}] }
    case 'itemList':
      return { id, type, entityId: '', formId: '', filters: [], limit: 6, layout: 'cards' }
    case 'itemCard':
      return { id, type, entityId: '', formId: '', itemId: '' }
    case 'memberCount':
      return { id, type }
    case 'itemForm':
      return { id, type, entityId: '', formId: '', label: {} }
  }
}
 
/**
 * The block as the API takes it: response-only fields (image URLs, items,
 * count, unavailable mark) dropped.
 */
export function toBlockInput(block: SpaceBlock): SpaceBlock {
  const input: Record<string, any> = { ...block }
  for (const key of ['imageUrl', 'data', 'count', 'unavailable']) delete input[key]
  if (block.type === 'gallery') {
    input.images = block.images.map(({ imageUrl: _url, ...entry }) => entry)
  }
  if (block.type === 'columns') {
    input.columns = block.columns.map(({ imageUrl: _url, ...entry }) => entry)
  }
  return input as SpaceBlock
}
 
/** The label of a shown field: its form override, else its name */
export function dataFieldLabel(field: DataField, lang: string, fallback?: string): string {
  const override = localize(field.labelOverride, lang, fallback)
  if (override) return override
  if (typeof field.name === 'string') return field.name
  return localize(field.name, lang, fallback) || ''
}
 
const LINK_CONFLICT_KEYS: Record<string, string> = {
  PAGE_LINKED: 'spacePages.pageLinked',
  LINKS_TO_UNPUBLISHED: 'spacePages.linksToUnpublished'
}
 
/**
 * The message for a change the API refused to keep the links between pages
 * working (UC-SPACE-016.1), naming the pages in `lang`; null for any other error
 */
export function pageLinkConflictMessage(
  err: any,
  t: (key: string) => string,
  lang: string,
  fallback?: string
): string | null {
  const data = err?.response?.data
  const key = LINK_CONFLICT_KEYS[data?.error]
  if (!key || !Array.isArray(data.pages)) return null
  const names = data.pages
    .map(
      (page: { slug: string; title?: LocalizedText | null }) =>
        `"${localize(page.title, lang, fallback) || page.slug}"`
    )
    .join(', ')
  return t(key).replace('{pages}', names)
}