feat: [OCISDEV-137] inline markdown editor images as base64 (#12967)
* feat: [OCISDEV-137] inline markdown editor images as base64
This commit is contained in:
1 parent
d54974677e
commit
b99e8ff0a7
8 files changed
+695
-29
No files matched your search
@@ -0,0 +1,27 @@
|
||||
Enhancement: Inline images in the markdown editor
|
||||
|
||||
Uploading an image in the markdown editor did nothing at all - neither
|
||||
drag-and-drop nor the "Upload Images" toolbar button produced a result, a
|
||||
progress indicator, or an error. The feature had been deliberately suppressed
|
||||
because there was no answer to where an uploaded image should be stored, and
|
||||
because a recipient of a public link to a single markdown file has no
|
||||
permission to read an image stored next to it.
|
||||
|
||||
Images dropped or picked in the markdown editor are now encoded into the
|
||||
document itself as base64 data URIs, so a shared document carries its own
|
||||
images and needs no further permissions. Because the image bytes are now part
|
||||
of the document, two limits keep documents small enough to stay fully
|
||||
searchable: a maximum size per image, and a budget for the total size of all
|
||||
images in one document. An image that exceeds either limit is rejected with a
|
||||
notification naming the image and the limit, instead of failing silently.
|
||||
|
||||
Both limits are configurable through the text editor's app configuration as
|
||||
`maxImageSize` and `maxDocumentImageSize`, given in bytes and defaulting to
|
||||
2 MB and 10 MB respectively.
|
||||
|
||||
The editor's "Crop And Upload" entry is no longer offered. Cropping was not part
|
||||
of the reported problem, so it stays out until users ask for it, and images are
|
||||
inlined exactly as they were picked.
|
||||
|
||||
https://github.com/owncloud/ocis/pull/12967
|
||||
https://github.com/owncloud/web/issues/12407
|
||||
@@ -23,34 +23,40 @@
|
||||
:auto-focus="autoFocus"
|
||||
:sanitize="sanitize"
|
||||
:toolbars-exclude="['save', 'github']"
|
||||
no-upload-img
|
||||
@on-change="(value) => $emit('update:currentContent', value)"
|
||||
@on-upload-img="onUploadImg"
|
||||
>
|
||||
<template #defFooters>
|
||||
<span class="footer-links">
|
||||
<a
|
||||
href="https://imzbf.github.io/md-editor-v3/en-US/api#%F0%9F%AA%A1%20Shortcut%20keys"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>{{
|
||||
$pgettext(
|
||||
'A link to a list of keyboard shortcuts that can be used in the markdown editor.',
|
||||
'Keyboard shortcuts'
|
||||
)
|
||||
}}</a
|
||||
>
|
||||
<span class="footer-slot">
|
||||
<span v-if="isAddingImages" class="footer-image-progress" role="status">
|
||||
{{ $gettext('Adding image…') }}
|
||||
</span>
|
||||
|
||||
<a
|
||||
href="https://highlightjs.readthedocs.io/en/latest/supported-languages.html"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>{{
|
||||
$pgettext(
|
||||
'A link to a list of supported programming languages that can be used in the markdown editor.',
|
||||
'Supported programming languages'
|
||||
)
|
||||
}}</a
|
||||
>
|
||||
<span class="footer-links">
|
||||
<a
|
||||
href="https://imzbf.github.io/md-editor-v3/en-US/api#%F0%9F%AA%A1%20Shortcut%20keys"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>{{
|
||||
$pgettext(
|
||||
'A link to a list of keyboard shortcuts that can be used in the markdown editor.',
|
||||
'Keyboard shortcuts'
|
||||
)
|
||||
}}</a
|
||||
>
|
||||
|
||||
<a
|
||||
href="https://highlightjs.readthedocs.io/en/latest/supported-languages.html"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>{{
|
||||
$pgettext(
|
||||
'A link to a list of supported programming languages that can be used in the markdown editor.',
|
||||
'Supported programming languages'
|
||||
)
|
||||
}}</a
|
||||
>
|
||||
</span>
|
||||
</span>
|
||||
</template>
|
||||
</md-editor>
|
||||
@@ -58,7 +64,7 @@
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { computed, nextTick, onMounted, unref } from 'vue'
|
||||
import { computed, nextTick, onMounted, ref, unref, watch } from 'vue'
|
||||
import { Resource } from '@ownclouders/web-client'
|
||||
import dompurify from 'dompurify'
|
||||
|
||||
@@ -82,7 +88,9 @@ import { languageUserDefined, languages } from './l18n'
|
||||
|
||||
import { useGettext } from 'vue3-gettext'
|
||||
import { AppConfigObject } from '../../apps'
|
||||
import { useThemeStore } from '../../composables'
|
||||
import { useMessages, useThemeStore } from '../../composables'
|
||||
import { DEFAULT_MAX_DOCUMENT_IMAGE_SIZE, DEFAULT_MAX_IMAGE_SIZE } from '../../constants'
|
||||
import { formatFileSize } from '../../helpers'
|
||||
|
||||
interface TextEditorProps {
|
||||
applicationConfig?: AppConfigObject
|
||||
@@ -106,13 +114,18 @@ const {
|
||||
|
||||
defineEmits<TextEditorEmits>()
|
||||
|
||||
const { current: currentLanguage, $gettext } = useGettext()
|
||||
const { current: currentLanguage, $gettext, $ngettext } = useGettext()
|
||||
const { currentTheme } = useThemeStore()
|
||||
const { showErrorMessage } = useMessages()
|
||||
|
||||
// Should not be a ref, otherwise functions like setMarkdown won't work
|
||||
const editorConfig = computed(() => {
|
||||
const { showPreviewOnlyMd = true }: AppConfigObject = applicationConfig
|
||||
return { showPreviewOnlyMd }
|
||||
const {
|
||||
showPreviewOnlyMd = true,
|
||||
maxImageSize = DEFAULT_MAX_IMAGE_SIZE,
|
||||
maxDocumentImageSize = DEFAULT_MAX_DOCUMENT_IMAGE_SIZE
|
||||
}: AppConfigObject = applicationConfig
|
||||
return { showPreviewOnlyMd, maxImageSize, maxDocumentImageSize }
|
||||
})
|
||||
|
||||
const isMarkdown = computed(() => {
|
||||
@@ -128,6 +141,141 @@ const theme = computed(() => (unref(currentTheme).isDark ? 'dark' : 'light'))
|
||||
const sanitize = (html) =>
|
||||
dompurify.sanitize(html, { ADD_ATTR: ['target'], ADD_TAGS: ['foreignObject'] })
|
||||
|
||||
const dataUriRegex = /data:image\/[a-z0-9.+-]+;base64,[A-Za-z0-9+/=]+/gi
|
||||
|
||||
const isAddingImages = ref(false)
|
||||
const pendingImageSize = ref(0)
|
||||
|
||||
const formatSize = (size: number) => formatFileSize(size, currentLanguage)
|
||||
|
||||
const MAX_LISTED_FILE_NAMES = 3
|
||||
|
||||
const formatFileNames = (names: Array<string>): string => {
|
||||
const listed = names.slice(0, MAX_LISTED_FILE_NAMES).join(', ')
|
||||
if (names.length <= MAX_LISTED_FILE_NAMES) {
|
||||
return listed
|
||||
}
|
||||
return $gettext('%{ files } and %{ count } more', {
|
||||
files: listed,
|
||||
count: (names.length - MAX_LISTED_FILE_NAMES).toString()
|
||||
})
|
||||
}
|
||||
|
||||
const usedDocumentImageSize = (markdown: string): number => {
|
||||
const dataUris: string[] = markdown?.match(dataUriRegex) ?? []
|
||||
return dataUris.reduce((total, dataUri) => total + dataUri.length, 0)
|
||||
}
|
||||
|
||||
const readAsDataUrl = (file: File): Promise<string> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const reader = new FileReader()
|
||||
reader.onload = () => resolve(reader.result as string)
|
||||
reader.onerror = () => reject(reader.error)
|
||||
reader.readAsDataURL(file)
|
||||
})
|
||||
|
||||
type UploadImgCallBack = (urls: Array<{ url: string; alt: string; title: string }>) => void
|
||||
|
||||
const onUploadImg = async (files: Array<File>, callBack: UploadImgCallBack) => {
|
||||
if (!unref(isMarkdown)) {
|
||||
callBack([])
|
||||
return
|
||||
}
|
||||
|
||||
const { maxImageSize, maxDocumentImageSize } = unref(editorConfig)
|
||||
isAddingImages.value = true
|
||||
try {
|
||||
callBack(await pickImages(files, maxImageSize, maxDocumentImageSize))
|
||||
} finally {
|
||||
isAddingImages.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const pickImages = async (
|
||||
files: Array<File>,
|
||||
maxImageSize: number,
|
||||
maxDocumentImageSize: number
|
||||
): Promise<Array<{ url: string; alt: string; title: string }>> => {
|
||||
let usedSize = usedDocumentImageSize(currentContent) + unref(pendingImageSize)
|
||||
const accepted: Array<{ url: string; alt: string; title: string }> = []
|
||||
const tooBig: Array<string> = []
|
||||
const unreadable: Array<string> = []
|
||||
const doesNotFit: Array<string> = []
|
||||
|
||||
for (const file of files) {
|
||||
if (!file.type.startsWith('image/')) {
|
||||
continue
|
||||
}
|
||||
|
||||
if (file.size > maxImageSize) {
|
||||
tooBig.push(file.name)
|
||||
continue
|
||||
}
|
||||
|
||||
let dataUri: string
|
||||
try {
|
||||
dataUri = await readAsDataUrl(file)
|
||||
} catch {
|
||||
unreadable.push(file.name)
|
||||
continue
|
||||
}
|
||||
|
||||
if (usedSize + dataUri.length > maxDocumentImageSize) {
|
||||
doesNotFit.push(file.name)
|
||||
continue
|
||||
}
|
||||
|
||||
usedSize += dataUri.length
|
||||
pendingImageSize.value += dataUri.length
|
||||
accepted.push({ url: dataUri, alt: file.name, title: '' })
|
||||
}
|
||||
|
||||
if (tooBig.length) {
|
||||
showErrorMessage({
|
||||
title: $ngettext('Image is too big', 'Images are too big', tooBig.length),
|
||||
desc: $gettext('%{ files }. Max image size: %{ limit }.', {
|
||||
files: formatFileNames(tooBig),
|
||||
limit: formatSize(maxImageSize)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
if (doesNotFit.length) {
|
||||
showErrorMessage({
|
||||
title: $ngettext(
|
||||
'Image does not fit in this document',
|
||||
'Images do not fit in this document',
|
||||
doesNotFit.length
|
||||
),
|
||||
desc: $ngettext(
|
||||
'%{ files }. Only %{ remaining } left - remove an image or link the file instead.',
|
||||
'%{ files }. Only %{ remaining } left - remove an image or link the files instead.',
|
||||
doesNotFit.length,
|
||||
{
|
||||
files: formatFileNames(doesNotFit),
|
||||
remaining: formatSize(Math.max(maxDocumentImageSize - usedSize, 0))
|
||||
}
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
if (unreadable.length) {
|
||||
showErrorMessage({
|
||||
title: $ngettext('Image could not be read', 'Images could not be read', unreadable.length),
|
||||
desc: formatFileNames(unreadable)
|
||||
})
|
||||
}
|
||||
|
||||
return accepted
|
||||
}
|
||||
|
||||
watch(
|
||||
() => currentContent,
|
||||
() => {
|
||||
pendingImageSize.value = 0
|
||||
}
|
||||
)
|
||||
|
||||
onMounted(async () => {
|
||||
if (isReadOnly) {
|
||||
return
|
||||
@@ -160,6 +308,12 @@ config({
|
||||
},
|
||||
mermaid: {
|
||||
instance: mermaid
|
||||
},
|
||||
// The crop entry is hidden (see the CSS below), so Cropper is never constructed.
|
||||
// md-editor-v3 CDN-injects cropperjs from unpkg unless an instance is registered
|
||||
// (composition.ts: noCropperScript) — this stub keeps that request from being made.
|
||||
cropper: {
|
||||
instance: class {} as never
|
||||
}
|
||||
},
|
||||
markdownItConfig(md) {
|
||||
@@ -224,6 +378,14 @@ config({
|
||||
}
|
||||
}
|
||||
|
||||
.footer-slot {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.625rem;
|
||||
vertical-align: middle;
|
||||
padding-inline-start: 10px;
|
||||
}
|
||||
|
||||
.footer-links {
|
||||
display: inline-flex;
|
||||
gap: 0.625rem;
|
||||
@@ -235,6 +397,15 @@ config({
|
||||
.md-editor-code-head {
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
// Hides the "Crop And Upload" entry: cropping is dropped until users ask for it.
|
||||
// md-editor-v3 hardcodes the three image-dropdown entries with identical classes and
|
||||
// exposes no prop to hide one (still true in v7), so position is the only handle.
|
||||
// Requiring :nth-child(3) and :last-child together means an upstream reorder stops the
|
||||
// selector matching, showing all entries rather than hiding the wrong one.
|
||||
.md-editor-menu-item-image:nth-child(3):last-child {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
.toastui-editor-tabs {
|
||||
|
||||
@@ -2,6 +2,9 @@ export const EVENT_TROW_MOUNTED = 'rowMounted'
|
||||
export const EVENT_FILE_DROPPED = 'fileDropped'
|
||||
export const EVENT_TROW_CONTEXTMENU = 'contextmenuClicked'
|
||||
|
||||
export const DEFAULT_MAX_IMAGE_SIZE = 2 * 1000 * 1000
|
||||
export const DEFAULT_MAX_DOCUMENT_IMAGE_SIZE = 10 * 1000 * 1000
|
||||
|
||||
export abstract class ImageDimension {
|
||||
static readonly Thumbnail: [number, number] = [36, 36]
|
||||
static readonly Tile: [number, number] = [1000, 1000]
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
import { defineComponent, nextTick } from 'vue'
|
||||
import { defaultPlugins, mount } from '@ownclouders/web-test-helpers'
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
import { config } from 'md-editor-v3'
|
||||
import { useMessages } from '../../../../src/composables'
|
||||
import TextEditor from '../../../../src/components/TextEditor/TextEditor.vue'
|
||||
import { AppConfigObject } from '../../../../src/apps'
|
||||
|
||||
vi.mock('md-editor-v3', () => ({
|
||||
config: vi.fn(),
|
||||
MdEditor: defineComponent({
|
||||
name: 'MdEditor',
|
||||
emits: ['on-upload-img', 'on-change'],
|
||||
template: '<div><slot name="defFooters" /></div>'
|
||||
}),
|
||||
MdPreview: defineComponent({
|
||||
name: 'MdPreview',
|
||||
template: '<div />'
|
||||
})
|
||||
}))
|
||||
|
||||
// FileReader returns a URI where the base64 section is exactly file.size 'A' characters.
|
||||
// URI length = file.size + len('data:<type>;base64,'), making lengths predictable.
|
||||
class MockFileReader {
|
||||
onload: (() => void) | null = null
|
||||
onerror: ((e: ErrorEvent) => void) | null = null
|
||||
result: string | null = null
|
||||
|
||||
readAsDataURL(file: File) {
|
||||
this.result = `data:${file.type};base64,${'A'.repeat(file.size)}`
|
||||
queueMicrotask(() => this.onload?.())
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('FileReader', MockFileReader)
|
||||
})
|
||||
|
||||
const makeFile = (name: string, size: number, type = 'image/png') =>
|
||||
new File([new Uint8Array(size)], name, { type })
|
||||
|
||||
const contentWithInlinedBytes = (totalEncodedBytes: number) =>
|
||||
`})`
|
||||
|
||||
function getWrapper(
|
||||
overrides: {
|
||||
currentContent?: string
|
||||
markdownMode?: boolean
|
||||
applicationConfig?: AppConfigObject
|
||||
resource?: any
|
||||
isReadOnly?: boolean
|
||||
} = {}
|
||||
) {
|
||||
return mount(TextEditor, {
|
||||
props: {
|
||||
currentContent: '',
|
||||
markdownMode: true,
|
||||
isReadOnly: false,
|
||||
applicationConfig: { maxImageSize: 200, maxDocumentImageSize: 500 },
|
||||
...overrides
|
||||
},
|
||||
global: { plugins: [...defaultPlugins()] }
|
||||
})
|
||||
}
|
||||
|
||||
async function triggerUpload(
|
||||
wrapper: ReturnType<typeof getWrapper>,
|
||||
files: File[]
|
||||
): Promise<ReturnType<typeof vi.fn>> {
|
||||
const callback = vi.fn()
|
||||
const mdEditor = wrapper.findComponent({ name: 'MdEditor' })
|
||||
await mdEditor.vm.$emit('on-upload-img', files, callback)
|
||||
await flushPromises()
|
||||
return callback
|
||||
}
|
||||
|
||||
describe('TextEditor — image upload', () => {
|
||||
it('counts images already in the document against the budget', async () => {
|
||||
const intoEmpty = await triggerUpload(getWrapper(), [makeFile('a.png', 100)])
|
||||
const [accepted] = intoEmpty.mock.calls[0]
|
||||
expect(accepted).toHaveLength(1)
|
||||
expect(accepted[0].url).toContain('data:image/png;base64,')
|
||||
|
||||
// The same file must be rejected once the document already holds enough to leave no room.
|
||||
const intoFilled = await triggerUpload(
|
||||
getWrapper({ currentContent: contentWithInlinedBytes(400) }),
|
||||
[makeFile('a.png', 100)]
|
||||
)
|
||||
expect(intoFilled).toHaveBeenCalledWith([])
|
||||
})
|
||||
|
||||
it('rejects a file that exceeds the per-image size cap', async () => {
|
||||
const wrapper = getWrapper()
|
||||
const callback = await triggerUpload(wrapper, [makeFile('big.png', 250)])
|
||||
|
||||
expect(callback).toHaveBeenCalledWith([])
|
||||
const { showErrorMessage } = useMessages()
|
||||
expect(showErrorMessage).toHaveBeenCalledTimes(1)
|
||||
expect(vi.mocked(showErrorMessage).mock.calls[0][0].desc).toContain('big.png')
|
||||
expect(vi.mocked(showErrorMessage).mock.calls[0][0].desc).toContain('200')
|
||||
})
|
||||
|
||||
it('reports one message per reason rather than one per rejected file', async () => {
|
||||
await triggerUpload(getWrapper(), [
|
||||
makeFile('a.png', 250),
|
||||
makeFile('b.png', 250),
|
||||
makeFile('c.png', 250),
|
||||
makeFile('d.png', 250)
|
||||
])
|
||||
|
||||
const { showErrorMessage } = useMessages()
|
||||
expect(showErrorMessage).toHaveBeenCalledTimes(1)
|
||||
const { desc } = vi.mocked(showErrorMessage).mock.calls[0][0]
|
||||
// The file list is truncated so a large drop cannot produce an unbounded message.
|
||||
expect(desc).toContain('a.png, b.png, c.png')
|
||||
expect(desc).not.toContain('d.png')
|
||||
expect(desc).toContain('1')
|
||||
})
|
||||
|
||||
it('rejects a file that would push the document over budget and reports remaining space', async () => {
|
||||
const existingBytes = 400
|
||||
const wrapper = getWrapper({ currentContent: contentWithInlinedBytes(existingBytes) })
|
||||
const callback = await triggerUpload(wrapper, [makeFile('over.png', 150)])
|
||||
|
||||
expect(callback).toHaveBeenCalledWith([])
|
||||
// 400 bytes of base64 plus the 22-byte data URI prefix leaves 78 of the 500-byte budget.
|
||||
const { showErrorMessage } = useMessages()
|
||||
expect(vi.mocked(showErrorMessage).mock.calls[0][0].desc).toContain('78')
|
||||
})
|
||||
|
||||
it('accepts files that fit and rejects those that would overflow in the same drop', async () => {
|
||||
const wrapper = getWrapper({
|
||||
applicationConfig: { maxImageSize: 200, maxDocumentImageSize: 300 }
|
||||
})
|
||||
const callback = await triggerUpload(wrapper, [
|
||||
makeFile('f1.png', 100),
|
||||
makeFile('f2.png', 100),
|
||||
makeFile('f3.png', 100)
|
||||
])
|
||||
|
||||
const [accepted] = callback.mock.calls[0]
|
||||
expect(accepted).toHaveLength(2)
|
||||
expect(useMessages().showErrorMessage).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('keeps the document budget hard across uploads the parent has not echoed back yet', async () => {
|
||||
const wrapper = getWrapper({
|
||||
applicationConfig: { maxImageSize: 200, maxDocumentImageSize: 200 }
|
||||
})
|
||||
|
||||
// 100 bytes plus the 22-byte data URI prefix fits; a second one of the same size does not.
|
||||
const first = await triggerUpload(wrapper, [makeFile('f1.png', 100)])
|
||||
expect(first.mock.calls[0][0]).toHaveLength(1)
|
||||
|
||||
// currentContent is still '' here - the parent has not propagated the insertion.
|
||||
const second = await triggerUpload(wrapper, [makeFile('f2.png', 100)])
|
||||
expect(second).toHaveBeenCalledWith([])
|
||||
expect(useMessages().showErrorMessage).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('shows a busy cue while the picked images are being read', async () => {
|
||||
const wrapper = getWrapper()
|
||||
const mdEditor = wrapper.findComponent({ name: 'MdEditor' })
|
||||
|
||||
mdEditor.vm.$emit('on-upload-img', [makeFile('a.png', 100)], vi.fn())
|
||||
await nextTick()
|
||||
expect(wrapper.find('.footer-image-progress').exists()).toBe(true)
|
||||
|
||||
await flushPromises()
|
||||
await nextTick()
|
||||
expect(wrapper.find('.footer-image-progress').exists()).toBe(false)
|
||||
})
|
||||
|
||||
it('data URIs survive the DOMPurify sanitize call used by the editor', () => {
|
||||
const wrapper = getWrapper()
|
||||
const sanitize = wrapper.findComponent({ name: 'MdEditor' }).vm.$attrs.sanitize as (
|
||||
html: string
|
||||
) => string
|
||||
const html = '<div><img src="data:image/png;base64,ABC123==" alt="test"></div>'
|
||||
expect(sanitize(html)).toContain('data:image/png;base64,ABC123==')
|
||||
})
|
||||
|
||||
it('does not process uploads when isMarkdown is false', async () => {
|
||||
const wrapper = getWrapper({
|
||||
markdownMode: false,
|
||||
applicationConfig: { showPreviewOnlyMd: true, maxImageSize: 200, maxDocumentImageSize: 500 }
|
||||
})
|
||||
const callback = await triggerUpload(wrapper, [makeFile('img.png', 50)])
|
||||
|
||||
expect(callback).toHaveBeenCalledWith([])
|
||||
expect(useMessages().showErrorMessage).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('silently skips non-image files without a validation message', async () => {
|
||||
const wrapper = getWrapper()
|
||||
const callback = await triggerUpload(wrapper, [makeFile('doc.txt', 10, 'text/plain')])
|
||||
|
||||
expect(callback).toHaveBeenCalledWith([])
|
||||
expect(useMessages().showErrorMessage).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
// md-editor-v3 injects cropperjs from unpkg.com on mount unless an instance is
|
||||
// registered, so dropping this registration silently adds an external request.
|
||||
it('registers a cropper instance so md-editor-v3 skips the unpkg CDN injection', () => {
|
||||
getWrapper()
|
||||
|
||||
const [{ editorExtensions }] = vi.mocked(config).mock.calls.at(-1)
|
||||
expect(editorExtensions.cropper.instance).toBeDefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,49 @@
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
import { nextTick } from 'vue'
|
||||
import { defaultPlugins, mount } from '@ownclouders/web-test-helpers'
|
||||
import TextEditor from '../../../../src/components/TextEditor/TextEditor.vue'
|
||||
|
||||
// Mounts the real md-editor-v3 rather than the stub used by TextEditor.spec.ts: the `footers`
|
||||
// prop picks defFooters slot children by index, so anything that shifts that index makes the
|
||||
// footer silently render the wrong node. Only the real Footer component exercises that lookup.
|
||||
|
||||
class MockFileReader {
|
||||
onload: (() => void) | null = null
|
||||
onerror: (() => void) | null = null
|
||||
result: string | null = null
|
||||
readAsDataURL(file: File) {
|
||||
this.result = `data:${file.type};base64,${'A'.repeat(file.size)}`
|
||||
queueMicrotask(() => this.onload?.())
|
||||
}
|
||||
}
|
||||
|
||||
describe('TextEditor - footer slot', () => {
|
||||
it('renders the slot content in the footer', async () => {
|
||||
vi.stubGlobal('FileReader', MockFileReader)
|
||||
const wrapper = mount(TextEditor, {
|
||||
props: {
|
||||
currentContent: '',
|
||||
markdownMode: true,
|
||||
isReadOnly: false,
|
||||
applicationConfig: { maxImageSize: 200, maxDocumentImageSize: 500 }
|
||||
},
|
||||
global: { plugins: [...defaultPlugins()] }
|
||||
})
|
||||
await flushPromises()
|
||||
expect(wrapper.find('.md-editor-footer .footer-links').exists()).toBe(true)
|
||||
|
||||
const md = wrapper.findComponent({ name: 'MdEditorV3' })
|
||||
md.vm.$emit(
|
||||
'on-upload-img',
|
||||
[new File([new Uint8Array(100)], 'a.png', { type: 'image/png' })],
|
||||
() => {}
|
||||
)
|
||||
await nextTick()
|
||||
expect(wrapper.find('.md-editor-footer .footer-image-progress').exists()).toBe(true)
|
||||
|
||||
await flushPromises()
|
||||
await nextTick()
|
||||
expect(wrapper.find('.md-editor-footer .footer-image-progress').exists()).toBe(false)
|
||||
expect(wrapper.find('.md-editor-footer .footer-links').exists()).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,69 @@
|
||||
import { test } from '../../environment/test'
|
||||
import * as api from '../../steps/api/api'
|
||||
import * as ui from '../../steps/ui/index'
|
||||
import { application } from '../../environment/constants'
|
||||
|
||||
test.describe('Markdown editor inlines images as base64', { tag: '@predefined-users' }, () => {
|
||||
test.beforeEach(async () => {
|
||||
// Given "Admin" creates following user using API
|
||||
// | id |
|
||||
// | Alice |
|
||||
await api.usersHaveBeenCreated({ stepUser: 'Admin', users: ['Alice'] })
|
||||
|
||||
// And "Alice" logs in
|
||||
await ui.userLogsIn({ stepUser: 'Alice' })
|
||||
|
||||
// And "Alice" creates the following resources
|
||||
// | resource | type | content |
|
||||
// | notes.md | mdFile | # image test |
|
||||
await ui.userCreatesResources({
|
||||
stepUser: 'Alice',
|
||||
resources: [{ name: 'notes.md', type: 'mdFile', content: '# image test' }]
|
||||
})
|
||||
|
||||
// And "Alice" opens the following file in texteditor
|
||||
// | resource |
|
||||
// | notes.md |
|
||||
// (creating the file saves and closes the editor, so it has to be reopened)
|
||||
await ui.userOpensResourceInViewer({
|
||||
stepUser: 'Alice',
|
||||
resource: 'notes.md',
|
||||
viewer: application.textEditor
|
||||
})
|
||||
})
|
||||
|
||||
test.afterEach(async () => {
|
||||
// And "Alice" logs out
|
||||
await ui.userLogsOut({ stepUser: 'Alice' })
|
||||
})
|
||||
|
||||
test('picked image is inlined into the document', async () => {
|
||||
// When "Alice" picks the image "testavatar.png" in the markdown editor
|
||||
await ui.userPicksImageInMarkdownEditor({ stepUser: 'Alice', image: 'testavatar.png' })
|
||||
|
||||
// Then "Alice" should see the image inlined in the markdown editor
|
||||
await ui.userShouldSeeInlinedImageInMarkdownEditor({ stepUser: 'Alice' })
|
||||
})
|
||||
|
||||
test('image above the per-image limit is rejected', async () => {
|
||||
// When "Alice" picks an image of 2500000 bytes in the markdown editor
|
||||
await ui.userPicksOversizedImageInMarkdownEditor({ stepUser: 'Alice', sizeInBytes: 2500000 })
|
||||
|
||||
// Then "Alice" should see the image rejected in the markdown editor
|
||||
// | image | limit |
|
||||
// | oversized.png | 2 MB |
|
||||
await ui.userShouldSeeImageRejectionInMarkdownEditor({
|
||||
stepUser: 'Alice',
|
||||
image: 'oversized.png',
|
||||
limit: '2 MB'
|
||||
})
|
||||
|
||||
// And "Alice" should not see an image inlined in the markdown editor
|
||||
await ui.userShouldNotSeeInlinedImageInMarkdownEditor({ stepUser: 'Alice' })
|
||||
})
|
||||
|
||||
test('crop and upload is not offered', async () => {
|
||||
// Then "Alice" should not see the crop option in the markdown editor
|
||||
await ui.userShouldNotSeeCropOptionInMarkdownEditor({ stepUser: 'Alice' })
|
||||
})
|
||||
})
|
||||
@@ -482,6 +482,102 @@ export async function userClosesFileViewer({ stepUser }: { stepUser: string }):
|
||||
await editor.close(page)
|
||||
}
|
||||
|
||||
export async function userPicksImageInMarkdownEditor({
|
||||
stepUser,
|
||||
image
|
||||
}: {
|
||||
stepUser: string
|
||||
image: string
|
||||
}): Promise<void> {
|
||||
const world = getWorld()
|
||||
const { page } = world.actorsEnvironment.getActor({ key: stepUser })
|
||||
await editor.waitForMarkdownEditor(page)
|
||||
await editor.pickMarkdownImage(page, world.filesEnvironment.getFile({ name: image }).path)
|
||||
}
|
||||
|
||||
export async function userPicksOversizedImageInMarkdownEditor({
|
||||
stepUser,
|
||||
sizeInBytes
|
||||
}: {
|
||||
stepUser: string
|
||||
sizeInBytes: number
|
||||
}): Promise<void> {
|
||||
const world = getWorld()
|
||||
const { page } = world.actorsEnvironment.getActor({ key: stepUser })
|
||||
await editor.waitForMarkdownEditor(page)
|
||||
// Only file.type and file.size decide the rejection, so an in-memory payload avoids
|
||||
// committing a multi-megabyte fixture.
|
||||
await editor.pickMarkdownImage(page, {
|
||||
name: 'oversized.png',
|
||||
mimeType: 'image/png',
|
||||
buffer: Buffer.alloc(sizeInBytes)
|
||||
})
|
||||
}
|
||||
|
||||
export async function userShouldSeeInlinedImageInMarkdownEditor({
|
||||
stepUser
|
||||
}: {
|
||||
stepUser: string
|
||||
}): Promise<void> {
|
||||
const world = getWorld()
|
||||
const { page } = world.actorsEnvironment.getActor({ key: stepUser })
|
||||
// The markdown source only exposes the data URI through the shortener's title attribute.
|
||||
await expect(editor.markdownShortenedTokenLocator(page)).toHaveAttribute(
|
||||
'title',
|
||||
/^data:image\/png;base64,/
|
||||
)
|
||||
await expect(editor.markdownPreviewImageLocator(page)).toBeVisible()
|
||||
}
|
||||
|
||||
export async function userShouldNotSeeInlinedImageInMarkdownEditor({
|
||||
stepUser
|
||||
}: {
|
||||
stepUser: string
|
||||
}): Promise<void> {
|
||||
const world = getWorld()
|
||||
const { page } = world.actorsEnvironment.getActor({ key: stepUser })
|
||||
await expect(editor.markdownPreviewImageLocator(page)).toHaveCount(0)
|
||||
await expect(editor.markdownShortenedTokenLocator(page)).toHaveCount(0)
|
||||
}
|
||||
|
||||
export async function userShouldSeeImageRejectionInMarkdownEditor({
|
||||
stepUser,
|
||||
image,
|
||||
limit
|
||||
}: {
|
||||
stepUser: string
|
||||
image: string
|
||||
limit: string
|
||||
}): Promise<void> {
|
||||
const world = getWorld()
|
||||
const { page } = world.actorsEnvironment.getActor({ key: stepUser })
|
||||
const notification = editor.imageRejectionNotificationLocator(page)
|
||||
await expect(notification).toBeVisible()
|
||||
await expect(notification.locator('.oc-notification-message-title')).toHaveText(
|
||||
'Image is too big'
|
||||
)
|
||||
await expect(notification.locator('.oc-notification-message-content')).toHaveText(
|
||||
`${image}. Max image size: ${limit}.`
|
||||
)
|
||||
}
|
||||
|
||||
export async function userShouldNotSeeCropOptionInMarkdownEditor({
|
||||
stepUser
|
||||
}: {
|
||||
stepUser: string
|
||||
}): Promise<void> {
|
||||
const world = getWorld()
|
||||
const { page } = world.actorsEnvironment.getActor({ key: stepUser })
|
||||
await editor.openMarkdownImageMenu(page)
|
||||
|
||||
// md-editor-v3 always renders three image entries; TextEditor.vue hides the third
|
||||
// ("Crop And Upload") with `.md-editor-menu-item-image:nth-child(3):last-child`.
|
||||
const items = editor.markdownImageMenuItemsLocator(page)
|
||||
await expect(items).toHaveCount(3)
|
||||
await expect(items.filter({ visible: true })).toHaveCount(2)
|
||||
await expect(items.filter({ visible: true, hasText: /crop/i })).toHaveCount(0)
|
||||
}
|
||||
|
||||
export async function userDeletesResources({
|
||||
stepUser,
|
||||
actionType = fileAction.sideBarPanel,
|
||||
|
||||
@@ -8,6 +8,20 @@ const texEditor = '#text-editor'
|
||||
const pdfViewer = '#pdf-viewer'
|
||||
const imageViewer = '.stage'
|
||||
|
||||
const markdownEditor = '#text-editor-component'
|
||||
// md-editor-v3's ImageDropdown renders its hidden file input as `${editorId}-toolbar-wrapper_label`.
|
||||
const markdownImageInput = `${markdownEditor}-toolbar-wrapper_label`
|
||||
// The aria-label is md-editor-v3's toolbarTips.image, which is "image" in en-US.
|
||||
const markdownImageButton = `${markdownEditor} button.md-editor-toolbar-item[aria-label="image"]`
|
||||
const markdownImageMenuItem = `${markdownEditor} .md-editor-menu-item-image`
|
||||
// CodeMirror's linkShortener extension replaces any token over 30 characters with "...",
|
||||
// keeping the original in the title attribute - so an inlined data URI never appears as text.
|
||||
const markdownShortenedToken = `${markdownEditor} .cm-short-text`
|
||||
const markdownPreviewImage = `${markdownEditor} .md-editor-preview img[src^="data:"]`
|
||||
// Image rejections are reported through the app's notification store, so they render in the
|
||||
// global notification stack rather than inside the editor.
|
||||
const imageRejectionNotification = 'div.oc-notification .oc-notification-message-danger'
|
||||
|
||||
export const close = async (page: Page): Promise<void> => {
|
||||
await Promise.all([
|
||||
page.waitForURL(/.*\/files\/(spaces|shares|link|search)\/.*/),
|
||||
@@ -38,6 +52,33 @@ export const save = async (page: Page): Promise<void> => {
|
||||
)
|
||||
}
|
||||
|
||||
export const waitForMarkdownEditor = async (page: Page): Promise<void> => {
|
||||
await page.locator(markdownImageInput).waitFor({ state: 'attached' })
|
||||
}
|
||||
|
||||
export const pickMarkdownImage = async (
|
||||
page: Page,
|
||||
file: { name: string; mimeType: string; buffer: Buffer } | string
|
||||
): Promise<void> => {
|
||||
await page.locator(markdownImageInput).setInputFiles(file)
|
||||
}
|
||||
|
||||
export const openMarkdownImageMenu = async (page: Page): Promise<void> => {
|
||||
await page.locator(markdownImageButton).click()
|
||||
}
|
||||
|
||||
export const markdownImageMenuItemsLocator = (page: Page): Locator =>
|
||||
page.locator(markdownImageMenuItem)
|
||||
|
||||
export const markdownShortenedTokenLocator = (page: Page): Locator =>
|
||||
page.locator(markdownShortenedToken)
|
||||
|
||||
export const markdownPreviewImageLocator = (page: Page): Locator =>
|
||||
page.locator(markdownPreviewImage)
|
||||
|
||||
export const imageRejectionNotificationLocator = (page: Page): Locator =>
|
||||
page.locator(imageRejectionNotification)
|
||||
|
||||
export const fileViewerLocator = ({
|
||||
page,
|
||||
fileViewerType
|
||||
|
||||
Reference in new issue
Block a user