A fully open source & end-to-end encrypted note taking alternative to Evernote.
TypeScript asp-net-coredotnet-coreelectronfosshacktoberfestnote-managmentnote-takingnote-taking-appnotebooknotesnotes-appopen-sourceopensourceprivacyproductivityreactreact-nativereactjsself-hosted
editor: add extension for embedding web clips
Abdullah Attaaa0bf3b3dcfe
diff --git a/packages/editor/src/extensions/web-clip/component.tsx b/packages/editor/src/extensions/web-clip/component.tsxnew file mode 100644index 000000000..657169e27--- /dev/null+++ b/packages/editor/src/extensions/web-clip/component.tsx@@ -0,0 +1,237 @@+/*+This file is part of the Notesnook project (https://notesnook.com/)++Copyright (C) 2022 Streetwriters (Private) Limited++This program is free software: you can redistribute it and/or modify+it under the terms of the GNU General Public License as published by+the Free Software Foundation, either version 3 of the License, or+(at your option) any later version.++This program is distributed in the hope that it will be useful,+but WITHOUT ANY WARRANTY; without even the implied warranty of+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+GNU General Public License for more details.++You should have received a copy of the GNU General Public License+along with this program. If not, see <http://www.gnu.org/licenses/>.+*/++import { Box, Flex, Text } from "@theme-ui/components";+import { useEffect, useRef, useState } from "react";+import { SelectionBasedReactNodeViewProps } from "../react";+import { Icon, Icons } from "../../toolbar";+import { WebClipAttributes, WebClipOptions } from "./web-clip";+import { DesktopOnly } from "../../components/responsive";+import { ToolbarGroup } from "../../toolbar/components/toolbar-group";++const FAILED_CONTENT = `<html><head>+<title>Failed to load web clip</title>+</head>+<body>+<p>Failed to load web clip</p>+</body>+</html>`;++export function WebClipComponent(+ props: SelectionBasedReactNodeViewProps<WebClipAttributes>+) {+ const { editor, selected, node, updateAttributes } = props;+ const [isLoading, setIsLoading] = useState(true);+ const embedRef = useRef<HTMLIFrameElement>(null);+ const resizeObserverRef = useRef<ResizeObserver>();+ const { src, title, hash, fullscreen } = node.attrs;+ const { onLoadWebClip } = editor.storage.webclip as WebClipOptions;++ useEffect(() => {+ (async function () {+ const iframe = embedRef.current;+ if (!iframe || !iframe.contentDocument) return;+ iframe.contentDocument.open();+ iframe.contentDocument.write(+ (await onLoadWebClip(editor, hash)) || FAILED_CONTENT+ );+ iframe.contentDocument.close();+ iframe.contentDocument.head.innerHTML += `<base target="_blank">`;++ setIsLoading(false);+ })();+ }, [hash, onLoadWebClip]);++ useEffect(() => {+ function fullscreenchanged() {+ if (document.fullscreenElement) {+ resizeObserverRef.current?.disconnect();+ resetIframeSize(embedRef.current);+ } else {+ updateAttributes({ fullscreen: false });+ resizeIframe(embedRef.current);++ if (embedRef.current?.contentDocument) {+ resizeObserverRef.current?.observe(+ embedRef.current?.contentDocument?.body+ );+ }+ }+ }++ document.addEventListener("fullscreenchange", fullscreenchanged);+ return () => {+ document.removeEventListener("fullscreenchange", fullscreenchanged);+ };+ }, [updateAttributes]);++ return (+ <>+ <Box+ sx={{+ mt: 2,+ display: "flex",+ flexDirection: "column",+ position: "relative",+ border: selected+ ? "2px solid var(--primary)"+ : "2px solid var(--border)",+ borderRadius: "default"+ }}+ >+ <Flex+ sx={{+ width: "100%",+ p: 1,+ bg: "bgSecondary",+ borderTopLeftRadius: "default",+ borderTopRightRadius: "default",+ cursor: "pointer",+ justifyContent: "space-between"+ }}+ title={title}+ >+ <Flex sx={{ alignItems: "center" }}>+ <Icon+ path={Icons.webClip}+ size={14}+ onClick={() => {+ window.open(src, "_blank", "noreferrer");+ }}+ />+ <Text+ variant="subBody"+ sx={{+ color: "icon",+ ml: 1,+ whiteSpace: "nowrap",+ overflow: "hidden",+ textOverflow: "ellipsis"+ }}+ >+ {title}+ </Text>+ </Flex>++ <DesktopOnly>+ {selected && (+ <Flex sx={{ position: "relative", justifyContent: "end" }}>+ <Flex+ sx={{+ position: "absolute",+ top: -10,+ mb: 2,+ alignItems: "end"+ }}+ >+ <ToolbarGroup+ editor={editor}+ tools={[+ "webclipFullScreen",+ "webclipOpenExternal",+ "webclipOpenSource"+ ]}+ sx={{+ boxShadow: "menu",+ borderRadius: "default",+ bg: "background"+ }}+ />+ </Flex>+ </Flex>+ )}+ </DesktopOnly>+ </Flex>+ <Box+ sx={{+ overflow: "hidden auto",+ maxHeight: 1080+ }}+ >+ <Box sx={{ overflow: "hidden" }}>+ <iframe+ ref={embedRef}+ width="100%"+ frameBorder={"0"}+ scrolling={fullscreen ? "yes" : "no"}+ style={{ transformOrigin: "0 0", overflow: "hidden" }}+ onLoad={() => {+ if (fullscreen) return;++ resizeIframe(embedRef.current);++ if (embedRef.current?.contentDocument) {+ resizeObserverRef.current = new ResizeObserver(() => {+ resizeIframe(embedRef.current);+ });+ resizeObserverRef.current.observe(+ embedRef.current?.contentDocument?.body+ );+ }+ }}+ />+ </Box>+ </Box>+ {isLoading && (+ <Flex+ sx={{+ position: "absolute",+ bottom: 0,+ width: "100%",+ height: "calc(100% - 20px)",+ alignItems: "center",+ justifyContent: "center"+ }}+ >+ <Icon path={Icons.loading} rotate size={32} color="disabled" />+ </Flex>+ )}+ </Box>+ </>+ );+}++function resizeIframe(iframe?: HTMLIFrameElement | null) {+ if (!iframe || !iframe.contentDocument || !iframe.contentDocument.body)+ return;++ const height = iframe.contentDocument.body.scrollHeight;+ const width = iframe.contentDocument.body.scrollWidth;++ iframe.style.height = `${height}px`;+ iframe.style.width = `${width}px`;++ const container = iframe.parentElement;+ if (!container || container.clientWidth > width) return;+ const scale = container.clientWidth / width;+ iframe.style.scale = `${scale}`;+ container.style.height = `${height * scale}px`;+}++function resetIframeSize(iframe?: HTMLIFrameElement | null) {+ if (!iframe || !iframe.contentDocument || !iframe.contentDocument.body)+ return;++ const height = iframe.contentDocument.body.scrollHeight;+ const width = iframe.contentDocument.body.scrollWidth;++ iframe.style.height = `${height}px`;+ iframe.style.width = `${width}px`;+ iframe.style.scale = `1`;+}diff --git a/packages/editor/src/extensions/web-clip/index.ts b/packages/editor/src/extensions/web-clip/index.tsnew file mode 100644index 000000000..ef2c4a884--- /dev/null+++ b/packages/editor/src/extensions/web-clip/index.ts@@ -0,0 +1,20 @@+/*+This file is part of the Notesnook project (https://notesnook.com/)++Copyright (C) 2022 Streetwriters (Private) Limited++This program is free software: you can redistribute it and/or modify+it under the terms of the GNU General Public License as published by+the Free Software Foundation, either version 3 of the License, or+(at your option) any later version.++This program is distributed in the hope that it will be useful,+but WITHOUT ANY WARRANTY; without even the implied warranty of+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+GNU General Public License for more details.++You should have received a copy of the GNU General Public License+along with this program. If not, see <http://www.gnu.org/licenses/>.+*/++export * from "./web-clip";diff --git a/packages/editor/src/extensions/web-clip/web-clip.ts b/packages/editor/src/extensions/web-clip/web-clip.tsnew file mode 100644index 000000000..d1c89c76e--- /dev/null+++ b/packages/editor/src/extensions/web-clip/web-clip.ts@@ -0,0 +1,103 @@+/*+This file is part of the Notesnook project (https://notesnook.com/)++Copyright (C) 2022 Streetwriters (Private) Limited++This program is free software: you can redistribute it and/or modify+it under the terms of the GNU General Public License as published by+the Free Software Foundation, either version 3 of the License, or+(at your option) any later version.++This program is distributed in the hope that it will be useful,+but WITHOUT ANY WARRANTY; without even the implied warranty of+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+GNU General Public License for more details.++You should have received a copy of the GNU General Public License+along with this program. If not, see <http://www.gnu.org/licenses/>.+*/++import { Node, mergeAttributes, Editor } from "@tiptap/core";+import { getDataAttribute } from "../attachment";+import { createSelectionBasedNodeView } from "../react";+import { WebClipComponent } from "./component";++export interface WebClipOptions {+ HTMLAttributes: Record<string, unknown>;+ onLoadWebClip: (+ editor: Editor,+ attachmentHash: string+ ) => Promise<string | undefined>;+}++export type WebClipAttributes = {+ fullscreen: boolean;+ src: string;+ title: string;+ hash: string;+ type: string;+};++export const WebClipNode = Node.create<+ WebClipOptions,+ Omit<WebClipOptions, "HTMLAttributes">+>({+ name: "webclip",+ content: "",+ marks: "",+ draggable: true,+ priority: 51,++ addOptions() {+ return {+ HTMLAttributes: {},+ onLoadWebClip: () => Promise.resolve(undefined)+ };+ },++ addStorage() {+ return {+ onLoadWebClip: this.options.onLoadWebClip+ };+ },++ group() {+ return "block";+ },++ addAttributes() {+ return {+ fullscreen: {+ rendered: false,+ default: false+ },+ src: {+ default: null+ },+ title: {+ default: null+ },+ hash: getDataAttribute("hash"),+ type: getDataAttribute("mime")+ };+ },++ parseHTML() {+ return [+ {+ tag: "iframe[data-hash]"+ }+ ];+ },++ renderHTML({ HTMLAttributes }) {+ return [+ "iframe",+ mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)+ ];+ },++ addNodeView() {+ return createSelectionBasedNodeView(WebClipComponent);+ }+});diff --git a/packages/editor/src/index.ts b/packages/editor/src/index.tsindex 4eeaf0165..2d110c168 100644--- a/packages/editor/src/index.ts+++ b/packages/editor/src/index.ts@@ -74,6 +74,7 @@ import { DateTime } from "./extensions/date-time";import { OpenLink, OpenLinkOptions } from "./extensions/open-link";import HorizontalRule from "@tiptap/extension-horizontal-rule";import { KeyMap } from "./extensions/key-map";+import { WebClipNode, WebClipOptions } from "./extensions/web-clip";const CoreExtensions = Object.entries(TiptapCoreExtensions)// we will implement our own customized clipboard serializer@@ -81,7 +82,8 @@ const CoreExtensions = Object.entries(TiptapCoreExtensions).map(([, extension]) => extension);type TiptapOptions = EditorOptions &- AttachmentOptions &+ Omit<AttachmentOptions, "HTMLAttributes"> &+ Omit<WebClipOptions, "HTMLAttributes"> &OpenLinkOptions & {theme: Theme;isMobile?: boolean;@@ -102,6 +104,7 @@ const useTiptap = (onOpenAttachmentPicker,onOpenLink,onBeforeCreate,+ onLoadWebClip,...restOptions} = options;const PortalProviderAPI = usePortalProvider();@@ -229,7 +232,10 @@ const useTiptap = (KeepInView,SelectionPersist,DateTime,- KeyMap+ KeyMap,+ WebClipNode.configure({+ onLoadWebClip+ })],onBeforeCreate: ({ editor }) => {editor.storage.portalProviderAPI = PortalProviderAPI;@@ -242,7 +248,8 @@ const useTiptap = (onOpenAttachmentPicker,PortalProviderAPI,onBeforeCreate,- onOpenLink+ onOpenLink,+ onLoadWebClip]);diff --git a/packages/editor/src/toolbar/icons.ts b/packages/editor/src/toolbar/icons.tsindex e804b06b5..64c3c5d16 100644--- a/packages/editor/src/toolbar/icons.ts+++ b/packages/editor/src/toolbar/icons.ts@@ -108,7 +108,11 @@ import {mdiProgressAlert,mdiContentSaveOutline,mdiClipboardOutline,- mdiNotificationClearAll+ mdiNotificationClearAll,+ mdiNewspaper,+ mdiFullscreen,+ mdiWeb,+ mdiPageNextOutline} from "@mdi/js";export const Icons = {@@ -138,11 +142,17 @@ export const Icons = {link: mdiLinkPlus,linkRemove: mdiLinkOff,openLink: mdiOpenInNew,+ openSource: mdiWeb,+ webClip: mdiNewspaper,+ simplifyWebClip: mdiPageNextOutline,linkEdit:"m19 14 1.28 1.28c.22.21.22.56 0 .77l-1 1L17.23 15l1-1c.11-.11.25-.17.39-.17s.27.06.38.17m-.3 3.63-6.06 6.07h-2.06v-2.06l6.07-6.06zM7 7h4v2H7c-1.6568542 0-3 1.343146-3 3s1.3431458 3 3 3h4v2H7c-2.7614237 0-5-2.238576-5-5 0-2.7614237 2.2385763-5 5-5m10 0c2.761424 0 5 2.2385763 5 5h-2c0-1.656854-1.343146-3-3-3h-4V7h4m-9 4h8v2H8v-2",linkSettings:"M7 7h4v2H7c-1.6568542 0-3 1.343146-3 3s1.3431458 3 3 3h4v2H7c-2.7614237 0-5-2.238576-5-5 0-2.7614237 2.2385763-5 5-5m10 0c2.761424 0 5 2.2385763 5 5h-2c0-1.656854-1.343146-3-3-3h-4V7h4m-9 4h8v2H8v-2m15.119777 8.323608-1.07-.82c.02-.17.04-.33.04-.5 0-.17-.01-.33-.04-.5l1.06-.82c.09258-.07939.117526-.212463.06-.32l-1-1.73c-.06-.13-.19-.13-.33-.13l-1.22.5c-.28-.18-.54-.35-.85-.47l-.19-1.32c-.01-.12-.12-.21-.24-.21h-2c-.12 0-.23.09-.25.21l-.19 1.32c-.3.13-.59.29-.85.47l-1.24-.5c-.11 0-.24 0-.31.13l-1 1.73c-.06.11-.04.24.06.32l1.06.82c-.03989.33214-.03989.66786 0 1l-1.06.82c-.09258.07939-.117526.212462-.06.32l1 1.73c.06.13.19.13.31.13l1.24-.5c.26.18.54.35.85.47l.19 1.32c.02.12.12.21.25.21h2c.12 0 .23-.09.25-.21l.19-1.32c.3-.13.56-.29.84-.47l1.22.5c.14 0 .27 0 .34-.13l1-1.73c.05753-.107538.03258-.240607-.06-.32m-4.78.18c-.83 0-1.5-.67-1.5-1.5s.68-1.5 1.5-1.5 1.5.67 1.5 1.5-.66 1.5-1.5 1.5z",+ webclipSettings:+ "m23.15375 19.82-1.07-.82c.02-.17.04-.33.04-.5 0-.17-.01-.33-.04-.5l1.06-.82c.09258-.07939.117526-.212463.06-.32l-1-1.73c-.06-.13-.19-.13-.33-.13l-1.22.5c-.28-.18-.54-.35-.85-.47l-.19-1.32c-.01-.12-.12-.21-.24-.21h-2c-.12 0-.23.09-.25.21l-.19 1.32c-.3.13-.59.29-.85.47l-1.24-.5c-.11 0-.24 0-.31.13l-1 1.73c-.06.11-.04.24.06.32l1.06.82c-.03989.33214-.03989.66786 0 1l-1.06.82c-.09258.07939-.117526.212463-.06.32l1 1.73c.06.13.19.13.31.13l1.24-.5c.26.18.54.35.85.47l.19 1.32c.02.12.12.21.25.21h2c.12 0 .23-.09.25-.21l.19-1.32c.3-.13.56-.29.84-.47l1.22.5c.14 0 .27 0 .34-.13l1-1.73c.05753-.107537.03258-.240606-.06-.32m-4.78.18c-.83 0-1.5-.67-1.5-1.5s.68-1.5 1.5-1.5 1.5.67 1.5 1.5-.66 1.5-1.5 1.5zM20.33 4.67 18.67 3 17 4.67 15.33 3l-1.66 1.67L12 3l-1.67 1.67L8.67 3 7 4.67 5.33 3 3.67 4.67 2 3v16c0 1.104569.8954305 2 2 2h8.8c-.51-.88-.8-1.91-.8-3 0-1.23.37-2.37 1-3.32V13h1.68c.95-.63 2.09-1 3.32-1 1.53 0 2.93.58 4 1.5V3l-1.67 1.67M11 19H4v-6h7v6m9-8H4V8h16v3",+ fullscreen: mdiFullscreen,url: mdiLink,image: mdiImageOutline,imageDownload: mdiProgressDownload,diff --git a/packages/editor/src/toolbar/tool-definitions.ts b/packages/editor/src/toolbar/tool-definitions.tsindex 2954af0eb..24a5e486c 100644--- a/packages/editor/src/toolbar/tool-definitions.ts+++ b/packages/editor/src/toolbar/tool-definitions.ts@@ -299,6 +299,26 @@ const tools: Record<ToolId, ToolDefinition> = {title: "Embed properties",conditional: true},+ webclipSettings: {+ icon: "webclipSettings",+ title: "Web clip settings",+ conditional: true+ },+ webclipFullScreen: {+ icon: "fullscreen",+ title: "Full screen",+ conditional: true+ },+ webclipOpenExternal: {+ icon: "openLink",+ title: "Open in new tab",+ conditional: true+ },+ webclipOpenSource: {+ icon: "openSource",+ title: "Open source",+ conditional: true+ },outdent: {icon: "outdent",title: "Lift list item",diff --git a/packages/editor/src/toolbar/tools/index.ts b/packages/editor/src/toolbar/tools/index.tsindex b2966c461..52f7dc8c4 100644--- a/packages/editor/src/toolbar/tools/index.ts+++ b/packages/editor/src/toolbar/tools/index.ts@@ -81,6 +81,12 @@ import {EmbedSettings} from "./embed";import { AddLink, EditLink, RemoveLink, LinkSettings, OpenLink } from "./link";+import {+ WebClipFullScreen,+ WebClipSettings,+ WebClipOpenExternal,+ WebClipOpenSource+} from "./web-clip";export type ToolId = keyof typeof tools;const tools = {@@ -122,6 +128,11 @@ const tools = {embedProperties: EmbedProperties,embedSettings: EmbedSettings,+ webclipFullScreen: WebClipFullScreen,+ webclipOpenExternal: WebClipOpenExternal,+ webclipOpenSource: WebClipOpenSource,+ webclipSettings: WebClipSettings,+attachmentSettings: AttachmentSettings,downloadAttachment: DownloadAttachment,removeAttachment: RemoveAttachment,diff --git a/packages/editor/src/toolbar/tools/web-clip.tsx b/packages/editor/src/toolbar/tools/web-clip.tsxnew file mode 100644index 000000000..310c25e02--- /dev/null+++ b/packages/editor/src/toolbar/tools/web-clip.tsx@@ -0,0 +1,106 @@+/*+This file is part of the Notesnook project (https://notesnook.com/)++Copyright (C) 2022 Streetwriters (Private) Limited++This program is free software: you can redistribute it and/or modify+it under the terms of the GNU General Public License as published by+the Free Software Foundation, either version 3 of the License, or+(at your option) any later version.++This program is distributed in the hope that it will be useful,+but WITHOUT ANY WARRANTY; without even the implied warranty of+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+GNU General Public License for more details.++You should have received a copy of the GNU General Public License+along with this program. If not, see <http://www.gnu.org/licenses/>.+*/++import { ToolProps } from "../types";+import { ToolButton } from "../components/tool-button";+import { MoreTools } from "../components/more-tools";+import { useToolbarLocation } from "../stores/toolbar-store";+import { findSelectedNode, selectionToOffset } from "../utils/prosemirror";++export function WebClipSettings(props: ToolProps) {+ const { editor } = props;+ const isBottom = useToolbarLocation() === "bottom";+ if (!editor.isActive("webclip") || !isBottom) return null;++ return (+ <MoreTools+ {...props}+ autoCloseOnUnmount+ popupId="webclipSettings"+ tools={["webclipFullScreen"]}+ />+ );+}++export function WebClipFullScreen(props: ToolProps) {+ const { editor } = props;++ return (+ <ToolButton+ {...props}+ toggled={false}+ onClick={() => {+ const dom = editor.current?.view.nodeDOM(+ selectionToOffset(editor.state).from+ );+ if (!dom || !(dom instanceof HTMLElement)) return;++ const iframe = dom.querySelector("iframe");+ if (!iframe) return;++ iframe.requestFullscreen();+ editor.current?.commands.updateAttributes("webclip", {+ fullscreen: true+ });+ }}+ />+ );+}++export function WebClipOpenExternal(props: ToolProps) {+ const { editor } = props;+ return (+ <ToolButton+ {...props}+ toggled={false}+ onClick={async () => {+ const dom = editor.current?.view.nodeDOM(+ selectionToOffset(editor.state).from+ );+ if (!dom || !(dom instanceof HTMLElement)) return;++ const iframe = dom.querySelector("iframe");+ if (!iframe || !iframe.contentDocument) return;++ const url = URL.createObjectURL(+ new Blob(+ ["\ufeff", iframe.contentDocument.documentElement.outerHTML],+ { type: "text/html" }+ )+ );+ editor.current?.commands.openLink(url);+ }}+ />+ );+}++export function WebClipOpenSource(props: ToolProps) {+ const { editor } = props;+ return (+ <ToolButton+ {...props}+ toggled={false}+ onClick={async () => {+ const node = findSelectedNode(editor, "webclip");+ if (!node) return;+ editor.current?.commands.openLink(node.attrs.src);+ }}+ />+ );+}