tiptap-link-card
Version:
Link Card Block for TipTap Editor
221 lines (212 loc) • 9 kB
JavaScript
import { Node, PasteRule, mergeAttributes } from '@tiptap/core';
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol, Iterator */
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
const pasteRegex = /https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z]{2,}\b(?:[-a-zA-Z0-9@:%._+~#=?!&/]*)(?:[-a-zA-Z0-9@:%._+~#=?!&/]*)/gi;
const LinkCard = Node.create({
name: "linkCard",
group: "block",
atom: true,
draggable: true,
marks: "",
whitespace: "normal",
addOptions() {
return {
openOnClick: true,
linkOnPaste: false,
dataResolver: null,
HTMLAttributes: {},
};
},
addCommands() {
return {
setLinkCard: (options) => ({ commands }) => {
return commands.insertContent({
type: this.name,
attrs: options,
});
},
setLinkCardUrl: (url) => ({ commands, editor }) => {
if (!this.options.dataResolver) {
throw new Error("dataResolver is not set. Please provide a dataResolver function.");
}
const id = Math.random().toString(36).slice(2);
((id) => __awaiter(this, void 0, void 0, function* () {
const attributes = yield this.options.dataResolver(url);
if (!attributes) {
throw new Error("Failed to resolve link card data. Please check the URL or the dataResolver function.");
}
const { pos } = editor.$node(this.name, { id });
editor.view.dispatch(editor.state.tr.setNodeMarkup(pos, undefined, attributes));
}))(id);
return commands.insertContent({
type: this.name,
attrs: {
id,
isLoading: true,
href: url,
},
});
},
};
},
addAttributes() {
return {
id: {
default: undefined,
},
isLoading: {
default: undefined,
},
href: {
default: null,
},
title: {
default: null,
},
description: {
default: null,
},
imageSrc: {
default: null,
},
};
},
parseHTML() {
return [
{
tag: "link-card",
getAttrs: (element) => {
const href = element.getAttribute("href");
if (!href)
return false;
return {
href,
title: element.getAttribute("title") || "",
description: element.getAttribute("description") || "",
imageSrc: element.getAttribute("imageSrc") || "",
};
},
},
];
},
addPasteRules() {
if (!this.options.linkOnPaste || !this.options.dataResolver) {
return [];
}
return [
new PasteRule({
find: pasteRegex,
handler: ({ match, chain, range, pasteEvent }) => {
const id = Math.random().toString(36).slice(2);
((url, id) => __awaiter(this, void 0, void 0, function* () {
const attributes = yield this.options.dataResolver(url);
if (!attributes) {
throw new Error("Failed to resolve link card data. Please check the URL or the dataResolver function.");
}
const { pos } = this.editor.$node(this.name, { id });
this.editor.view.dispatch(this.editor.state.tr.setNodeMarkup(pos, undefined, attributes));
}))(match.input, id);
const node = {
type: this.name,
attrs: {
id,
isLoading: true,
href: match.input,
},
};
return chain()
.deleteRange(range)
.insertContentAt(range.from, node)
.run();
},
}),
];
},
renderHTML({ HTMLAttributes }) {
return ["link-card", mergeAttributes(HTMLAttributes)];
},
addNodeView() {
return ({ editor, node, getPos }) => {
const root = document.createElement(this.options.openOnClick ? "a" : "div");
const attributes = this.options.HTMLAttributes;
Object.keys(attributes).forEach((key) => {
root.setAttribute(key, attributes[key]);
});
root.classList.add("link-card");
if (this.options.openOnClick) {
root.setAttribute("href", node.attrs.href || "#");
root.setAttribute("target", "_blank");
root.setAttribute("rel", "noopener noreferrer");
}
else {
root.setAttribute("data-href", node.attrs.href || "#");
}
if (node.attrs.imageSrc) {
const figure = document.createElement("figure");
figure.classList.add("link-card-figure");
const img = document.createElement("img");
img.classList.add("link-card-image");
img.src = node.attrs.imageSrc;
figure.appendChild(img);
root.appendChild(figure);
}
const meta = document.createElement("div");
meta.classList.add("link-card-meta");
if (node.attrs.title) {
const title = document.createElement("h3");
title.classList.add("link-card-title");
title.textContent = node.attrs.title;
meta.appendChild(title);
}
if (node.attrs.description) {
const description = document.createElement("p");
description.classList.add("link-card-description");
description.textContent = node.attrs.description;
meta.appendChild(description);
}
if (node.attrs.href) {
const url = new URL(node.attrs.href);
const domain = document.createElement("span");
domain.classList.add("link-card-domain");
domain.textContent = url.hostname;
meta.appendChild(domain);
}
root.appendChild(meta);
if (node.attrs.isLoading) {
const loadingIndicator = document.createElement("span");
loadingIndicator.classList.add("link-card-loading");
loadingIndicator.textContent = "Loading...";
root.appendChild(loadingIndicator);
}
return {
dom: root,
};
};
},
});
export { LinkCard, LinkCard as default, pasteRegex };
//# sourceMappingURL=index.js.map