Commit 00294fb5 authored by Simon Knox's avatar Simon Knox

Merge branch '218531-determine-image-relative-paths' into 'master'

Resolve image relative paths

See merge request gitlab-org/gitlab!46208
parents 41f8575f 6543c30e
......@@ -37,6 +37,14 @@ export default {
required: false,
default: '',
},
branch: {
type: String,
required: true,
},
baseUrl: {
type: String,
required: true,
},
mounts: {
type: Array,
required: true,
......@@ -75,7 +83,7 @@ export default {
return this.editorMode === EDITOR_TYPES.wysiwyg;
},
customRenderers() {
const imageRenderer = renderImage.build(this.mounts, this.project);
const imageRenderer = renderImage.build(this.mounts, this.project, this.branch, this.baseUrl);
return {
image: [imageRenderer],
};
......
......@@ -6,6 +6,8 @@ query appData {
sourcePath
username
returnUrl
branch
baseUrl
mounts {
source
target
......
......@@ -26,6 +26,8 @@ type AppData {
returnUrl: String
sourcePath: String!
username: String!
branch: String!
baseUrl: String!
mounts: [Mount]!
imageUploadPath: String!
}
......
......@@ -9,6 +9,7 @@ const initStaticSiteEditor = el => {
isSupportedContent,
path: sourcePath,
baseUrl,
branch,
namespace,
project,
mergeRequestsIllustrationPath,
......@@ -27,6 +28,8 @@ const initStaticSiteEditor = el => {
hasSubmittedChanges: false,
project: `${namespace}/${project}`,
mounts: JSON.parse(mounts), // NOTE that the object in 'mounts' is a JSON string from the data attribute, so it must be parsed into an object.
branch,
baseUrl,
returnUrl,
sourcePath,
username,
......
......@@ -139,6 +139,8 @@ export default {
:saving-changes="isSavingChanges"
:return-url="appData.returnUrl"
:mounts="appData.mounts"
:branch="appData.branch"
:base-url="appData.baseUrl"
:project="appData.project"
:image-root="appData.imageUploadPath"
@submit="onPrepareSubmit"
......
import { isAbsolute, getBaseURL, joinPaths } from '~/lib/utils/url_utility';
const canRender = ({ type }) => type === 'image';
// NOTE: the `metadata` is not used yet, but will be used in a follow-up iteration
// To be removed with the next iteration of https://gitlab.com/gitlab-org/gitlab/-/issues/218531
// eslint-disable-next-line no-unused-vars
let metadata;
const render = (node, { skipChildren }) => {
skipChildren();
const isRelativeToCurrentDirectory = basePath => !basePath.startsWith('/');
const extractSourceDirectory = url => {
const sourceDir = /^(.+)\/([^/]+)$/.exec(url); // Extracts the base path and fileName from an image path
return sourceDir || [null, null, url]; // If no source directory was extracted it means only a fileName was specified (e.g. url='file.png')
};
const parseCurrentDirectory = basePath => {
const baseUrl = decodeURIComponent(metadata.baseUrl);
const sourceDirectory = extractSourceDirectory(baseUrl)[1];
const currentDirectory = sourceDirectory.split(`/-/sse/${metadata.branch}`)[1];
return joinPaths(currentDirectory, basePath);
};
// For more context around this logic, please see the following comment:
// https://gitlab.com/gitlab-org/gitlab/-/issues/241166#note_409413500
const generateSourceDirectory = basePath => {
let sourceDir = '';
let defaultSourceDir = '';
if (!basePath || isRelativeToCurrentDirectory(basePath)) {
return parseCurrentDirectory(basePath);
}
if (!metadata.mounts.length) {
return basePath;
}
// To be removed with the next iteration of https://gitlab.com/gitlab-org/gitlab/-/issues/218531
// TODO resolve relative paths
metadata.mounts.forEach(({ source, target }) => {
const hasTarget = target !== '';
if (hasTarget && basePath.includes(target)) {
sourceDir = source;
} else if (!hasTarget) {
defaultSourceDir = joinPaths(source, basePath);
}
});
return sourceDir || defaultSourceDir;
};
const resolveFullPath = originalSrc => {
if (isAbsolute(originalSrc)) {
return originalSrc;
}
const sourceDirectory = extractSourceDirectory(originalSrc);
const [, basePath, fileName] = sourceDirectory;
const sourceDir = generateSourceDirectory(basePath);
return joinPaths(getBaseURL(), metadata.project, '/-/raw/', metadata.branch, sourceDir, fileName);
};
const render = ({ destination: originalSrc, firstChild }, { skipChildren }) => {
skipChildren();
return {
type: 'openTag',
tagName: 'img',
selfClose: true,
attributes: {
src: node.destination,
alt: node.firstChild.literal,
'data-original-src': !isAbsolute(originalSrc) ? originalSrc : '',
src: resolveFullPath(originalSrc),
alt: firstChild.literal,
},
};
};
const build = (mounts, project) => {
metadata = { mounts, project };
const build = (mounts = [], project, branch, baseUrl) => {
metadata = { mounts, project, branch, baseUrl };
return { canRender, render };
};
......
......@@ -99,6 +99,10 @@ const buildHTMLToMarkdownRender = (baseRenderer, formattingPreferences = {}) =>
? `\n\n${node.innerText}\n\n`
: baseRenderer.convert(node, subContent);
},
IMG(node) {
const { originalSrc } = node.dataset;
return `![${node.alt}](${originalSrc || node.src})`;
},
};
};
......
---
title: Determine image relative paths
merge_request: 46208
author:
type: added
......@@ -17,6 +17,8 @@ import {
returnUrl,
mounts,
project,
branch,
baseUrl,
imageRoot,
} from '../mock_data';
......@@ -36,6 +38,8 @@ describe('~/static_site_editor/components/edit_area.vue', () => {
returnUrl,
mounts,
project,
branch,
baseUrl,
imageRoot,
savingChanges,
...propsData,
......
......@@ -75,9 +75,17 @@ export const images = new Map([
export const mounts = [
{
source: 'some/source/',
source: 'default/source/',
target: '',
},
{
source: 'source/with/target',
target: 'target',
},
];
export const branch = 'master';
export const baseUrl = '/user1/project1/-/sse/master%2Ftest.md';
export const imageRoot = 'source/images/';
......@@ -24,6 +24,8 @@ import {
trackingCategory,
images,
mounts,
branch,
baseUrl,
imageRoot,
} from '../mock_data';
......@@ -44,6 +46,8 @@ describe('static_site_editor/pages/home', () => {
username,
sourcePath,
mounts,
branch,
baseUrl,
imageUploadPath: imageRoot,
};
const hasSubmittedChangesMutationPayload = {
......
import imageRenderer from '~/static_site_editor/services/renderers/render_image';
import { mounts, project } from '../../mock_data';
import { mounts, project, branch, baseUrl } from '../../mock_data';
describe('rich_content_editor/renderers/render_image', () => {
let renderer;
beforeEach(() => {
renderer = imageRenderer.build(mounts, project);
renderer = imageRenderer.build(mounts, project, branch, baseUrl);
});
describe('build', () => {
......@@ -27,37 +27,38 @@ describe('rich_content_editor/renderers/render_image', () => {
});
describe('render', () => {
let context;
let result;
const skipChildren = jest.fn();
beforeEach(() => {
it.each`
destination | isAbsolute | src
${'http://test.host/absolute/path/to/image.png'} | ${true} | ${'http://test.host/absolute/path/to/image.png'}
${'/relative/path/to/image.png'} | ${false} | ${'http://test.host/user1/project1/-/raw/master/default/source/relative/path/to/image.png'}
${'/target/image.png'} | ${false} | ${'http://test.host/user1/project1/-/raw/master/source/with/target/image.png'}
${'relative/to/current/image.png'} | ${false} | ${'http://test.host/user1/project1/-/raw/master/relative/to/current/image.png'}
${'./relative/to/current/image.png'} | ${false} | ${'http://test.host/user1/project1/-/raw/master/./relative/to/current/image.png'}
${'../relative/to/current/image.png'} | ${false} | ${'http://test.host/user1/project1/-/raw/master/../relative/to/current/image.png'}
`('returns an image with the correct attributes', ({ destination, isAbsolute, src }) => {
const skipChildren = jest.fn();
const context = { skipChildren };
const node = {
destination: '/some/path/image.png',
destination,
firstChild: {
type: 'img',
literal: 'Some Image',
},
};
const result = renderer.render(node, context);
context = { skipChildren };
result = renderer.render(node, context);
});
it('invokes `skipChildren`', () => {
expect(skipChildren).toHaveBeenCalled();
});
it('returns an image', () => {
expect(result).toEqual({
type: 'openTag',
tagName: 'img',
selfClose: true,
attributes: {
src: '/some/path/image.png',
'data-original-src': !isAbsolute ? destination : '',
src,
alt: 'Some Image',
},
});
expect(skipChildren).toHaveBeenCalled();
});
});
});
......@@ -189,4 +189,30 @@ describe('rich_content_editor/services/html_to_markdown_renderer', () => {
expect(htmlToMarkdownRenderer['PRE CODE'](node, subContent)).toBe(originalConverterResult);
});
});
describe('IMG', () => {
const originalSrc = 'path/to/image.png';
const alt = 'alt text';
let node;
beforeEach(() => {
node = document.createElement('img');
node.alt = alt;
node.src = originalSrc;
});
it('returns an image with its original src of the `original-src` attribute is preset', () => {
node.dataset.originalSrc = originalSrc;
node.src = 'modified/path/to/image.png';
htmlToMarkdownRenderer = buildHTMLToMarkdownRenderer(baseRenderer);
expect(htmlToMarkdownRenderer.IMG(node)).toBe(`![${alt}](${originalSrc})`);
});
it('fallback to `src` if no `original-src` is specified on the image', () => {
htmlToMarkdownRenderer = buildHTMLToMarkdownRenderer(baseRenderer);
expect(htmlToMarkdownRenderer.IMG(node)).toBe(`![${alt}](${originalSrc})`);
});
});
});
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment