Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
why the mirror lags one release, structurally, and why this bump is the first step rather than
an afterthought.
-->
<PackageReference Include="Ank.DocToolkit" Version="[0.34.0, )" />
<PackageReference Include="Ank.DocToolkit" Version="[0.36.1, )" />

<!--
8.0.2, not 8.0.0, since 0.15.0. PDFsharp raised Microsoft.Extensions.Logging.Abstractions
Expand Down
25 changes: 25 additions & 0 deletions src/DocToolkit.Extensions.DependencyInjection/DocxReviewService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
namespace DocToolkit.Extensions.DependencyInjection;

/// <summary>Default <see cref="IDocxReview"/>, delegating to <see cref="DocToolkit.DocxReview"/>.</summary>
internal sealed class DocxReviewService : IDocxReview
{
public DocToolkit.DocxReviewReport Inspect(byte[] docx) => DocToolkit.DocxReview.Inspect(docx);

public Task<DocToolkit.DocxReviewReport> InspectAsync(Stream source, CancellationToken ct = default)
=> DocToolkit.DocxReview.InspectAsync(source, ct);

public byte[] RemoveComments(byte[] docx) => DocToolkit.DocxReview.RemoveComments(docx);

public Task RemoveCommentsAsync(Stream source, Stream destination, CancellationToken ct = default)
=> DocToolkit.DocxReview.RemoveCommentsAsync(source, destination, ct);

public byte[] AcceptRevisions(byte[] docx) => DocToolkit.DocxReview.AcceptRevisions(docx);

public Task AcceptRevisionsAsync(Stream source, Stream destination, CancellationToken ct = default)
=> DocToolkit.DocxReview.AcceptRevisionsAsync(source, destination, ct);

public byte[] RejectRevisions(byte[] docx) => DocToolkit.DocxReview.RejectRevisions(docx);

public Task RejectRevisionsAsync(Stream source, Stream destination, CancellationToken ct = default)
=> DocToolkit.DocxReview.RejectRevisionsAsync(source, destination, ct);
}
74 changes: 74 additions & 0 deletions src/DocToolkit.Extensions.DependencyInjection/IDocxReview.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
namespace DocToolkit.Extensions.DependencyInjection;

