Resolve "Copying ordered list to new comment becomes unordered"

This commit is contained in:
Jan Beckmann 2018-06-27 08:47:29 +00:00 committed by Phil Hughes
parent 87f7597a4f
commit 351d5f3e36
3 changed files with 74 additions and 1 deletions

View file

@ -189,12 +189,25 @@ export const getParameterByName = (name, urlToParse) => {
return decodeURIComponent(results[2].replace(/\+/g, ' '));
};
const handleSelectedRange = (range) => {
const container = range.commonAncestorContainer;
// add context to fragment if needed
if (container.tagName === 'OL') {
const parentContainer = document.createElement(container.tagName);
parentContainer.appendChild(range.cloneContents());
return parentContainer;
}
return range.cloneContents();
};
export const getSelectedFragment = () => {
const selection = window.getSelection();
if (selection.rangeCount === 0) return null;
const documentFragment = document.createDocumentFragment();
for (let i = 0; i < selection.rangeCount; i += 1) {
documentFragment.appendChild(selection.getRangeAt(i).cloneContents());
const range = selection.getRangeAt(i);
documentFragment.appendChild(handleSelectedRange(range));
}
if (documentFragment.textContent.length === 0) return null;

View file

@ -0,0 +1,5 @@
---
title: Keep lists ordered when copying only list items
merge_request: 18522
author: Jan Beckmann
type: fixed

View file

@ -44,4 +44,59 @@ describe('CopyAsGFM', () => {
callPasteGFM();
});
});
describe('CopyAsGFM.copyGFM', () => {
// Stub getSelection to return a purpose-built object.
const stubSelection = (html, parentNode) => ({
getRangeAt: () => ({
commonAncestorContainer: { tagName: parentNode },
cloneContents: () => {
const fragment = document.createDocumentFragment();
const node = document.createElement('div');
node.innerHTML = html;
Array.from(node.childNodes).forEach((item) => fragment.appendChild(item));
return fragment;
},
}),
rangeCount: 1,
});
const clipboardData = {
setData() {},
};
const simulateCopy = () => {
const e = {
originalEvent: {
clipboardData,
},
preventDefault() {},
stopPropagation() {},
};
CopyAsGFM.copyAsGFM(e, CopyAsGFM.transformGFMSelection);
return clipboardData;
};
beforeEach(() => spyOn(clipboardData, 'setData'));
describe('list handling', () => {
it('uses correct gfm for unordered lists', () => {
const selection = stubSelection('<li>List Item1</li><li>List Item2</li>\n', 'UL');
spyOn(window, 'getSelection').and.returnValue(selection);
simulateCopy();
const expectedGFM = '- List Item1\n- List Item2';
expect(clipboardData.setData).toHaveBeenCalledWith('text/x-gfm', expectedGFM);
});
it('uses correct gfm for ordered lists', () => {
const selection = stubSelection('<li>List Item1</li><li>List Item2</li>\n', 'OL');
spyOn(window, 'getSelection').and.returnValue(selection);
simulateCopy();
const expectedGFM = '1. List Item1\n1. List Item2';
expect(clipboardData.setData).toHaveBeenCalledWith('text/x-gfm', expectedGFM);
});
});
});
});