Skip to content

The Unified and Autonomous Development Platform

Split text diff expander controls

Work Horse34b5a32ff848
diff --git a/e2e-test/specs/text-diff-expander.plan.md b/e2e-test/specs/text-diff-expander.plan.md
new file mode 100644
index 0000000000..e17aee7d2b
--- /dev/null
+++ b/e2e-test/specs/text-diff-expander.plan.md
@@ -0,0 +1,33 @@
+# Text Diff Expander Test Plan
+
+## Application Overview
+
+Text diffs collapse unchanged lines around changes. A middle collapsed region offers independent up, both, and down expansion, while file-edge regions keep one applicable control.
+
+## Test Scenarios
+
+### 1. Commit Diff Expansion
+
+**Seed:** `tests/text-diff-expander.spec.js` logs in as administrator, creates a project, and pushes a two-commit fixture with separated changes.
+
+#### 1.1. expand-a-middle-gap-by-direction
+
+**File:** `tests/text-diff-expander.spec.js`
+
+**Steps:**
+
+1. Open the fixture commit detail.
+ - expect: file-start and file-end gaps have one control.
+ - expect: the middle gap has three equal-width up, both, and down controls.
+ - expect: the skipped-line count appears on the middle control.
+2. Expand upward.
+ - expect: lines adjacent to the preceding hunk appear while lines adjacent to the following hunk do not change.
+3. Reload and expand downward.
+ - expect: lines adjacent to the following hunk appear while lines adjacent to the preceding hunk do not change.
+4. Reload and expand both ways.
+ - expect: context appears on both sides of the hidden gap.
+5. Repeatedly expand upward until that direction is exhausted.
+ - expect: the row becomes one control for the remaining direction.
+6. Repeatedly activate the remaining control.
+ - expect: the expander disappears when all unchanged lines are visible.
+
diff --git a/e2e-test/tests/text-diff-expander.spec.js b/e2e-test/tests/text-diff-expander.spec.js
new file mode 100644
index 0000000000..5ebbde5b58
--- /dev/null
+++ b/e2e-test/tests/text-diff-expander.spec.js
@@ -0,0 +1,96 @@
+import { execFileSync } from 'node:child_process';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { expect, test } from '@playwright/test';
+import { fillLabeledInput, login } from './helpers.js';
+
+test('expands a middle text-diff gap up, both, and down', async ({ page }) => {
+ test.setTimeout(120_000);
+
+ // 1. Open a commit containing two distant changes
+ await login(page, 'admin', 'admin');
+ const projectName = `text-diff-expander-${Date.now()}`;
+ await page.goto('~projects/new');
+ await fillLabeledInput(page, 'Name', projectName);
+ await page.getByRole('button', { name: 'Create' }).click();
+ await expect(page).toHaveURL(new RegExp(`/${projectName}(/|$)`));
+ const repositoryDir = mkdtempSync(path.join(tmpdir(), 'onedev-text-diff-'));
+ let commitHash;
+ try {
+ const git = (...args) => execFileSync('git', args, { cwd: repositoryDir, stdio: 'pipe' });
+ git('init', '--initial-branch=main');
+ git('config', 'user.name', 'OneDev E2E');
+ git('config', 'user.email', '[email protected]');
+
+ const lines = Array.from({ length: 100 }, (_, index) => `unchanged-line-${index + 1}`);
+ writeFileSync(path.join(repositoryDir, 'fixture.txt'), `${lines.join('\n')}\n`);
+ git('add', 'fixture.txt');
+ git('commit', '-m', 'Add text diff fixture');
+
+ lines[9] = 'changed-line-10';
+ lines[89] = 'changed-line-90';
+ writeFileSync(path.join(repositoryDir, 'fixture.txt'), `${lines.join('\n')}\n`);
+ git('commit', '-am', 'Change distant fixture lines');
+ commitHash = git('rev-parse', 'HEAD').toString().trim();
+
+ const remoteUrl = new URL(page.url());
+ remoteUrl.username = 'admin';
+ remoteUrl.password = 'admin';
+ remoteUrl.pathname = `/${projectName}`;
+ remoteUrl.search = '';
+ remoteUrl.hash = '';
+ git('remote', 'add', 'origin', remoteUrl.toString());
+ git('push', 'origin', 'main');
+ } finally {
+ rmSync(repositoryDir, { recursive: true, force: true });
+ }
+
+ const commitUrl = `${projectName}/~commits/${commitHash}`;
+ await page.goto(commitUrl);
+ const directionalRow = page.locator('tr.expander').filter({ has: page.locator('.expander-controls') });
+ await expect(directionalRow).toHaveCount(1);
+ await expect(page.locator('tr.expander').filter({ hasNot: page.locator('.expander-controls') })).toHaveCount(2);
+
+ const controls = directionalRow.locator('.expander-controls > a');
+ await expect(controls).toHaveCount(3);
+ await expect(directionalRow.getByLabel('Show more lines above')).toBeVisible();
+ await expect(directionalRow.getByLabel('Show more lines', { exact: true })).toBeVisible();
+ await expect(directionalRow.getByLabel('Show more lines below')).toBeVisible();
+ await expect(controls.nth(1)).toContainText(/skipped \d+ lines/);
+ const widths = await controls.evaluateAll((elements) => elements.map((element) => element.getBoundingClientRect().width));
+ expect(Math.max(...widths) - Math.min(...widths)).toBeLessThan(2);
+
+ const rowClass = (await directionalRow.getAttribute('class')).split(/\s+/).find((name) => /^expander\d+$/.test(name));
+ const middleRow = page.locator(`tr.${rowClass}`);
+
+ // 2. Expand only toward the preceding hunk
+ await directionalRow.locator('.expand-up').click();
+ await expect(page.getByText('unchanged-line-28', { exact: true })).toBeVisible();
+ await expect(page.getByText('unchanged-line-71', { exact: true })).toHaveCount(0);
+
+ // 3. Reload and expand only toward the following hunk
+ await page.goto(commitUrl);
+ await page.locator(`tr.${rowClass} .expand-down`).click();
+ await expect(page.getByText('unchanged-line-72', { exact: true })).toBeVisible();
+ await expect(page.getByText('unchanged-line-29', { exact: true })).toHaveCount(0);
+
+ // 4. Reload and retain the existing both-sides expansion
+ await page.goto(commitUrl);
+ await page.locator(`tr.${rowClass} .expand-both`).click();
+ await expect(page.getByText('unchanged-line-28', { exact: true })).toBeVisible();
+ await expect(page.getByText('unchanged-line-72', { exact: true })).toBeVisible();
+
+ // 5. Exhaust the upward half and leave one control for the downward half
+ await page.goto(commitUrl);
+ for (let click = 0; click < 3; click += 1)
+ await page.locator(`tr.${rowClass} .expand-up`).click();
+ await expect(middleRow.locator('.expander-controls')).toHaveCount(0);
+ await expect(middleRow.locator('td.expander > a')).toHaveCount(1);
+
+ // 6. Reveal the remaining half until the expander disappears
+ for (let click = 0; click < 3; click += 1)
+ await middleRow.locator('td.expander > a').click();
+ await expect(middleRow).toHaveCount(0);
+});
diff --git a/server-core/src/main/java/io/onedev/server/web/asset/textdiff/text-diff.css b/server-core/src/main/java/io/onedev/server/web/asset/textdiff/text-diff.css
index 55db48cce5..bc79fbb5f2 100644
--- a/server-core/src/main/java/io/onedev/server/web/asset/textdiff/text-diff.css
+++ b/server-core/src/main/java/io/onedev/server/web/asset/textdiff/text-diff.css
@@ -166,6 +166,33 @@
padding: 2rem 0;
margin: -2rem -1px;
}
+.text-diff>tbody>tr.expander>td.expander.directional {
+ padding: 0;
+}
+.text-diff>tbody>tr.expander>td.expander>.expander-controls {
+ display: flex;
+}
+.text-diff>tbody>tr.expander>td.expander>.expander-controls>a {
+ display: flex;
+ flex: 1 1 0;
+ align-items: center;
+ justify-content: center;
+ gap: 0.5rem;
+ margin: 0;
+ padding: 0.5rem 0;
+ min-width: 0;
+}
+.text-diff>tbody>tr.expander>td.expander>.expander-controls>a+a {
+ border-left: 1px solid var(--light-gray);
+}
+.dark-mode .text-diff>tbody>tr.expander>td.expander>.expander-controls>a+a {
+ border-left-color: var(--dark-mode-lighter-dark);
+}
+.text-diff>tbody>tr.expander>td.expander>.expander-controls>a:hover,
+.text-diff>tbody>tr.expander>td.expander>.expander-controls>a:focus {
+ background: var(--primary);
+ color: white;
+}
.dark-mode .text-diff>tbody>tr.expander>td.expander a {
background: rgb(23, 33, 53);
color: var(--gray);
@@ -177,4 +204,4 @@
}
.text-diff>tbody>tr>td:first-child {
border-left: none !important;
-}
\ No newline at end of file
+}
diff --git a/server-core/src/main/java/io/onedev/server/web/component/diff/DiffExpandSupport.java b/server-core/src/main/java/io/onedev/server/web/component/diff/DiffExpandSupport.java
index 339a42a156..a8caa985a3 100644
--- a/server-core/src/main/java/io/onedev/server/web/component/diff/DiffExpandSupport.java
+++ b/server-core/src/main/java/io/onedev/server/web/component/diff/DiffExpandSupport.java
@@ -13,25 +13,80 @@ import io.onedev.server.web.WebConstants;
*/
public class DiffExpandSupport implements Serializable {
- private final Map<Integer, Integer> contextSizes = new HashMap<>();
+ private final Map<Integer, ContextSizes> contextSizes = new HashMap<>();
+
+ public enum Direction {
+ UP, BOTH, DOWN;
+
+ public static Direction fromString(String value) {
+ for (Direction direction : values()) {
+ if (direction.name().equalsIgnoreCase(value))
+ return direction;
+ }
+ return BOTH;
+ }
+ }
+
+ public static class ContextSizes implements Serializable {
+
+ private final int top;
+
+ private final int bottom;
+
+ public ContextSizes(int top, int bottom) {
+ this.top = top;
+ this.bottom = bottom;
+ }
+
+ public int getTop() {
+ return top;
+ }
+
+ public int getBottom() {
+ return bottom;
+ }
+ }
/**
* Gets the current or default context size for a given block index.
*/
- public int getContextSize(int blockIndex) {
- Integer contextSize = contextSizes.get(blockIndex);
- return contextSize != null ? contextSize : WebConstants.DIFF_CONTEXT_SIZE;
+ public ContextSizes getContextSizes(int blockIndex, int blockSize, int totalBlocks) {
+ ContextSizes contextSizes = this.contextSizes.get(blockIndex);
+ if (contextSizes != null)
+ return contextSizes;
+ if (blockIndex == 0)
+ return new ContextSizes(0, Math.min(WebConstants.DIFF_CONTEXT_SIZE, blockSize));
+ else if (blockIndex == totalBlocks - 1)
+ return new ContextSizes(Math.min(WebConstants.DIFF_CONTEXT_SIZE, blockSize), 0);
+ else
+ return new ContextSizes(
+ Math.min(WebConstants.DIFF_CONTEXT_SIZE, (blockSize + 1) / 2),
+ Math.min(WebConstants.DIFF_CONTEXT_SIZE, blockSize / 2));
}
/**
* Expands the context for a given block index.
* @return the new context size after expansion
*/
- public int expand(int blockIndex) {
- int lastContextSize = getContextSize(blockIndex);
- int newContextSize = lastContextSize + WebConstants.DIFF_EXPAND_SIZE;
- contextSizes.put(blockIndex, newContextSize);
- return newContextSize;
+ public ContextSizes expand(int blockIndex, int blockSize, int totalBlocks, Direction direction) {
+ ContextSizes lastContextSizes = getContextSizes(blockIndex, blockSize, totalBlocks);
+ int top = lastContextSizes.getTop();
+ int bottom = lastContextSizes.getBottom();
+ if (blockIndex == 0) {
+ bottom = Math.min(blockSize, bottom + WebConstants.DIFF_EXPAND_SIZE);
+ } else if (blockIndex == totalBlocks - 1) {
+ top = Math.min(blockSize, top + WebConstants.DIFF_EXPAND_SIZE);
+ } else {
+ int maxTop = (blockSize + 1) / 2;
+ int maxBottom = blockSize / 2;
+ if (direction == Direction.UP || direction == Direction.BOTH)
+ top = Math.min(maxTop, top + WebConstants.DIFF_EXPAND_SIZE);
+ if (direction == Direction.DOWN || direction == Direction.BOTH)
+ bottom = Math.min(maxBottom, bottom + WebConstants.DIFF_EXPAND_SIZE);
+ }
+ ContextSizes newContextSizes = new ContextSizes(top, bottom);
+ contextSizes.put(blockIndex, newContextSizes);
+ return newContextSizes;
}
/**
@@ -39,47 +94,50 @@ public class DiffExpandSupport implements Serializable {
*
* @param builder the string builder to append to
* @param blockIndex the index of the current equal block
- * @param lastContextSize the previous context size (0 for initial render)
- * @param contextSize the current context size to render
+ * @param lastContextSizes the previous top and bottom context sizes
+ * @param contextSizes the current top and bottom context sizes to render
* @param block the diff block containing equal lines
* @param totalBlocks total number of diff blocks
* @param callback callback to append individual lines and expanders
*/
- public void appendEquals(StringBuilder builder, int blockIndex, int lastContextSize,
- int contextSize, DiffBlock<String> block, int totalBlocks, ExpandCallback callback) {
+ public void appendEquals(StringBuilder builder, int blockIndex, ContextSizes lastContextSizes,
+ ContextSizes contextSizes, DiffBlock<String> block, int totalBlocks, ExpandCallback callback) {
if (blockIndex == 0) {
// First block: show last N context lines
- int start = block.getElements().size() - contextSize;
+ int start = block.getElements().size() - contextSizes.getBottom();
if (start < 0)
start = 0;
else if (start > 0)
- callback.appendExpander(builder, blockIndex, start);
- for (int j = start; j < block.getElements().size() - lastContextSize; j++)
- callback.appendEqual(builder, block, j, lastContextSize);
+ callback.appendExpander(builder, blockIndex, start, true, false);
+ for (int j = start; j < block.getElements().size() - lastContextSizes.getBottom(); j++)
+ callback.appendEqual(builder, block, j, lastContextSizes.getBottom());
} else if (blockIndex == totalBlocks - 1) {
// Last block: show first N context lines
int end = block.getElements().size();
int skipped = 0;
- if (end > contextSize) {
- skipped = end - contextSize;
- end = contextSize;
+ if (end > contextSizes.getTop()) {
+ skipped = end - contextSizes.getTop();
+ end = contextSizes.getTop();
}
- for (int j = lastContextSize; j < end; j++)
- callback.appendEqual(builder, block, j, lastContextSize);
+ for (int j = lastContextSizes.getTop(); j < end; j++)
+ callback.appendEqual(builder, block, j, lastContextSizes.getTop());
if (skipped != 0)
- callback.appendExpander(builder, blockIndex, skipped);
- } else if (2 * contextSize < block.getElements().size()) {
- // Middle block with large content: show N lines at start, expander, N lines at end
- for (int j = lastContextSize; j < contextSize; j++)
- callback.appendEqual(builder, block, j, lastContextSize);
- callback.appendExpander(builder, blockIndex, block.getElements().size() - 2 * contextSize);
- for (int j = block.getElements().size() - contextSize; j < block.getElements().size() - lastContextSize; j++)
- callback.appendEqual(builder, block, j, lastContextSize);
+ callback.appendExpander(builder, blockIndex, skipped, false, true);
} else {
- // Middle block with small content: show all newly expanded lines
- for (int j = lastContextSize; j < block.getElements().size() - lastContextSize; j++)
- callback.appendEqual(builder, block, j, lastContextSize);
+ // Middle block: top and bottom contexts grow independently toward the block midpoint
+ for (int j = lastContextSizes.getTop(); j < contextSizes.getTop(); j++)
+ callback.appendEqual(builder, block, j, lastContextSizes.getTop());
+ int skipped = block.getElements().size() - contextSizes.getTop() - contextSizes.getBottom();
+ if (skipped > 0) {
+ boolean canExpandUp = contextSizes.getTop() < (block.getElements().size() + 1) / 2;
+ boolean canExpandDown = contextSizes.getBottom() < block.getElements().size() / 2;
+ callback.appendExpander(builder, blockIndex, skipped, canExpandUp, canExpandDown);
+ }
+ for (int j = block.getElements().size() - contextSizes.getBottom();
+ j < block.getElements().size() - lastContextSizes.getBottom(); j++) {
+ callback.appendEqual(builder, block, j, lastContextSizes.getBottom());
+ }
}
}
@@ -104,7 +162,7 @@ public class DiffExpandSupport implements Serializable {
* @param blockIndex the block index
* @param skippedLines the number of skipped lines
*/
- void appendExpander(StringBuilder builder, int blockIndex, int skippedLines);
+ void appendExpander(StringBuilder builder, int blockIndex, int skippedLines,
+ boolean canExpandUp, boolean canExpandDown);
}
}
-
diff --git a/server-core/src/main/java/io/onedev/server/web/component/diff/blob/text/BlobTextDiffPanel.java b/server-core/src/main/java/io/onedev/server/web/component/diff/blob/text/BlobTextDiffPanel.java
index 269a138c31..e133f14fac 100644
--- a/server-core/src/main/java/io/onedev/server/web/component/diff/blob/text/BlobTextDiffPanel.java
+++ b/server-core/src/main/java/io/onedev/server/web/component/diff/blob/text/BlobTextDiffPanel.java
@@ -274,12 +274,16 @@ public class BlobTextDiffPanel extends Panel implements ChatToolAware {
blameInfo.lastNewCommitHash = null;
}
int index = params.getParameterValue("param1").toInt();
- int lastContextSize = expandSupport.getContextSize(index);
- int contextSize = expandSupport.expand(index);
+ DiffBlock<String> block = change.getDiffBlocks().get(index);
+ var lastContextSizes = expandSupport.getContextSizes(index, block.getElements().size(),
+ change.getDiffBlocks().size());
+ var direction = DiffExpandSupport.Direction.fromString(
+ params.getParameterValue("param2").toString("both"));
+ var contextSizes = expandSupport.expand(index, block.getElements().size(),
+ change.getDiffBlocks().size(), direction);
StringBuilder builder = new StringBuilder();
- DiffBlock<String> block = change.getDiffBlocks().get(index);
- expandSupport.appendEquals(builder, index, lastContextSize, contextSize,
+ expandSupport.appendEquals(builder, index, lastContextSizes, contextSizes,
block, change.getDiffBlocks().size(), new ExpandCallbackImpl());
String expanded = Strings.CS.replace(builder.toString(), "\n", "");
@@ -585,8 +589,9 @@ public class BlobTextDiffPanel extends Panel implements ChatToolAware {
for (int i=0; i<change.getDiffBlocks().size(); i++) {
DiffBlock<String> block = change.getDiffBlocks().get(i);
if (block.getOperation() == Operation.EQUAL) {
- int contextSize = expandSupport.getContextSize(i);
- expandSupport.appendEquals(builder, i, 0, contextSize,
+ var contextSizes = expandSupport.getContextSizes(i, block.getElements().size(),
+ change.getDiffBlocks().size());
+ expandSupport.appendEquals(builder, i, new DiffExpandSupport.ContextSizes(0, 0), contextSizes,
block, change.getDiffBlocks().size(), callback);
} else if (block.getOperation() == Operation.DELETE) {
if (i+1<change.getDiffBlocks().size()) {
@@ -955,16 +960,51 @@ public class BlobTextDiffPanel extends Panel implements ChatToolAware {
builder.append("</td></tr>");
}
- private void appendExpander(StringBuilder builder, int blockIndex, int skippedLines) {
+ private void appendExpander(StringBuilder builder, int blockIndex, int skippedLines,
+ boolean canExpandUp, boolean canExpandDown) {
builder.append("<tr class='expander expander").append(blockIndex).append("'>");
String expandSvg = String.format("<svg class='icon'><use xlink:href='%s'/></svg>",
SpriteImage.getVersionedHref(IconScope.class, "expand2"));
+ String upSvg = String.format("<svg class='icon rotate-270'><use xlink:href='%s'/></svg>",
+ SpriteImage.getVersionedHref(IconScope.class, "arrow"));
+ String downSvg = String.format("<svg class='icon rotate-90'><use xlink:href='%s'/></svg>",
+ SpriteImage.getVersionedHref(IconScope.class, "arrow"));
String ellipsisSvg = String.format("<svg class='icon'><use xlink:href='%s'/></svg>",
SpriteImage.getVersionedHref(IconScope.class, "ellipsis"));
- String script = String.format("javascript:$('#%s').data('callback')('expand', %d);", getMarkupId(), blockIndex);
var skippedMessage = MessageFormat.format(_T("skipped {0} lines"), String.valueOf(skippedLines));
+ if (canExpandUp && canExpandDown) {
+ int colspan;
+ if (diffMode == DiffViewMode.UNIFIED)
+ colspan = blameInfo != null ? 5 : 4;
+ else
+ colspan = blameInfo != null ? 8 : 6;
+ String upScript = String.format("javascript:$('#%s').data('callback')('expand', %d, 'up');", getMarkupId(), blockIndex);
+ String bothScript = String.format("javascript:$('#%s').data('callback')('expand', %d, 'both');", getMarkupId(), blockIndex);
+ String downScript = String.format("javascript:$('#%s').data('callback')('expand', %d, 'down');", getMarkupId(), blockIndex);
+ builder.append("<td colspan='").append(colspan).append("' class='expander directional noselect'><div class='expander-controls'>")
+ .append("<a class='expand-up' aria-label='").append(_T("Show more lines above"))
+ .append("' data-tippy-content='").append(_T("Show more lines above")).append("' href=\"")
+ .append(upScript).append("\">").append(upSvg).append("</a>")
+ .append("<a class='expand-both' aria-label='").append(_T("Show more lines"))
+ .append("' data-tippy-content='").append(_T("Show more lines")).append("' href=\"")
+ .append(bothScript).append("\">").append(expandSvg).append(" <span>").append(skippedMessage).append("</span></a>")
+ .append("<a class='expand-down' aria-label='").append(_T("Show more lines below"))
+ .append("' data-tippy-content='").append(_T("Show more lines below")).append("' href=\"")
+ .append(downScript).append("\">").append(downSvg).append("</a></div></td>");
+ if (blameInfo != null) {
+ blameInfo.lastCommitHash = null;
+ blameInfo.lastOldCommitHash = null;
+ blameInfo.lastNewCommitHash = null;
+ }
+ builder.append("</tr>");
+ return;
+ }
+
+ String direction = canExpandUp ? "up" : "down";
+ String script = String.format("javascript:$('#%s').data('callback')('expand', %d, '%s');",
+ getMarkupId(), blockIndex, direction);
if (diffMode == DiffViewMode.UNIFIED) {
if (blameInfo != null) {
builder.append("<td colspan='3' class='expander noselect'><a data-tippy-content='" + _T("Show more lines") + "' href=\"")
@@ -1085,8 +1125,9 @@ public class BlobTextDiffPanel extends Panel implements ChatToolAware {
}
@Override
- public void appendExpander(StringBuilder builder, int blockIndex, int skippedLines) {
- BlobTextDiffPanel.this.appendExpander(builder, blockIndex, skippedLines);
+ public void appendExpander(StringBuilder builder, int blockIndex, int skippedLines,
+ boolean canExpandUp, boolean canExpandDown) {
+ BlobTextDiffPanel.this.appendExpander(builder, blockIndex, skippedLines, canExpandUp, canExpandDown);
}
}
diff --git a/server-core/src/main/java/io/onedev/server/web/component/diff/text/PlainTextDiffPanel.java b/server-core/src/main/java/io/onedev/server/web/component/diff/text/PlainTextDiffPanel.java
index f3ee5b94f8..f7394f93e3 100644
--- a/server-core/src/main/java/io/onedev/server/web/component/diff/text/PlainTextDiffPanel.java
+++ b/server-core/src/main/java/io/onedev/server/web/component/diff/text/PlainTextDiffPanel.java
@@ -73,12 +73,14 @@ public class PlainTextDiffPanel extends Panel {
IRequestParameters params = RequestCycle.get().getRequest().getPostParameters();
if ("expand".equals(params.getParameterValue("action").toString(""))) {
int index = params.getParameterValue("param1").toInt();
- int lastContextSize = expandSupport.getContextSize(index);
- int contextSize = expandSupport.expand(index);
+ DiffBlock<String> block = diffBlocks.get(index);
+ var lastContextSizes = expandSupport.getContextSizes(index, block.getElements().size(), diffBlocks.size());
+ var direction = DiffExpandSupport.Direction.fromString(
+ params.getParameterValue("param2").toString("both"));
+ var contextSizes = expandSupport.expand(index, block.getElements().size(), diffBlocks.size(), direction);
StringBuilder builder = new StringBuilder();
- DiffBlock<String> block = diffBlocks.get(index);
- expandSupport.appendEquals(builder, index, lastContextSize, contextSize,
+ expandSupport.appendEquals(builder, index, lastContextSizes, contextSizes,
block, diffBlocks.size(), new ExpandCallbackImpl());
String expanded = Strings.CS.replace(builder.toString(), "\n", "");
@@ -117,8 +119,8 @@ public class PlainTextDiffPanel extends Panel {
for (int i = 0; i < diffBlocks.size(); i++) {
DiffBlock<String> block = diffBlocks.get(i);
if (block.getOperation() == Operation.EQUAL) {
- int contextSize = expandSupport.getContextSize(i);
- expandSupport.appendEquals(builder, i, 0, contextSize,
+ var contextSizes = expandSupport.getContextSizes(i, block.getElements().size(), diffBlocks.size());
+ expandSupport.appendEquals(builder, i, new DiffExpandSupport.ContextSizes(0, 0), contextSizes,
block, diffBlocks.size(), callback);
} else if (block.getOperation() == Operation.DELETE) {
for (int j = 0; j < block.getElements().size(); j++)
@@ -186,16 +188,40 @@ public class PlainTextDiffPanel extends Panel {
builder.append("</td></tr>");
}
- private void appendExpander(StringBuilder builder, int blockIndex, int skippedLines) {
+ private void appendExpander(StringBuilder builder, int blockIndex, int skippedLines,
+ boolean canExpandUp, boolean canExpandDown) {
builder.append("<tr class='expander expander").append(blockIndex).append("'>");
String expandSvg = String.format("<svg class='icon'><use xlink:href='%s'/></svg>",
SpriteImage.getVersionedHref(IconScope.class, "expand2"));
+ String upSvg = String.format("<svg class='icon rotate-270'><use xlink:href='%s'/></svg>",
+ SpriteImage.getVersionedHref(IconScope.class, "arrow"));
+ String downSvg = String.format("<svg class='icon rotate-90'><use xlink:href='%s'/></svg>",
+ SpriteImage.getVersionedHref(IconScope.class, "arrow"));
String ellipsisSvg = String.format("<svg class='icon'><use xlink:href='%s'/></svg>",
SpriteImage.getVersionedHref(IconScope.class, "ellipsis"));
- String script = String.format("javascript:$('#%s').data('callback')('expand', %d);", getMarkupId(), blockIndex);
var skippedMessage = MessageFormat.format(_T("skipped {0} lines"), String.valueOf(skippedLines));
+ if (canExpandUp && canExpandDown) {
+ String upScript = String.format("javascript:$('#%s').data('callback')('expand', %d, 'up');", getMarkupId(), blockIndex);
+ String bothScript = String.format("javascript:$('#%s').data('callback')('expand', %d, 'both');", getMarkupId(), blockIndex);
+ String downScript = String.format("javascript:$('#%s').data('callback')('expand', %d, 'down');", getMarkupId(), blockIndex);
+ builder.append("<td colspan='").append(showLineNumbers ? 4 : 2).append("' class='expander directional noselect'><div class='expander-controls'>")
+ .append("<a class='expand-up' aria-label='").append(_T("Show more lines above"))
+ .append("' data-tippy-content='").append(_T("Show more lines above")).append("' href=\"")
+ .append(upScript).append("\">").append(upSvg).append("</a>")
+ .append("<a class='expand-both' aria-label='").append(_T("Show more lines"))
+ .append("' data-tippy-content='").append(_T("Show more lines")).append("' href=\"")
+ .append(bothScript).append("\">").append(expandSvg).append(" <span>").append(skippedMessage).append("</span></a>")
+ .append("<a class='expand-down' aria-label='").append(_T("Show more lines below"))
+ .append("' data-tippy-content='").append(_T("Show more lines below")).append("' href=\"")
+ .append(downScript).append("\">").append(downSvg).append("</a></div></td></tr>");
+ return;
+ }
+
+ String direction = canExpandUp ? "up" : "down";
+ String script = String.format("javascript:$('#%s').data('callback')('expand', %d, '%s');",
+ getMarkupId(), blockIndex, direction);
if (showLineNumbers) {
builder.append("<td colspan='2' class='expander noselect'><a data-tippy-content='").append(_T("Show more lines")).append("' href=\"")
@@ -222,7 +248,8 @@ public class PlainTextDiffPanel extends Panel {
super.renderHead(response);
response.render(JavaScriptHeaderItem.forReference(new PlainTextDiffResourceReference()));
- CharSequence callback = callbackBehavior.getCallbackFunction(explicit("action"), explicit("param1"));
+ CharSequence callback = callbackBehavior.getCallbackFunction(
+ explicit("action"), explicit("param1"), explicit("param2"));
String fileNameParam = fileName != null ? "'" + escapeJavaScript(fileName) + "'" : "null";
String script = String.format("onedev.server.plainTextDiff.onDomReady('%s', %s, %s);",
getMarkupId(), callback, fileNameParam);
@@ -236,8 +263,9 @@ public class PlainTextDiffPanel extends Panel {
}
@Override
- public void appendExpander(StringBuilder builder, int blockIndex, int skippedLines) {
- PlainTextDiffPanel.this.appendExpander(builder, blockIndex, skippedLines);
+ public void appendExpander(StringBuilder builder, int blockIndex, int skippedLines,
+ boolean canExpandUp, boolean canExpandDown) {
+ PlainTextDiffPanel.this.appendExpander(builder, blockIndex, skippedLines, canExpandUp, canExpandDown);
}
}
diff --git a/server-core/src/test/java/io/onedev/server/web/component/diff/DiffExpandSupportTest.java b/server-core/src/test/java/io/onedev/server/web/component/diff/DiffExpandSupportTest.java
new file mode 100644
index 0000000000..6668464b7f
--- /dev/null
+++ b/server-core/src/test/java/io/onedev/server/web/component/diff/DiffExpandSupportTest.java
@@ -0,0 +1,106 @@
+package io.onedev.server.web.component.diff;
+
+import static io.onedev.server.web.component.diff.DiffExpandSupport.Direction.BOTH;
+import static io.onedev.server.web.component.diff.DiffExpandSupport.Direction.DOWN;
+import static io.onedev.server.web.component.diff.DiffExpandSupport.Direction.UP;
+import static java.util.stream.Collectors.toList;
+import static java.util.stream.IntStream.range;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.Test;
+
+import io.onedev.server.util.diff.DiffBlock;
+import io.onedev.server.util.diff.DiffMatchPatch.Operation;
+
+public class DiffExpandSupportTest {
+
+ @Test
+ public void shouldExpandMiddleBlockIndependently() {
+ var support = new DiffExpandSupport();
+ var block = newBlock(100);
+ var callback = new Callback();
+ var contextSizes = support.getContextSizes(1, 100, 3);
+
+ support.appendEquals(new StringBuilder(), 1, new DiffExpandSupport.ContextSizes(0, 0),
+ contextSizes, block, 3, callback);
+ assertEquals(List.of(0, 1, 2, 97, 98, 99), callback.lines);
+ assertEquals(94, callback.skippedLines);
+ assertTrue(callback.canExpandUp);
+ assertTrue(callback.canExpandDown);
+
+ callback = new Callback();
+ var lastContextSizes = contextSizes;
+ contextSizes = support.expand(1, 100, 3, UP);
+ support.appendEquals(new StringBuilder(), 1, lastContextSizes, contextSizes, block, 3, callback);
+ assertEquals(range(3, 18).boxed().collect(toList()), callback.lines);
+ assertEquals(79, callback.skippedLines);
+
+ support.expand(1, 100, 3, UP);
+ support.expand(1, 100, 3, UP);
+ lastContextSizes = support.getContextSizes(1, 100, 3);
+ contextSizes = support.expand(1, 100, 3, UP);
+ callback = new Callback();
+ support.appendEquals(new StringBuilder(), 1, lastContextSizes, contextSizes, block, 3, callback);
+ assertEquals(List.of(48, 49), callback.lines);
+ assertFalse(callback.canExpandUp);
+ assertTrue(callback.canExpandDown);
+ assertEquals(47, callback.skippedLines);
+
+ lastContextSizes = contextSizes;
+ contextSizes = support.expand(1, 100, 3, DOWN);
+ callback = new Callback();
+ support.appendEquals(new StringBuilder(), 1, lastContextSizes, contextSizes, block, 3, callback);
+ assertEquals(range(82, 97).boxed().collect(toList()), callback.lines);
+ assertFalse(callback.canExpandUp);
+ assertTrue(callback.canExpandDown);
+ }
+
+ @Test
+ public void shouldExpandBothSidesAndRemoveExpanderWhenSidesMeet() {
+ var support = new DiffExpandSupport();
+ var block = newBlock(40);
+ support.expand(1, 40, 3, BOTH);
+ var lastContextSizes = support.getContextSizes(1, 40, 3);
+ var contextSizes = support.expand(1, 40, 3, BOTH);
+ var callback = new Callback();
+
+ support.appendEquals(new StringBuilder(), 1, lastContextSizes, contextSizes, block, 3, callback);
+ assertEquals(range(18, 22).boxed().collect(toList()), callback.lines);
+ assertEquals(-1, callback.skippedLines);
+ }
+
+ private static DiffBlock<String> newBlock(int size) {
+ return new DiffBlock<>(Operation.EQUAL,
+ range(0, size).mapToObj(String::valueOf).collect(toList()), 0, 0);
+ }
+
+ private static class Callback implements DiffExpandSupport.ExpandCallback {
+
+ private final List<Integer> lines = new ArrayList<>();
+
+ private int skippedLines = -1;
+
+ private boolean canExpandUp;
+
+ private boolean canExpandDown;
+
+ @Override
+ public void appendEqual(StringBuilder builder, DiffBlock<String> block, int lineIndex,
+ int lastContextSize) {
+ lines.add(lineIndex);
+ }
+
+ @Override
+ public void appendExpander(StringBuilder builder, int blockIndex, int skippedLines,
+ boolean canExpandUp, boolean canExpandDown) {
+ this.skippedLines = skippedLines;
+ this.canExpandUp = canExpandUp;
+ this.canExpandDown = canExpandDown;
+ }
+ }
+}