/// <summary>
/// Reads and resolves a Word document's review state — the comments and tracked changes it carries
/// from having been through review. Registered by
/// <see cref="ServiceCollectionExtensions.AddDocToolkit"/>.
/// </summary>
/// <remarks>
/// <b>Separate from <see cref="IDocxEditor"/> deliberately.</b> That interface is about a document's
/// content; this is about the record of people arguing over it.
///
/// <b>Read and resolve only.</b> There is no member here to add a comment or to record an edit as a
/// tracked change — the core library cannot create review state, so neither can this.
/// </remarks>
public interface IDocxReview
{
/// <summary>Reads the comments and tracked changes <paramref name="docx"/> carries.</summary>
/// <param name="docx">The document to inspect.</param>
/// <exception cref="ArgumentNullException"><paramref name="docx"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="docx"/> is empty.</exception>
/// <exception cref="DocToolkit.DocumentConversionException">It could not be opened or read.</exception>
DocToolkit.DocxReviewReport Inspect(byte[] docx);

/// <inheritdoc cref="Inspect(byte[])"/>
/// <param name="source">The document to inspect. Read to its end; never disposed or sought.</param>
/// <param name="ct">Cancels before the document is read.</param>
Task<DocToolkit.DocxReviewReport> InspectAsync(Stream source, CancellationToken ct = default);

/// <summary>A copy of <paramref name="docx"/> with every comment removed.</summary>
/// <param name="docx">The document to clean.</param>
/// <exception cref="ArgumentNullException"><paramref name="docx"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="docx"/> is empty.</exception>
/// <exception cref="DocToolkit.DocumentConversionException">It could not be read or written.</exception>
byte[] RemoveComments(byte[] docx);

/// <inheritdoc cref="RemoveComments(byte[])"/>
/// <param name="source">The document to clean. Read to its end; never disposed or sought.</param>
/// <param name="destination">Receives the cleaned document. Written; never disposed or sought.</param>
/// <param name="ct">Cancels before the document is read, and while it is written.</param>
Task RemoveCommentsAsync(Stream source, Stream destination, CancellationToken ct = default);

/// <summary>
/// A copy of <paramref name="docx"/> with every tracked change applied: insertions kept,
/// deletions dropped. <b>Cannot be undone from the result.</b>
/// </summary>
/// <param name="docx">The document to apply changes to.</param>
/// <exception cref="ArgumentNullException"><paramref name="docx"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="docx"/> is empty.</exception>
/// <exception cref="DocToolkit.DocumentConversionException">It could not be read or written.</exception>
byte[] AcceptRevisions(byte[] docx);

/// <inheritdoc cref="AcceptRevisions(byte[])"/>
/// <param name="source">The document to apply changes to. Read to its end; never disposed or sought.</param>
/// <param name="destination">Receives the result. Written; never disposed or sought.</param>
/// <param name="ct">Cancels before the document is read, and while it is written.</param>
Task AcceptRevisionsAsync(Stream source, Stream destination, CancellationToken ct = default);

/// <summary>
/// A copy of <paramref name="docx"/> with every tracked change discarded: insertions dropped,
/// deletions restored — the mirror of <see cref="AcceptRevisions(byte[])"/>. <b>Cannot be undone
/// from the result.</b>
/// </summary>
/// <param name="docx">The document to discard changes from.</param>
/// <exception cref="ArgumentNullException"><paramref name="docx"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="docx"/> is empty.</exception>
/// <exception cref="DocToolkit.DocumentConversionException">It could not be read or written.</exception>
byte[] RejectRevisions(byte[] docx);

/// <inheritdoc cref="RejectRevisions(byte[])"/>
/// <param name="source">The document to discard changes from. Read to its end; never disposed or sought.</param>
/// <param name="destination">Receives the result. Written; never disposed or sought.</param>
/// <param name="ct">Cancels before the document is read, and while it is written.</param>
Task RejectRevisionsAsync(Stream source, Stream destination, CancellationToken ct = default);
}
7 changes: 4 additions & 3 deletions src/DocToolkit.Extensions.DependencyInjection/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@
[![NuGet Downloads](https://img.shields.io/nuget/dt/Ank.DocToolkit.Extensions.DependencyInjection.svg)](https://www.nuget.org/packages/Ank.DocToolkit.Extensions.DependencyInjection/)

Dependency-injection registration for [Ank.DocToolkit](https://www.nuget.org/packages/Ank.DocToolkit) —
`services.AddDocToolkit()` registers fifteen injectable interfaces over the same pure-managed
HTML/DOCX/PDF/XLSX/PPTX/Markdown conversion and editing logic.
`services.AddDocToolkit()` registers an injectable interface per capability, over the same
pure-managed HTML/DOCX/PDF/XLSX/PPTX/Markdown conversion and editing logic. They are named in full
below.

```bash
dotnet add package Ank.DocToolkit.Extensions.DependencyInjection
Expand Down Expand Up @@ -154,7 +155,7 @@ Every interface — `IHtmlToDocxConverter`, `IDocxToPdfConverter`, `IHtmlToPdfCo
`IXlsxToPdfConverter`, `IPptxToPdfConverter`, `IDocxToHtmlConverter`,
`IDocxToMarkdownConverter`, `IMarkdownToDocxConverter`, `IMarkdownToPdfConverter`,
`IXlsxToCsvConverter`, `IXlsxToHtmlConverter`, `IDocToDocxConverter`, `IDocxEditor`,
`IWorkbookEditor`, `IPresentationEditor`, `IPdfEditor` — mirrors
`IWorkbookEditor`, `IPresentationEditor`, `IPdfEditor`, `IDocxReview` — mirrors
[`Ank.DocToolkit`](https://www.nuget.org/packages/Ank.DocToolkit)'s static API, including both its
`byte[]` and its `Stream`-based async overloads.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ public static IServiceCollection AddDocToolkit(
services.TryAddSingleton<IXlsxToCsvConverter, XlsxToCsvConverterService>();
services.TryAddSingleton<IXlsxToHtmlConverter, XlsxToHtmlConverterService>();
services.TryAddSingleton<IDocToDocxConverter, DocToDocxConverterService>();
services.TryAddSingleton<IDocxReview, DocxReviewService>();

return services;
}
Expand Down
12 changes: 6 additions & 6 deletions src/DocToolkit.Extensions.DependencyInjection/packages.lock.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
"net10.0": {
"Ank.DocToolkit": {
"type": "Direct",
"requested": "[0.34.0, )",
"resolved": "0.34.0",
"contentHash": "vwG9bd1x1KD9NAljaThHr1Y/UfPNhbVW/SICejpLDYBOKIZ6Go+CPewupqlqS+C3iKpxM9ihrmekLd64mwCL0g==",
"requested": "[0.36.1, )",
"resolved": "0.36.1",
"contentHash": "eIEAYc7n19tGqCv1bBNj+/3Kt19D/sGC+KOs+ciq11KBPIP6Lso5Wx++byPHCmnIQVodtYpiKOQ+06yLxNKOog==",
"dependencies": {
"AngleSharp": "1.7.1",
"ClosedXML": "0.105.1",
Expand Down Expand Up @@ -273,9 +273,9 @@
"net8.0": {
"Ank.DocToolkit": {
"type": "Direct",
"requested": "[0.34.0, )",
"resolved": "0.34.0",
"contentHash": "vwG9bd1x1KD9NAljaThHr1Y/UfPNhbVW/SICejpLDYBOKIZ6Go+CPewupqlqS+C3iKpxM9ihrmekLd64mwCL0g==",
"requested": "[0.36.1, )",
"resolved": "0.36.1",
"contentHash": "eIEAYc7n19tGqCv1bBNj+/3Kt19D/sGC+KOs+ciq11KBPIP6Lso5Wx++byPHCmnIQVodtYpiKOQ+06yLxNKOog==",
"dependencies": {
"AngleSharp": "1.7.1",
"ClosedXML": "0.105.1",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using Xunit;

namespace DocToolkit.Extensions.DependencyInjection.Tests;

/// <summary>
/// <see cref="DocxReviewService"/> — the dependency-injection mirror of
/// <see cref="DocToolkit.DocxReview"/>, which landed one release behind it because the extensions
/// package builds against the PUBLISHED core.
///
/// <b>This service is pure delegation, so the risk is not that the logic is wrong — it is that a
/// member delegates to the WRONG thing, or silently does nothing.</b> A test asserting only "it did
/// not throw" would miss both, and the DI package is held at 100% coverage precisely because an
/// uncovered member here is a member nobody checked was wired to anything.
///
/// So every assertion below is one a passthrough would fail:
///
/// <list type="bullet">
/// <item><c>Inspect</c> reads a comment and a tracked change out of a document that HAS them — a
/// stub returning an empty report passes a clean-document test and fails this one.</item>
/// <item><c>AcceptRevisions</c> and <c>RejectRevisions</c> are asserted on OPPOSITE outcomes, so
/// one implementation cannot satisfy both, and neither can a method that returns its input.</item>
/// <item><c>RemoveComments</c> is asserted to have removed them.</item>
/// <item>every guard is asserted to throw, which a member doing nothing would not.</item>
/// </list>
///
/// The fixtures are built with raw OpenXml — available transitively through
/// <c>Ank.DocToolkit</c>, so no new dependency — because the library cannot author either state:
/// <c>TrackChanges</c> records nothing for its own edits, and there is no comment-authoring API.
/// </summary>
public class DocxReviewServiceTests
{
private static readonly DateTime Reviewed = new(2026, 8, 24, 9, 0, 0, DateTimeKind.Utc);

private static IDocxReview Service() => new DocxReviewService();

// ---- Inspect ---------------------------------------------------------------------------

[Fact]
public void Inspect_ReadsTheReviewStateRatherThanReportingNothing()
{
var report = Service().Inspect(WithACommentAndTwoRevisions());

// A stub returning an empty report would pass a clean-document test. It fails here.
Assert.Equal("Reviewer One", Assert.Single(report.Comments).Author);
Assert.Equal(1, report.CommentThreadCount);
Assert.Equal(2, report.Revisions.Count);
}

[Fact]
public async Task InspectAsync_ReadsTheSameStateAndLeavesTheStreamOpen()
{
using var source = new MemoryStream(WithACommentAndTwoRevisions());

var report = await Service().InspectAsync(source);

Assert.Equal("Reviewer One", Assert.Single(report.Comments).Author);
Assert.Equal(2, report.Revisions.Count);

// DocToolkit did not open this stream and must not close it. A member that disposed the
// caller's stream would throw on the next read.
source.Position = 0;
Assert.Equal(1, source.ReadByte() >= 0 ? 1 : 0);
}

// ---- RemoveComments --------------------------------------------------------------------

[Fact]
public void RemoveComments_ActuallyRemovesThem()
{
byte[] input = WithACommentAndTwoRevisions();
Assert.NotEmpty(Service().Inspect(input).Comments); // the fixture really has one

byte[] cleaned = Service().RemoveComments(input);

Assert.Empty(Service().Inspect(cleaned).Comments);
}

[Fact]
public async Task RemoveCommentsAsync_WritesACleanedDocumentToTheDestination()
{
using var source = new MemoryStream(WithACommentAndTwoRevisions());
using var destination = new MemoryStream();

await Service().RemoveCommentsAsync(source, destination);

// Something was written, and what was written is a document with no comments left.
Assert.True(destination.Length > 0);
Assert.Empty(Service().Inspect(destination.ToArray()).Comments);
}

// ---- Accept and reject, asserted on OPPOSITE outcomes ----------------------------------

[Fact]
public void AcceptRevisions_KeepsTheInsertionAndDropsTheDeletion()
{
byte[] accepted = Service().AcceptRevisions(WithACommentAndTwoRevisions());

Assert.Empty(Service().Inspect(accepted).Revisions);

string text = DocToolkit.DocxEditor.ExtractText(accepted);
Assert.Contains("Inserted", text, StringComparison.Ordinal);
Assert.DoesNotContain("Removed", text, StringComparison.Ordinal);
}

[Fact]
public void RejectRevisions_DropsTheInsertionAndRestoresTheDeletion()
{
// THE MIRROR. Wire both members to the same static method and one of these two fails.
byte[] rejected = Service().RejectRevisions(WithACommentAndTwoRevisions());

Assert.Empty(Service().Inspect(rejected).Revisions);

string text = DocToolkit.DocxEditor.ExtractText(rejected);
Assert.DoesNotContain("Inserted", text, StringComparison.Ordinal);
Assert.Contains("Removed", text, StringComparison.Ordinal);
}

[Fact]
public async Task AcceptRevisionsAsync_AndRejectRevisionsAsync_DisagreeTheSameWay()
{
Assert.Contains("Inserted", await ApplyAsync(Service().AcceptRevisionsAsync), StringComparison.Ordinal);
Assert.DoesNotContain("Inserted", await ApplyAsync(Service().RejectRevisionsAsync), StringComparison.Ordinal);
}

private static async Task<string> ApplyAsync(
Func<Stream, Stream, CancellationToken, Task> operation)
{
using var source = new MemoryStream(WithACommentAndTwoRevisions());
using var destination = new MemoryStream();
await operation(source, destination, CancellationToken.None);
return DocToolkit.DocxEditor.ExtractText(destination.ToArray());
}

// ---- Guards ----------------------------------------------------------------------------

[Fact]
public void EveryByteArrayMember_RefusesNullAndEmpty()
{
var service = Service();
var calls = new Action<byte[]>[]
{
b => service.Inspect(b),
b => service.RemoveComments(b),
b => service.AcceptRevisions(b),
b => service.RejectRevisions(b),
};

foreach (var call in calls)
{
// A member that did nothing would return rather than throw, so this discriminates.
Assert.Throws<ArgumentNullException>(() => call(null!));
Assert.Throws<ArgumentException>(() => call([]));
}
}

[Fact]
public async Task EveryStreamMember_RefusesAnUnusableStream()
{
var service = Service();
using var ok = new MemoryStream(WithACommentAndTwoRevisions());

await Assert.ThrowsAsync<ArgumentNullException>(() => service.InspectAsync(null!));
await Assert.ThrowsAsync<ArgumentNullException>(() => service.RemoveCommentsAsync(null!, new MemoryStream()));
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
await Assert.ThrowsAsync<ArgumentNullException>(() => service.AcceptRevisionsAsync(null!, new MemoryStream()));
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
await Assert.ThrowsAsync<ArgumentNullException>(() => service.RejectRevisionsAsync(null!, new MemoryStream()));
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
await Assert.ThrowsAsync<ArgumentNullException>(() => service.RejectRevisionsAsync(ok, null!));
}

// ---- Fixture ---------------------------------------------------------------------------

/// <summary>
/// One comment, one inserted run and one deleted run — enough for every assertion above, in a
/// single document so the tests share one fixture.
///
/// Hand-assembled because the library cannot produce either state: <c>TrackChanges</c> records
/// nothing for edits it makes, and <c>AddComment</c> needs a paragraph the placeholder-based API
/// does not expose. A fixture built through <c>DocxEditor</c> would assert against empty sets
/// forever while looking green.
/// </summary>
private static byte[] WithACommentAndTwoRevisions()
{
using var ms = new MemoryStream();
using (var document = WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document))
{
var main = document.AddMainDocumentPart();

var paragraph = new Paragraph(
new CommentRangeStart { Id = "1" },
new Run(new Text("Kept. ") { Space = SpaceProcessingModeValues.Preserve }),
new CommentRangeEnd { Id = "1" },
new Run(new CommentReference { Id = "1" }));

paragraph.Append(new InsertedRun(
new Run(new Text("Inserted text. ") { Space = SpaceProcessingModeValues.Preserve }))
{
Id = "2",
Author = "Reviewer Two",
Date = new DateTimeValue(Reviewed),
});

paragraph.Append(new DeletedRun(new Run(new DeletedText("Removed text.")))
{
Id = "3",
Author = "Reviewer Three",
Date = new DateTimeValue(Reviewed),
});

main.Document = new Document(new Body(paragraph));

var comments = main.AddNewPart<WordprocessingCommentsPart>();
comments.Comments = new Comments(
new Comment(new Paragraph(new Run(new Text("Please tighten this."))))
{
Id = "1",
Author = "Reviewer One",
Initials = "R1",
Date = new DateTimeValue(Reviewed),
});

main.Document.Save();
}

return ms.ToArray();
}
}
Loading
Loading