Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
12 changes: 12 additions & 0 deletions __tests__/migration/brackets.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { migrate } from '../helpers';

describe('migration of brackets', () => {
it('should retain opening bracket after a link reference brackets', () => {
const md = '[foo][bar';
const mdx = migrate(md);
expect(mdx).toMatchInlineSnapshot(`
"\\[foo]\\[bar
"
`);
});
});
19 changes: 17 additions & 2 deletions processor/migration/linkReference.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import type { Definition, LinkReference, Root, Text } from 'mdast';
import type { VFile } from 'vfile';

import { visit } from 'unist-util-visit';

const linkReferenceTransformer =
() =>
(tree: Root): Root => {
(tree: Root, vfile: VFile): Root => {
const originalContent = vfile.toString();

visit(tree, 'linkReference', (node: LinkReference, index, parent) => {
const definitions = {};

Expand All @@ -14,9 +17,21 @@ const linkReferenceTransformer =

if (node.label === node.identifier && parent) {
if (!(node.identifier in definitions)) {
// Use offsets from the source file so we can slice out the exact string, including stray '[' characters.
const startOffset = node.position?.start.offset;
const endOffset = node.position?.end.offset;
const sourceValue =
typeof startOffset === 'number' && typeof endOffset === 'number'
? originalContent.slice(startOffset, endOffset)
: null;
// If offsets aren't available we regenerate a safe `[label]` string instead.
const fallbackLabel = node.label || node.identifier || '';
// Preserve the sliced substring when it contains the dangling '[', otherwise synthesize `[label]`.
const value = sourceValue?.endsWith('[') ? sourceValue : `[${fallbackLabel}]`;

parent.children[index] = {
type: 'text',
value: `[${node.label}]`,
value,
position: node.position,
} as Text;
}
Expand Down