Skip to content

Commit

Permalink
🔗 Improve link formatting (#1684)
Browse files Browse the repository at this point in the history
No hanging single characters on a link
  • Loading branch information
rowanc1 authored Nov 28, 2024
1 parent a27bd88 commit 3aa40b0
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/nervous-avocados-tell.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"myst-transforms": patch
---

No trailing slash for end of links
20 changes: 19 additions & 1 deletion packages/myst-transforms/src/links/plugin.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { VFile } from 'vfile';
import type { Link } from 'myst-spec-ext';
import type { ResolvedExternalReference } from './types';
import { MystTransformer } from './myst';
import { linksTransform } from './plugin';
import { formatLinkText, linksTransform } from './plugin';

export const TEST_REFERENCES: ResolvedExternalReference[] = [
{
Expand Down Expand Up @@ -47,3 +47,21 @@ describe('Link Plugin Transformer', () => {
expect(link.children).toEqual([]);
});
});

describe('formatLinkText', () => {
test.each([
['https://mystmd.com/guide', 'https://​mystmd​.com​/guide'],
['https://mystmd.com/guide#x', 'https://​mystmd​.com​/guide#x'],
['https://mystmd.com/guide#abc', 'https://​mystmd​.com​/guide​#abc'],
['https://mystmd.com/guide/', 'https://​mystmd​.com​/guide/'],
['https://mystmd.com/guide/', 'https://​mystmd​.com​/guide/'],
[
'https://mystmd.com/guide/citaion-format?test=1#ok',
'https://​mystmd​.com​/guide​/citaion​-format​?test​=​1​#ok',
],
])('Link Text — %s', (url, result) => {
const node = { type: 'link', children: [{ type: 'text', value: url }] };
formatLinkText(node as any);
expect(node.children[0].value).toBe(result);
});
});
6 changes: 4 additions & 2 deletions packages/myst-transforms/src/links/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable no-irregular-whitespace */
import type { Plugin } from 'unified';
import { selectAll } from 'unist-util-select';
import type { VFile } from 'vfile';
Expand All @@ -15,7 +16,7 @@ type Options = {
* Uses a zero-width space, same as a `<wbr>` but no fancy rendering required.
* https://css-tricks.com/better-line-breaks-for-long-urls/
*/
function formatLinkText(link: Link) {
export function formatLinkText(link: Link) {
if (link.children?.length !== 1 || link.children[0].type !== 'text') return;
const url = link.children[0].value;
// Add an exception for wiki transforms links.
Expand All @@ -34,7 +35,8 @@ function formatLinkText(link: Link) {
.replace(/([=&])/giu, '​$1​'),
// Reconnect the strings with word break opportunities after double slashes
)
.join('//​');
.join('//​')
.replace(/​(.{1,2})$/, '$1');
link.children[0].value = formatted;
}

Expand Down

0 comments on commit 3aa40b0

Please sign in to comment.