All files / src/components RichTextEditor.vue

98.38% Statements 61/62
94.11% Branches 32/34
100% Functions 30/30
100% Lines 56/56

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  28x   224x                   10x                 3x           1x                                                             5x 5x   5x   5x 6x     5x   5x                           2x         20x     10x 10x         5x 7x   2x 2x 2x 2x 1x       5x 5x 5x     3x 3x 3x 3x       3x 3x 3x 2x 1x 2x     7x 5x 448x   5x         56x 1x           56x 1x           56x 1x           56x 1x           56x 1x           56x 1x           56x 1x           56x         5x                          
<template>
  <div class="rich-text-editor border rounded" data-testid="rich-text-editor">
    <div class="rte-toolbar d-flex flex-wrap gap-1 p-1 border-bottom" role="toolbar">
      <button
        v-for="action in actions"
        :key="action.name"
        type="button"
        class="btn btn-sm"
        :class="action.active() ? 'btn-secondary' : 'btn-outline-secondary'"
        :title="t(action.label)"
        :aria-label="t(action.label)"
        :aria-pressed="action.active()"
        :data-testid="`rte-${action.name}`"
        @click="action.run()"
      >
        <span v-if="action.text" class="fw-bold small">{{ action.text }}</span>
        <font-awesome-icon v-else :icon="action.icon!" />
      </button>
    </div>
    <div v-if="linkOpen" class="d-flex gap-1 p-1 border-bottom" data-testid="rte-link-form">
      <input
        ref="linkInput"
        v-model="linkUrl"
        type="url"
        class="form-control form-control-sm"
        placeholder="https://"
        :class="{ 'is-invalid': linkUrl && !safeHref(linkUrl) }"
        @keydown.enter.prevent="applyLink"
        @keydown.escape="linkOpen = false"
      />
      <button
        type="button"
        class="btn btn-sm btn-primary"
        :disabled="!!linkUrl && !safeHref(linkUrl)"
        @click="applyLink"
      >
        {{ t('spacePages.rte.applyLink') }}
      </button>
    </div>
    <EditorContent :editor="editor" class="rte-content p-2" />
  </div>
</template>
 
<script setup lang="ts">
// @implements UC-SPACE-009.1
/**
 * Visual editor of a page's rich text (TipTap, MIT), limited to what the API
 * accepts (flows-api utils/spacePages.js): paragraphs, headings 2 and 3,
 * lists, line breaks, bold, italic, underline, https:/mailto: links. Loaded
 * only by the page editor. v-model: a TipTap JSON document, null when empty.
 */
import { nextTick, onBeforeUnmount, ref, watch } from 'vue'
import { EditorContent, useEditor } from '@tiptap/vue-3'
import StarterKit from '@tiptap/starter-kit'
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
import { useUILanguage } from '@/composables/useUILanguage'
import { hasText, safeHref } from '@/utils/richText'
import type { RichTextNode } from '@/utils/spacePages'
 
const props = defineProps<{ modelValue?: RichTextNode | null }>()
const emit = defineEmits<{ 'update:modelValue': [value: RichTextNode | null] }>()
 
const { t } = useUILanguage()
 
const toContent = (doc: RichTextNode | null | undefined) =>
  doc ?? { type: 'doc', content: [{ type: 'paragraph' }] }
 
// Bumped on every editor transaction, so the toolbar shows the active marks
const editorVersion = ref(0)
 
const editor = useEditor({
  content: toContent(props.modelValue),
  extensions: [
    StarterKit.configure({
      heading: { levels: [2, 3] },
      blockquote: false,
      code: false,
      codeBlock: false,
      horizontalRule: false,
      strike: false,
      link: {
        openOnClick: false,
        autolink: true,
        defaultProtocol: 'https',
        isAllowedUri: (url) => !!safeHref(url)
      }
    })
  ],
  onTransaction: () => {
    editorVersion.value++
  },
  onUpdate: ({ editor: current }) => {
    const doc = current.getJSON() as RichTextNode
    emit('update:modelValue', hasText(doc) ? doc : null)
  }
})
 
// Another language (or another block) shown: its own text
watch(
  () => props.modelValue,
  (value) => {
    const current = editor.value
    Iif (!current) return
    const shown = current.getJSON() as RichTextNode
    if (JSON.stringify(hasText(shown) ? shown : null) === JSON.stringify(value ?? null)) return
    current.commands.setContent(toContent(value), { emitUpdate: false })
  }
)
 
const linkOpen = ref(false)
const linkUrl = ref('')
const linkInput = ref<HTMLInputElement | null>(null)
 
async function openLink() {
  linkUrl.value = editor.value?.getAttributes('link').href || ''
  linkOpen.value = true
  await nextTick()
  linkInput.value?.focus()
}
 
function applyLink() {
  const chain = editor.value?.chain().focus().extendMarkRange('link')
  const href = safeHref(linkUrl.value)
  if (!linkUrl.value) chain?.unsetLink().run()
  else if (href) chain?.setLink({ href }).run()
  else return
  linkOpen.value = false
}
 
const chain = () => editor.value!.chain().focus()
const isActive = (name: string, attrs?: Record<string, unknown>) =>
  editorVersion.value >= 0 && !!editor.value?.isActive(name, attrs)
 
const actions = [
  {
    name: 'h2',
    text: 'H2',
    label: 'spacePages.rte.heading2',
    active: () => isActive('heading', { level: 2 }),
    run: () => chain().toggleHeading({ level: 2 }).run()
  },
  {
    name: 'h3',
    text: 'H3',
    label: 'spacePages.rte.heading3',
    active: () => isActive('heading', { level: 3 }),
    run: () => chain().toggleHeading({ level: 3 }).run()
  },
  {
    name: 'bold',
    icon: 'fa-solid fa-bold',
    label: 'spacePages.rte.bold',
    active: () => isActive('bold'),
    run: () => chain().toggleBold().run()
  },
  {
    name: 'italic',
    icon: 'fa-solid fa-italic',
    label: 'spacePages.rte.italic',
    active: () => isActive('italic'),
    run: () => chain().toggleItalic().run()
  },
  {
    name: 'underline',
    icon: 'fa-solid fa-underline',
    label: 'spacePages.rte.underline',
    active: () => isActive('underline'),
    run: () => chain().toggleUnderline().run()
  },
  {
    name: 'bullet-list',
    icon: 'fa-solid fa-list-ul',
    label: 'spacePages.rte.bulletList',
    active: () => isActive('bulletList'),
    run: () => chain().toggleBulletList().run()
  },
  {
    name: 'ordered-list',
    icon: 'fa-solid fa-list-ol',
    label: 'spacePages.rte.orderedList',
    active: () => isActive('orderedList'),
    run: () => chain().toggleOrderedList().run()
  },
  {
    name: 'link',
    icon: 'fa-solid fa-link',
    label: 'spacePages.rte.link',
    active: () => isActive('link'),
    run: openLink
  }
]
 
onBeforeUnmount(() => editor.value?.destroy())
</script>
 
<style scoped>
.rte-content :deep(.ProseMirror) {
  min-height: 6rem;
  outline: none;
}
 
.rte-content :deep(.ProseMirror > :last-child) {
  margin-bottom: 0;
}
</style>