diff --git a/packages/text-annotator/src/utils/trimRangeToContainer.ts b/packages/text-annotator/src/utils/trimRangeToContainer.ts index 8a419a4b..f019cbd5 100644 --- a/packages/text-annotator/src/utils/trimRangeToContainer.ts +++ b/packages/text-annotator/src/utils/trimRangeToContainer.ts @@ -4,13 +4,31 @@ export const trimRangeToContainer = ( ): Range => { const trimmedRange = range.cloneRange(); - // If the start is outside the container - set it to the start of the container - if (!container.contains(trimmedRange.startContainer)) { + const containsStart = container.contains(trimmedRange.startContainer); + const containsEnd = container.contains(trimmedRange.endContainer); + + /** + * If both the start and the end are outside the container - + * collapse such a range as irrelevant + */ + if (!containsStart && !containsEnd) { + trimmedRange.collapse(); + return trimmedRange; + } + + /** + * If the range starts outside the container - + * trim it to the start of the container + */ + if (!containsStart) { trimmedRange.setStart(container, 0); } - // If the end is outside the container - set it to the end of the container - if (!container.contains(trimmedRange.endContainer)) { + /** + * If the range ends outside the container - + * trim it to the end of the container + */ + if (containsEnd) { trimmedRange.setEnd(container, container.childNodes.length); }