Skip to content
Closed
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
13 changes: 6 additions & 7 deletions src/blocks/components/fields/components/wysiwyg.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ import parserHtml from 'prettier/plugins/html';
import prettier from 'prettier/standalone';
import { Base } from '@/blocks/components/base';
import { Code } from '@/blocks/components/fields/components/code';
import {
getWysiwygLinkAttributes,
getWysiwygLinkHTMLAttributes,
} from '@/blocks/utils/wysiwyg-link';
import { Alignment, BlockstudioAttribute } from '@/types/block';
import { __ } from '@/utils/__';
import { css } from '@/utils/css';
Expand Down Expand Up @@ -76,7 +80,7 @@ export const WYSIWYG = ({
Link.configure({
autolink: false,
openOnClick: false,
HTMLAttributes: item?.toolbar?.formats?.link?.attributes || {},
HTMLAttributes: getWysiwygLinkHTMLAttributes(item),
}),
Underline,
TextAlign.configure({
Expand Down Expand Up @@ -443,12 +447,7 @@ export const WYSIWYG = ({
from: selection?.[0] ?? 0,
to: selection?.[1] ?? 0,
});
editor.commands.setLink({
href: (e as unknown as BlockstudioAttribute).url,
target: (e as unknown as BlockstudioAttribute).opensInNewTab
? '_blank'
: '_self',
});
editor.commands.setLink(getWysiwygLinkAttributes(item, e));
}}
onRemove={() => {
editor.commands.setTextSelection({
Expand Down
38 changes: 38 additions & 0 deletions src/blocks/utils/wysiwyg-link.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import type { BlockstudioAttribute } from '@/types/block';

type WysiwygLink = {
url: string;
target?: string;
rel?: string;
};

// Tiptap's Link renders target="_blank" and rel="noopener noreferrer nofollow"
// on every link unless HTMLAttributes resets them, and also falls back to
// these values for stored links without the attributes. Links should only
// carry what the field configures or the link modal sets.
export const getWysiwygLinkHTMLAttributes = (
item: BlockstudioAttribute,
): Record<string, any> => ({
target: null,
rel: null,
...item?.toolbar?.formats?.link?.attributes,
});

// Explicit target and rel replace the configured ones on the rendered link,
// so the configured rel is kept and the new tab tokens from the link modal
// are added to it.
export const getWysiwygLinkAttributes = (
item: BlockstudioAttribute,
link: WysiwygLink,
) => {
const configured = getWysiwygLinkHTMLAttributes(item);
const rel = new Set(
`${configured.rel ?? ''} ${link.rel ?? ''}`.split(/\s+/).filter(Boolean),
);

return {
href: link.url,
target: link.target ?? configured.target ?? null,
rel: Array.from(rel).join(' ') || null,
};
};
132 changes: 132 additions & 0 deletions tests/client/wysiwyg-link.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import { Editor } from '@tiptap/core';
import { Link } from '@tiptap/extension-link';
import StarterKit from '@tiptap/starter-kit';
import assert from 'node:assert/strict';
import { test } from 'node:test';
import {
getWysiwygLinkAttributes,
getWysiwygLinkHTMLAttributes,
} from '../../src/blocks/utils/wysiwyg-link';
import type { BlockstudioAttribute } from '../../src/types/block';

const field = (link: Record<string, unknown>) =>
({ type: 'wysiwyg', toolbar: { formats: { link } } }) as BlockstudioAttribute;

const createEditor = (item: BlockstudioAttribute) =>
new Editor({
element: null,
extensions: [
StarterKit.configure({ link: false }),
Link.configure({
autolink: false,
openOnClick: false,
HTMLAttributes: getWysiwygLinkHTMLAttributes(item),
}),
],
content: {
type: 'doc',
content: [
{ type: 'paragraph', content: [{ type: 'text', text: 'Hello world' }] },
],
},
});

// The link mark's DOM spec without null values, which ProseMirror's
// serializer skips. These are the attributes getHTML() writes.
const rendered = (editor: Editor) => {
const mark = editor.state.doc
.nodeAt(1)
?.marks.find(({ type }) => type.name === 'link');
assert.ok(mark);
const [, attributes] = editor.schema.marks.link.spec.toDOM?.(mark, true) as [
string,
Record<string, unknown>,
];

return Object.fromEntries(
Object.entries(attributes).filter(([, value]) => value != null),
);
};

// The link modal hands over the link with target and rel already set for
// "Open in new tab" (normalizeLinkChange in fields/components/link.tsx).
const modalLink = (url: string, opensInNewTab: boolean) =>
opensInNewTab
? { url, opensInNewTab, target: '_blank', rel: 'noreferrer noopener' }
: { url, opensInNewTab };

const insertLink = (
editor: Editor,
item: BlockstudioAttribute,
link: ReturnType<typeof modalLink>,
) => {
editor.commands.setTextSelection({ from: 1, to: 6 });
assert.equal(
editor.commands.setLink(getWysiwygLinkAttributes(item, link)),
true,
);
};

for (const url of ['/contact/', 'https://wordpress.org/']) {
test(`toolbar link to ${url} only gets target and rel for a new tab`, () => {
const item = field({ opensInNewTab: true });

const sameTab = createEditor(item);
insertLink(sameTab, item, modalLink(url, false));
assert.deepEqual(rendered(sameTab), { href: url });

const newTab = createEditor(item);
insertLink(newTab, item, modalLink(url, true));
assert.deepEqual(rendered(newTab), {
href: url,
target: '_blank',
rel: 'noreferrer noopener',
});
});
}

test('turning off "Open in new tab" removes target and rel again', () => {
const item = field({ opensInNewTab: true });
const editor = createEditor(item);

insertLink(editor, item, modalLink('/contact/', true));
insertLink(editor, item, modalLink('/contact/', false));

assert.deepEqual(rendered(editor), { href: '/contact/' });
});

test('stored links without target or rel do not get them on the next edit', () => {
const item = field({ opensInNewTab: true });
const editor = createEditor(item);

// Parsing a stored <a href> falls back to the attribute defaults for
// target and rel when the element has none.
editor.commands.setTextSelection({ from: 1, to: 6 });
editor.commands.setMark('link', { href: '/contact/' });

assert.deepEqual(rendered(editor), { href: '/contact/' });
});

test('configured link attributes apply to every link', () => {
const item = field({
opensInNewTab: true,
attributes: { rel: 'nofollow', class: 'field-link' },
});

const sameTab = createEditor(item);
insertLink(sameTab, item, modalLink('/contact/', false));
assert.deepEqual(rendered(sameTab), {
href: '/contact/',
rel: 'nofollow',
class: 'field-link',
});

const newTab = createEditor(item);
insertLink(newTab, item, modalLink('/contact/', true));
assert.deepEqual(rendered(newTab), {
href: '/contact/',
target: '_blank',
rel: 'nofollow noreferrer noopener',
class: 'field-link',
});
});