From 22c0ddd14b226d5c9787437703d3d36203ee3b45 Mon Sep 17 00:00:00 2001 From: Innei Date: Sun, 13 Oct 2024 14:51:48 +0800 Subject: [PATCH 01/52] fix: feed column auto scroll lead cause the whole page to move Signed-off-by: Innei --- .../entry-column/layouts/EntryListHeader.tsx | 4 ++-- .../src/modules/feed-column/category.tsx | 20 +++++++++++++++---- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/apps/renderer/src/modules/entry-column/layouts/EntryListHeader.tsx b/apps/renderer/src/modules/entry-column/layouts/EntryListHeader.tsx index d079cec84..182133e6d 100644 --- a/apps/renderer/src/modules/entry-column/layouts/EntryListHeader.tsx +++ b/apps/renderer/src/modules/entry-column/layouts/EntryListHeader.tsx @@ -46,12 +46,12 @@ export const EntryListHeader: FC<{ const titleInfo = !!headerTitle && (
-
+
{headerTitle}
-
+
{totalCount || 0} {t("quantifier.piece", { ns: "common" })} {unreadOnly && !isInCollectionList ? t("words.unread") : ""} {t("space", { ns: "common" })} diff --git a/apps/renderer/src/modules/feed-column/category.tsx b/apps/renderer/src/modules/feed-column/category.tsx index b304abbee..e0ab3932d 100644 --- a/apps/renderer/src/modules/feed-column/category.tsx +++ b/apps/renderer/src/modules/feed-column/category.tsx @@ -7,10 +7,11 @@ import { useOnClickOutside } from "usehooks-ts" import { MotionButtonBase } from "~/components/ui/button" import { LoadingCircle } from "~/components/ui/loading" +import { useScrollViewElement } from "~/components/ui/scroll-area/hooks" import { ROUTE_FEED_IN_FOLDER, views } from "~/constants" import { useNavigateEntry } from "~/hooks/biz/useNavigateEntry" import { getRouteParams, useRouteParamsSelector } from "~/hooks/biz/useRouteParams" -import { useAnyPointDown, useInputComposition } from "~/hooks/common" +import { useAnyPointDown, useInputComposition, useRefValue } from "~/hooks/common" import { stopPropagation } from "~/lib/dom" import type { FeedViewType } from "~/lib/enum" import { showNativeMenu } from "~/lib/native-menu" @@ -64,6 +65,8 @@ function FeedCategoryImpl({ data: ids, view, categoryOpenStateData }: FeedCatego const shouldOpen = useRouteParamsSelector( (s) => typeof s.feedId === "string" && ids.includes(s.feedId), ) + const scroller = useScrollViewElement() + const scrollerRef = useRefValue(scroller) useEffect(() => { if (shouldOpen) { setOpen(true) @@ -71,12 +74,21 @@ function FeedCategoryImpl({ data: ids, view, categoryOpenStateData }: FeedCatego const $items = itemsRef.current if (!$items) return - $items.querySelector(`[data-feed-id="${getRouteParams().feedId}"]`)?.scrollIntoView({ - block: "center", + const $target = $items.querySelector( + `[data-feed-id="${getRouteParams().feedId}"]`, + ) as HTMLElement + if (!$target) return + + const $scroller = scrollerRef.current + if (!$scroller) return + + const scrollTop = $target.offsetTop - $scroller.clientHeight / 2 + $scroller.scrollTo({ + top: scrollTop, behavior: "smooth", }) } - }, [shouldOpen]) + }, [scrollerRef, shouldOpen]) const expansion = folderName ? categoryOpenStateData[folderName] : true useEffect(() => { From df05044c0e326e3634df43511642f9c125ae95b7 Mon Sep 17 00:00:00 2001 From: Innei Date: Sun, 13 Oct 2024 18:20:54 +0800 Subject: [PATCH 02/52] fix: modal overlay Signed-off-by: Innei --- .../src/components/ui/modal/stacked/modal.tsx | 11 +++++++---- .../src/components/ui/modal/stacked/provider.tsx | 16 ++++++++++++++-- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/apps/renderer/src/components/ui/modal/stacked/modal.tsx b/apps/renderer/src/components/ui/modal/stacked/modal.tsx index 1aabbfe51..0e34f2736 100644 --- a/apps/renderer/src/components/ui/modal/stacked/modal.tsx +++ b/apps/renderer/src/components/ui/modal/stacked/modal.tsx @@ -24,7 +24,6 @@ import { AppErrorBoundary } from "~/components/common/AppErrorBoundary" import { SafeFragment } from "~/components/common/Fragment" import { m } from "~/components/common/Motion" import { ErrorComponentType } from "~/components/errors/enum" -import { resizableOnly } from "~/components/ui/modal" import { ElECTRON_CUSTOM_TITLEBAR_HEIGHT, isElectronBuild } from "~/constants" import { useSwitchHotKeyScope } from "~/hooks/common" import { nextFrame, stopPropagation } from "~/lib/dom" @@ -52,10 +51,14 @@ export const ModalInternal = memo( index: number isTop: boolean + isBottom: boolean overlayOptions?: ModalOverlayOptions onClose?: (open: boolean) => void } & PropsWithChildren - >(function Modal({ item, overlayOptions, onClose: onPropsClose, children, isTop }, ref) { + >(function Modal( + { item, overlayOptions, onClose: onPropsClose, children, isTop, isBottom }, + ref, + ) { const { CustomModalComponent, modalClassName, @@ -273,7 +276,7 @@ export const ModalInternal = memo( ) @@ -371,7 +374,7 @@ export const ModalInternal = memo( }} > { const topModalIndex = stack.findLastIndex((item) => item.modal) const overlayIndex = stack.findLastIndex((item) => item.overlay || item.modal) const overlayOptions = stack[overlayIndex]?.overlayOptions + + const hasModalStack = stack.length > 0 + + useEffect(() => { + // NOTE: document.body is being used by radix's dismissable, + // and using that will cause radix to get the value of `none` as the store value, + // and then revert to `none` instead of `auto` after a modal dismiss. + document.documentElement.style.pointerEvents = hasModalStack ? "none" : "auto" + document.documentElement.dataset.hasModal = hasModalStack.toString() + }, [hasModalStack]) return ( {stack.map((item, index) => ( ))} From f04df1e823611840dee5f25a16c3271c29c9a34f Mon Sep 17 00:00:00 2001 From: Stephen Zhou <38493346+hyoban@users.noreply.github.com> Date: Mon, 14 Oct 2024 09:44:19 +0800 Subject: [PATCH 03/52] chore: type check --- apps/renderer/src/components/ui/modal/stacked/modal.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/renderer/src/components/ui/modal/stacked/modal.tsx b/apps/renderer/src/components/ui/modal/stacked/modal.tsx index 0e34f2736..b158482d7 100644 --- a/apps/renderer/src/components/ui/modal/stacked/modal.tsx +++ b/apps/renderer/src/components/ui/modal/stacked/modal.tsx @@ -50,8 +50,8 @@ export const ModalInternal = memo( item: ModalProps & { id: string } index: number - isTop: boolean - isBottom: boolean + isTop?: boolean + isBottom?: boolean overlayOptions?: ModalOverlayOptions onClose?: (open: boolean) => void } & PropsWithChildren From 5d78da6f1064393ba3a7417ec79788989e9f9e7b Mon Sep 17 00:00:00 2001 From: Stephen Zhou <38493346+hyoban@users.noreply.github.com> Date: Mon, 14 Oct 2024 10:06:16 +0800 Subject: [PATCH 04/52] fix: can not show cmdk search type --- apps/renderer/src/modules/panel/cmdk.tsx | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/apps/renderer/src/modules/panel/cmdk.tsx b/apps/renderer/src/modules/panel/cmdk.tsx index a482f7b15..64041cb2a 100644 --- a/apps/renderer/src/modules/panel/cmdk.tsx +++ b/apps/renderer/src/modules/panel/cmdk.tsx @@ -136,7 +136,6 @@ export const SearchCmdK: React.FC = () => { "flex min-h-[50vh] flex-col bg-zinc-50/85 shadow-2xl backdrop-blur-xl dark:bg-neutral-900/90 md:rounded-xl", "border-0 border-zinc-300 dark:border-zinc-700 md:border", "absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2", - "z-10", )} > -
+
{feed && } {title} From d850a5c328aa0905278766f45cd21bd88e5352e0 Mon Sep 17 00:00:00 2001 From: Stephen Zhou <38493346+hyoban@users.noreply.github.com> Date: Mon, 14 Oct 2024 10:13:12 +0800 Subject: [PATCH 05/52] fix: modal escape conflict with cmdk --- apps/renderer/src/modules/panel/cmdk.tsx | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/apps/renderer/src/modules/panel/cmdk.tsx b/apps/renderer/src/modules/panel/cmdk.tsx index 64041cb2a..23323beaa 100644 --- a/apps/renderer/src/modules/panel/cmdk.tsx +++ b/apps/renderer/src/modules/panel/cmdk.tsx @@ -11,6 +11,7 @@ import { LoadMoreIndicator } from "~/components/common/LoadMoreIndicator" import { FeedIcon } from "~/components/feed-icon" import { EmptyIcon } from "~/components/icons/empty" import { Logo } from "~/components/icons/logo" +import { useModalStack } from "~/components/ui/modal" import { ScrollArea } from "~/components/ui/scroll-area" import { Select, @@ -58,6 +59,8 @@ export const SearchCmdK: React.FC = () => { const dialogRef = React.useRef(null) const scrollViewRef = React.useRef(null) + const { getTopModalStack } = useModalStack() + React.useEffect(() => { const $input = inputRef.current if (open && $input) { @@ -71,7 +74,7 @@ export const SearchCmdK: React.FC = () => { (e) => { const $input = inputRef.current - if (e.key === "Escape" && !isCompositionRef.current) { + if (e.key === "Escape" && !isCompositionRef.current && !getTopModalStack()) { setAppSearchOpen(false) return } @@ -82,7 +85,7 @@ export const SearchCmdK: React.FC = () => { $input?.focus() } }, - [isCompositionRef], + [getTopModalStack, isCompositionRef], ) const [isPending, startTransition] = React.useTransition() const handleSearch = React.useCallback( From 29b893a23e4d7602bdcb0c2ac0df3c5fdce6a540 Mon Sep 17 00:00:00 2001 From: Stephen Zhou <38493346+hyoban@users.noreply.github.com> Date: Mon, 14 Oct 2024 10:47:24 +0800 Subject: [PATCH 06/52] fix: hide some actions for inbox close #912 --- apps/renderer/src/hooks/biz/useEntryActions.tsx | 3 ++- apps/renderer/src/hooks/biz/useFeedActions.tsx | 5 ++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/apps/renderer/src/hooks/biz/useEntryActions.tsx b/apps/renderer/src/hooks/biz/useEntryActions.tsx index 1b2c006c2..b9673fd5a 100644 --- a/apps/renderer/src/hooks/biz/useEntryActions.tsx +++ b/apps/renderer/src/hooks/biz/useEntryActions.tsx @@ -137,6 +137,7 @@ export const useEntryActions = ({ const { t } = useTranslation() const feed = useFeedById(entry?.feedId) + const isInbox = feed?.type === "inbox" const populatedEntry = useMemo(() => { if (!entry) return null @@ -312,7 +313,7 @@ export const useEntryActions = ({ shortcut: shortcuts.entry.tip.key, name: t("entry_actions.tip"), className: "i-mgc-power-outline", - hide: feed?.ownerUserId === whoami()?.id, + hide: isInbox || feed?.ownerUserId === whoami()?.id, onClick: () => { nextFrame(openTipModal) }, diff --git a/apps/renderer/src/hooks/biz/useFeedActions.tsx b/apps/renderer/src/hooks/biz/useFeedActions.tsx index 7f0df8ee8..d1b120263 100644 --- a/apps/renderer/src/hooks/biz/useFeedActions.tsx +++ b/apps/renderer/src/hooks/biz/useFeedActions.tsx @@ -38,6 +38,7 @@ export const useFeedActions = ({ }) => { const { t } = useTranslation() const feed = useFeedById(feedId) + const isInbox = feed?.type === "inbox" const subscription = useSubscriptionByFeedId(feedId) const { present } = useModalStack() const deleteSubscription = useDeleteSubscription({}) @@ -91,6 +92,7 @@ export const useFeedActions = ({ { type: "text" as const, label: t("sidebar.feed_column.context_menu.add_feeds_to_list"), + disabled: isInbox, submenu: [ ...listByView.map((list) => { const isIncluded = list.feedIds.includes(feedId) @@ -150,13 +152,14 @@ export const useFeedActions = ({ ? t("sidebar.feed_actions.unfollow_feed") : t("sidebar.feed_actions.unfollow"), shortcut: "Meta+Backspace", + disabled: isInbox, click: () => deleteSubscription.mutate(subscription), }, { type: "text" as const, label: t("sidebar.feed_actions.navigate_to_feed"), shortcut: "Meta+G", - disabled: !isEntryList || getRouteParams().feedId === feedId, + disabled: isInbox || !isEntryList || getRouteParams().feedId === feedId, click: () => { navigateEntry({ feedId }) }, From 5b9ee0a622312b8aa19e9eb1ea40f3eab38ce384 Mon Sep 17 00:00:00 2001 From: Innei Date: Mon, 14 Oct 2024 12:01:14 +0800 Subject: [PATCH 07/52] fix: login modal overlay and parse feed site url Signed-off-by: Innei --- apps/renderer/src/components/feed-summary.tsx | 19 ++++++++++--------- apps/renderer/src/pages/(main)/layout.tsx | 1 + 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/apps/renderer/src/components/feed-summary.tsx b/apps/renderer/src/components/feed-summary.tsx index ad21f2f6f..8959d6033 100644 --- a/apps/renderer/src/components/feed-summary.tsx +++ b/apps/renderer/src/components/feed-summary.tsx @@ -17,17 +17,12 @@ export function FollowSummary({ docs?: string className?: string }) { - let siteLink - let feedLink + let siteLink: string | undefined + let feedLink: string | undefined let feedTitle = feed.title - let feedText + let feedText: string | undefined + switch (feed.type) { - case "feed": { - siteLink = feed.siteUrl || void 0 - feedLink = feed.url || docs - feedText = feed.url || docs - break - } case "list": { siteLink = `${WEB_URL}/list/${feed.id}` feedLink = siteLink @@ -41,6 +36,12 @@ export function FollowSummary({ feedTitle = feed.title || `${feed.id}'s Inbox` break } + default: { + siteLink = feed.siteUrl || void 0 + feedLink = feed.url || docs + feedText = feed.url || docs + break + } } return ( diff --git a/apps/renderer/src/pages/(main)/layout.tsx b/apps/renderer/src/pages/(main)/layout.tsx index 76144111e..df05b2aac 100644 --- a/apps/renderer/src/pages/(main)/layout.tsx +++ b/apps/renderer/src/pages/(main)/layout.tsx @@ -129,6 +129,7 @@ export function Component() { id="login" CustomModalComponent={PlainModal} open + overlay title="Login" canClose={false} clickOutsideToDismiss={false} From 7ef68282cec5d8e582c971acd9461a2cde7737c3 Mon Sep 17 00:00:00 2001 From: Stephen Zhou <38493346+hyoban@users.noreply.github.com> Date: Mon, 14 Oct 2024 12:37:51 +0800 Subject: [PATCH 08/52] chore: missing return --- apps/renderer/src/lib/parse-html.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/renderer/src/lib/parse-html.ts b/apps/renderer/src/lib/parse-html.ts index 4b6076a76..d76fffa49 100644 --- a/apps/renderer/src/lib/parse-html.ts +++ b/apps/renderer/src/lib/parse-html.ts @@ -191,7 +191,7 @@ export const parseHtml = ( language = children.props.className.replace("language-", "") } const code = "props" in children && children.props.children - if (!code) createElement("pre", props, props.children) + if (!code) return createElement("pre", props, props.children) try { codeString = extractCodeFromHtml(renderToString(code)) From 3f06c717a2b5b00fb4b76b6f7be50011ba53f742 Mon Sep 17 00:00:00 2001 From: Innei Date: Mon, 14 Oct 2024 13:09:06 +0800 Subject: [PATCH 09/52] fix: hijs code block parser, fixed #928 Signed-off-by: Innei --- apps/main/src/lib/readability.ts | 4 +- .../src/lib/__tests__/parse-html.test.ts | 376 +++ .../lib/{ => __tests__}/path-parser.test.ts | 2 +- apps/renderer/src/lib/parse-html.ts | 23 +- apps/renderer/vitest.config.ts | 6 +- package.json | 5 +- patches/@mozilla__readability.patch | 13 + patches/@mozilla__readability@0.5.0.patch | 2109 ----------------- pnpm-lock.yaml | 46 +- 9 files changed, 455 insertions(+), 2129 deletions(-) create mode 100644 apps/renderer/src/lib/__tests__/parse-html.test.ts rename apps/renderer/src/lib/{ => __tests__}/path-parser.test.ts (99%) create mode 100644 patches/@mozilla__readability.patch delete mode 100644 patches/@mozilla__readability@0.5.0.patch diff --git a/apps/main/src/lib/readability.ts b/apps/main/src/lib/readability.ts index 8e0ad855b..e0e9ebf10 100644 --- a/apps/main/src/lib/readability.ts +++ b/apps/main/src/lib/readability.ts @@ -3,6 +3,8 @@ import { name, version } from "@pkg" import { parseHTML } from "linkedom" import { fetch } from "ofetch" +import { isDev } from "~/env" + const userAgents = `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 ${name}/${version}` export async function readability(url: string) { @@ -41,7 +43,7 @@ export async function readability(url: string) { }) const reader = new Readability(document, { - // debug: isDev, + debug: isDev, }) return reader.parse() } diff --git a/apps/renderer/src/lib/__tests__/parse-html.test.ts b/apps/renderer/src/lib/__tests__/parse-html.test.ts new file mode 100644 index 000000000..4835d9798 --- /dev/null +++ b/apps/renderer/src/lib/__tests__/parse-html.test.ts @@ -0,0 +1,376 @@ +import { describe, expect, it } from "vitest" + +import { extractCodeFromHtml } from "../parse-html" + +describe("extractCodeFromHtml", () => { + it("should extract code from div elements", () => { + const htmlString = "
line 1
line 2
" + const result = extractCodeFromHtml(htmlString) + + expect(result).toBe("line 1\nline 2\n") + }) + + it("should extract code from span elements with line breaks", () => { + const htmlString = "line 1line 2" + const result = extractCodeFromHtml(htmlString) + + expect(result).toMatchInlineSnapshot(` + "line 1line 2 + " + `) + }) + + it("should extract code from span elements without line breaks", () => { + const htmlString = "line 1line 2" + const result = extractCodeFromHtml(htmlString) + + expect(result).toMatchInlineSnapshot(` + "line 1line 2 + " + `) + }) + + it("should return the entire text content if no specific structure is found", () => { + const htmlString = "plain text content" + const result = extractCodeFromHtml(htmlString) + + expect(result).toBe("plain text content") + }) + + it("pre > code", () => { + const htmlString = `
import i18next from 'i18next' import { initReactI18next } from 'react-i18next' import en from '@/locales/en.json' import zhCN from '@/locales/zh_CN.json' i18next.use(initReactI18next).init({ lng: 'zh', fallbackLng: 'en', resources: { en: { translation: en, }, zh: { translation: zhCN, }, }, })
` + const result = extractCodeFromHtml(htmlString) + + expect(result).toMatchInlineSnapshot( + `"import i18next from 'i18next' import { initReactI18next } from 'react-i18next' import en from '@/locales/en.json' import zhCN from '@/locales/zh_CN.json' i18next.use(initReactI18next).init({ lng: 'zh', fallbackLng: 'en', resources: { en: { translation: en, }, zh: { translation: zhCN, }, }, })"`, + ) + }) + + it("pre > code 2", () => { + const htmlString = `
import type { Namespace } from '@/types'; export const namespace: Namespace = { // ... }; 
` + const result = extractCodeFromHtml(htmlString) + + expect(result).toMatchInlineSnapshot( + `"import type { Namespace } from '@/types'; export const namespace: Namespace = { // ... }; "`, + ) + }) + + it("pre", () => { + const htmlString = `
@keyframes seed {
+    0%{--seed:0}1%{--seed:1}2%{--seed:2}3%{--seed:3}4%{--seed:4}5%{--seed:5}6%{--seed:6}7%{--seed:7}8%{--seed:8}9%{--seed:9}10%{--seed:10}11%{--seed:11}...95%{--seed:95}96%{--seed:96}97%{--seed:97}98%{--seed:98}99%{--seed:99}100%{--seed:100}
+}
` + const result = extractCodeFromHtml(htmlString) + + expect(result).toMatchInlineSnapshot(`"@keyframes seed { + 0%{--seed:0}1%{--seed:1}2%{--seed:2}3%{--seed:3}4%{--seed:4}5%{--seed:5}6%{--seed:6}7%{--seed:7}8%{--seed:8}9%{--seed:9}10%{--seed:10}11%{--seed:11}...95%{--seed:95}96%{--seed:96}97%{--seed:97}98%{--seed:98}99%{--seed:99}100%{--seed:100} +}"`) + }) + + it("pre 2", () => { + const htmlString = `
@property --seed {
+  syntax: "<integer>";
+  inherits: true;
+  initial-value: 0;
+}
+
+@keyframes seed {
+  from { --seed: 0; }
+  to { --seed: 100; }
+}
` + const result = extractCodeFromHtml(htmlString) + + expect(result).toMatchInlineSnapshot(` + "@property --seed { + syntax: ""; + inherits: true; + initial-value: 0; + } + + @keyframes seed { + from { --seed: 0; } + to { --seed: 100; } + }" + `) + }) + + it("pre > lang-*", () => { + const htmlString = `
module.exports = {
+  output: "standalone",
+}
` + const result = extractCodeFromHtml(htmlString) + + expect(result).toMatchInlineSnapshot(` + "module.exports = { + output: "standalone", + }" + `) + }) + + it("shiki render", () => { + const htmlString = `
import i18next from 'i18next'
+import { initReactI18next } from 'react-i18next'
+
+import en from '@/locales/en.json'
+import zhCN from '@/locales/zh_CN.json'
+
+i18next.use(initReactI18next).init({
+  lng: 'zh',
+  fallbackLng: 'en',
+  resources: {
+    en: {
+      translation: en,
+    },
+    zh: {
+      translation: zhCN,
+    },
+  },
+})
` + const result = extractCodeFromHtml(htmlString) + + expect(result).toMatchInlineSnapshot(` + "import i18next from 'i18next' + import { initReactI18next } from 'react-i18next' + + import en from '@/locales/en.json' + import zhCN from '@/locales/zh_CN.json' + + i18next.use(initReactI18next).init({ + lng: 'zh', + fallbackLng: 'en', + resources: { + en: { + translation: en, + }, + zh: { + translation: zhCN, + }, + }, + }) + " + `) + }) + + it("pre > code, without line wrapper", () => { + const htmlString = `
FROM node:20.15-alpine AS runner
+
+ENV NODE_ENV production
+
+# Create app directory
+WORKDIR /app
+
+RUN addgroup --system --gid 1001 nodejs
+RUN adduser --system --uid 1001 nextjs
+
+COPY public /app/public
+
+# Set the correct permission for prerender cache
+RUN mkdir .next
+RUN chown nextjs:nodejs .next
+
+# Automatically leverage output traces to reduce image size
+# https://nextjs.org/docs/advanced-features/output-file-tracing
+COPY --chown=nextjs:nodejs .next/standalone ./
+COPY --chown=nextjs:nodejs .next/static .next/static
+
+USER nextjs
+
+EXPOSE 3000
+ENV PORT 3000
+
+CMD ["ls", "-l"]
+
+# server.js is created by next build from the standalone output
+# https://nextjs.org/docs/pages/api-reference/next-config-js/output
+CMD HOSTNAME="0.0.0.0" node server.js
` + const result = extractCodeFromHtml(htmlString) + + expect(result).toMatchInlineSnapshot(` + "FROM node:20.15-alpine AS runner + + ENV NODE_ENV production + + # Create app directory + WORKDIR /app + + RUN addgroup --system --gid 1001 nodejs + RUN adduser --system --uid 1001 nextjs + + COPY public /app/public + + # Set the correct permission for prerender cache + RUN mkdir .next + RUN chown nextjs:nodejs .next + + # Automatically leverage output traces to reduce image size + # https://nextjs.org/docs/advanced-features/output-file-tracing + COPY --chown=nextjs:nodejs .next/standalone ./ + COPY --chown=nextjs:nodejs .next/static .next/static + + USER nextjs + + EXPOSE 3000 + ENV PORT 3000 + + CMD ["ls", "-l"] + + # server.js is created by next build from the standalone output + # https://nextjs.org/docs/pages/api-reference/next-config-js/output + CMD HOSTNAME="0.0.0.0" node server.js" + `) + }) + + it("hijs", () => { + const htmlString = `
@keyframes seed {
+    0%{--seed:0}1%{--seed:1}2%{--seed:2}3%{--seed:3}4%{--seed:4}5%{--seed:5}6%{--seed:6}7%{--seed:7}8%{--seed:8}9%{--seed:9}10%{--seed:10}11%{--seed:11}...95%{--seed:95}96%{--seed:96}97%{--seed:97}98%{--seed:98}99%{--seed:99}100%{--seed:100}
+}
` + const result = extractCodeFromHtml(htmlString) + + expect(result).toMatchInlineSnapshot(` + "@keyframes seed { + 0%{--seed:0}1%{--seed:1}2%{--seed:2}3%{--seed:3}4%{--seed:4}5%{--seed:5}6%{--seed:6}7%{--seed:7}8%{--seed:8}9%{--seed:9}10%{--seed:10}11%{--seed:11}...95%{--seed:95}96%{--seed:96}97%{--seed:97}98%{--seed:98}99%{--seed:99}100%{--seed:100} + }" + `) + }) + + it("hijs 2", () => { + const htmlString = `
function randInterval(): number {
+  return Math.random();
+}
+
+function boxMuller(mu: number, sigma: number): [number, number] {
+  const u = randInterval();
+  const v = randInterval();
+  const x = Math.cos(2 * Math.PI * u) * Math.sqrt(-2 * Math.log(v));
+  const y = Math.sin(2 * Math.PI * u) * Math.sqrt(-2 * Math.log(v));
+  return [x * sigma + mu, y * sigma + mu];
+}
+
+// Usage example
+const [value1, value2] = boxMuller(0, 1);
+console.log(value1, value2);
+// Outputs two normally distributed random numbers
+
` + const result = extractCodeFromHtml(htmlString) + + expect(result).toMatchInlineSnapshot(` + "function randInterval(): number { + return Math.random(); + } + + function boxMuller(mu: number, sigma: number): [number, number] { + const u = randInterval(); + const v = randInterval(); + const x = Math.cos(2 * Math.PI * u) * Math.sqrt(-2 * Math.log(v)); + const y = Math.sin(2 * Math.PI * u) * Math.sqrt(-2 * Math.log(v)); + return [x * sigma + mu, y * sigma + mu]; + } + + // Usage example + const [value1, value2] = boxMuller(0, 1); + console.log(value1, value2); + // Outputs two normally distributed random numbers + + " + `) + }) + + it("hijs without wrapper", () => { + const htmlString = `
import * as fs from "fs";
+import * as plotly from "plotly.js-dist";
+
+// Generate random numbers following a normal distribution using Box-Muller
+function randInterval(): number {
+  return Math.random();
+}
+
+function boxMuller(mu: number, sigma: number): [number, number] {
+  const u = randInterval();
+  const v = randInterval();
+  const x = Math.cos(2 * Math.PI * u) * Math.sqrt(-2 * Math.log(v));
+  const y = Math.sin(2 * Math.PI * u) * Math.sqrt(-2 * Math.log(v));
+  return [x * sigma + mu, y * sigma + mu];
+}
+
+// Generate n normally distributed random numbers
+function generateNormalDistribution(
+  mu: number,
+  sigma: number,
+  n: number
+): number[] {
+  const values: number[] = [];
+  for (let i = 0; i < n / 2; i++) {
+    const [value1, value2] = boxMuller(mu, sigma);
+    values.push(value1, value2);
+  }
+  return values;
+}
+
+// Generate the data
+const mu = 0;
+const sigma = 1;
+const sampleSize = 10000; // Sample size
+const values = generateNormalDistribution(mu, sigma, sampleSize);
+
+// Calculate the mean and variance of the generated random numbers
+const mean = values.reduce((acc, val) => acc + val, 0) / values.length;
+const variance =
+  values.reduce((acc, val) => acc + (val - mean) ** 2, 0) / values.length;
+  
+` + const result = extractCodeFromHtml(htmlString) + + expect(result).toMatchInlineSnapshot(` + "import * as fs from "fs"; + import * as plotly from "plotly.js-dist"; + + // Generate random numbers following a normal distribution using Box-Muller + function randInterval(): number { + return Math.random(); + } + + function boxMuller(mu: number, sigma: number): [number, number] { + const u = randInterval(); + const v = randInterval(); + const x = Math.cos(2 * Math.PI * u) * Math.sqrt(-2 * Math.log(v)); + const y = Math.sin(2 * Math.PI * u) * Math.sqrt(-2 * Math.log(v)); + return [x * sigma + mu, y * sigma + mu]; + } + + // Generate n normally distributed random numbers + function generateNormalDistribution( + mu: number, + sigma: number, + n: number + ): number[] { + const values: number[] = []; + for (let i = 0; i < n / 2; i++) { + const [value1, value2] = boxMuller(mu, sigma); + values.push(value1, value2); + } + return values; + } + + // Generate the data + const mu = 0; + const sigma = 1; + const sampleSize = 10000; // Sample size + const values = generateNormalDistribution(mu, sigma, sampleSize); + + // Calculate the mean and variance of the generated random numbers + const mean = values.reduce((acc, val) => acc + val, 0) / values.length; + const variance = + values.reduce((acc, val) => acc + (val - mean) ** 2, 0) / values.length; + + " + `) + }) + + it("no ", () => { + const htmlString = `if theme.twikoo.enable == true
#tcomment
script(src='https://registry.npmmirror.com/twikoo/1.6.39/files/dist/twikoo.all.min.js')
script.
twikoo.init({
envId: '#{theme.twikoo.envId}',
el: '#tcomment',
region: '#{theme.twikoo.region}',
path: '#{theme.twikoo.path}',
onCommentLoaded: function () {
const commentCountElement = document.querySelector('.tk-comments-count');
const targetElement = document.querySelector('.waline-comment-count');
if (commentCountElement) {
const countSpan = commentCountElement.querySelector('span:first-child');
const commentCount = parseInt(countSpan.textContent);
targetElement.textContent = commentCount;
} else {
console.log('未找到评论数量元素');
}
}
})

` + const result = extractCodeFromHtml(htmlString) + + expect(result).toMatchInlineSnapshot( + `"if theme.twikoo.enable == true #tcomment script(src='https://registry.npmmirror.com/twikoo/1.6.39/files/dist/twikoo.all.min.js') script. twikoo.init({ envId: '#{theme.twikoo.envId}', el: '#tcomment', region: '#{theme.twikoo.region}', path: '#{theme.twikoo.path}', onCommentLoaded: function () { const commentCountElement = document.querySelector('.tk-comments-count'); const targetElement = document.querySelector('.waline-comment-count'); if (commentCountElement) { const countSpan = commentCountElement.querySelector('span:first-child'); const commentCount = parseInt(countSpan.textContent); targetElement.textContent = commentCount; } else { console.log('未找到评论数量元素'); } } })"`, + ) + }) +}) diff --git a/apps/renderer/src/lib/path-parser.test.ts b/apps/renderer/src/lib/__tests__/path-parser.test.ts similarity index 99% rename from apps/renderer/src/lib/path-parser.test.ts rename to apps/renderer/src/lib/__tests__/path-parser.test.ts index 6c5ae19c5..80c4980c6 100644 --- a/apps/renderer/src/lib/path-parser.test.ts +++ b/apps/renderer/src/lib/__tests__/path-parser.test.ts @@ -8,7 +8,7 @@ import { parseRegexpPathParams, regexpPathToPath, transformUriPath, -} from "./path-parser" +} from "../path-parser" describe("test `transformUriPath()`", () => { test("normal path", () => { diff --git a/apps/renderer/src/lib/parse-html.ts b/apps/renderer/src/lib/parse-html.ts index d76fffa49..d63d0f531 100644 --- a/apps/renderer/src/lib/parse-html.ts +++ b/apps/renderer/src/lib/parse-html.ts @@ -177,11 +177,11 @@ export const parseHtml = ( codeString = props.children.toString() } else { const propsChildren = props.children - const children = Array.isArray(propsChildren) + let children = Array.isArray(propsChildren) ? propsChildren.find((i) => i.type === "code") : propsChildren - if (!children) return createElement("pre", props, props.children) + if (!children) children = createElement("pre", props, props.children) if ( "type" in children && @@ -190,8 +190,8 @@ export const parseHtml = ( ) { language = children.props.className.replace("language-", "") } - const code = "props" in children && children.props.children - if (!code) return createElement("pre", props, props.children) + const code = ("props" in children && children.props.children) || children + if (!code) return null try { codeString = extractCodeFromHtml(renderToString(code)) @@ -241,10 +241,15 @@ const Img: Components["img"] = ({ node, ...props }) => { ) } -function extractCodeFromHtml(htmlString: string) { +export function extractCodeFromHtml(htmlString: string) { const tempDiv = document.createElement("div") tempDiv.innerHTML = htmlString + const hasPre = tempDiv.querySelector("pre") + if (!hasPre) { + tempDiv.innerHTML = `
${htmlString}
` + } + // 1. line break via
const divElements = tempDiv.querySelectorAll("div") @@ -272,6 +277,14 @@ function extractCodeFromHtml(htmlString: string) { if (spanAsLineBreak) break } } + + if (!spanAsLineBreak) { + const usingBr = tempDiv.querySelector("br") + if (usingBr) { + spanAsLineBreak = true + } + } + if (spanElements.length > 0) { for (const node of tempDiv.children) { if (spanAsLineBreak) { diff --git a/apps/renderer/vitest.config.ts b/apps/renderer/vitest.config.ts index 27994e24a..1c9b76821 100644 --- a/apps/renderer/vitest.config.ts +++ b/apps/renderer/vitest.config.ts @@ -5,6 +5,8 @@ import { fileURLToPath } from "node:url" import tsconfigPath from "vite-tsconfig-paths" import { defineProject } from "vitest/config" +import { twMacro } from "../../plugins/vite/tw-macro" + const pkg = JSON.parse(readFileSync("package.json", "utf8")) const __dirname = fileURLToPath(new URL(".", import.meta.url)) @@ -13,7 +15,7 @@ export default defineProject({ test: { globals: true, setupFiles: [resolve(__dirname, "./setup-file.ts")], - environment: "node", + environment: "happy-dom", includeSource: [resolve(__dirname, ".")], }, @@ -31,5 +33,7 @@ export default defineProject({ tsconfigPath({ projects: ["./tsconfig.json"], }), + + twMacro(), ], }) diff --git a/package.json b/package.json index 41d218a66..5f1baf06e 100644 --- a/package.json +++ b/package.json @@ -79,6 +79,7 @@ "eslint": "^9.12.0", "eslint-config-hyoban": "^3.1.10", "fake-indexeddb": "6.0.0", + "happy-dom": "15.7.4", "hono": "4.6.3", "lint-staged": "15.2.10", "nbump": "2.0.4", @@ -104,10 +105,10 @@ "patchedDependencies": { "sonner@1.5.0": "patches/sonner@1.5.0.patch", "immer@10.1.1": "patches/immer@10.1.1.patch", - "@mozilla/readability@0.5.0": "patches/@mozilla__readability@0.5.0.patch", "re-resizable": "patches/re-resizable@6.9.17.patch", "hono": "patches/hono.patch", - "electron-context-menu": "patches/electron-context-menu.patch" + "electron-context-menu": "patches/electron-context-menu.patch", + "@mozilla/readability": "patches/@mozilla__readability.patch" }, "overrides": { "is-core-module": "npm:@nolyfill/is-core-module@^1", diff --git a/patches/@mozilla__readability.patch b/patches/@mozilla__readability.patch new file mode 100644 index 000000000..d40b5b321 --- /dev/null +++ b/patches/@mozilla__readability.patch @@ -0,0 +1,13 @@ +diff --git a/Readability-readerable.js b/Readability-readerable.js +index 892169fb94999987e895846b7605f9c4cf32802c..6c75e61f3c5e0b6143860fa1aa8c652548a78760 100644 +--- a/Readability-readerable.js ++++ b/Readability-readerable.js +@@ -29,7 +29,7 @@ var REGEXPS = { + function isNodeVisible(node) { + // Have to null-check node.style and node.className.indexOf to deal with SVG and MathML nodes. + return (!node.style || node.style.display != "none") +- && !node.hasAttribute("hidden") ++ && !(node.hasAttribute("hidden") && !node.id.startsWith("S:")) + //check for "fallback-image" so that wikimedia math images are displayed + && (!node.hasAttribute("aria-hidden") || node.getAttribute("aria-hidden") != "true" || (node.className && node.className.indexOf && node.className.indexOf("fallback-image") !== -1)); + } diff --git a/patches/@mozilla__readability@0.5.0.patch b/patches/@mozilla__readability@0.5.0.patch deleted file mode 100644 index 7ea789420..000000000 --- a/patches/@mozilla__readability@0.5.0.patch +++ /dev/null @@ -1,2109 +0,0 @@ -diff --git a/Readability.js b/Readability.js -index b745aa01d8ea23e55c5c309c29262f6fa0a74a01..21756f48574d33a7bd35ce7d47be106f922a9908 100644 ---- a/Readability.js -+++ b/Readability.js -@@ -30,7 +30,9 @@ function Readability(doc, options) { - doc = options; - options = arguments[2]; - } else if (!doc || !doc.documentElement) { -- throw new Error("First argument to Readability constructor should be a document object."); -+ throw new Error( -+ "First argument to Readability constructor should be a document object." -+ ); - } - options = options || {}; - -@@ -44,37 +46,43 @@ function Readability(doc, options) { - - // Configurable options - this._debug = !!options.debug; -- this._maxElemsToParse = options.maxElemsToParse || this.DEFAULT_MAX_ELEMS_TO_PARSE; -- this._nbTopCandidates = options.nbTopCandidates || this.DEFAULT_N_TOP_CANDIDATES; -+ this._maxElemsToParse = -+ options.maxElemsToParse || this.DEFAULT_MAX_ELEMS_TO_PARSE; -+ this._nbTopCandidates = -+ options.nbTopCandidates || this.DEFAULT_N_TOP_CANDIDATES; - this._charThreshold = options.charThreshold || this.DEFAULT_CHAR_THRESHOLD; -- this._classesToPreserve = this.CLASSES_TO_PRESERVE.concat(options.classesToPreserve || []); -+ this._classesToPreserve = this.CLASSES_TO_PRESERVE.concat( -+ options.classesToPreserve || [] -+ ); - this._keepClasses = !!options.keepClasses; -- this._serializer = options.serializer || function(el) { -- return el.innerHTML; -- }; -+ this._serializer = -+ options.serializer || -+ function (el) { -+ return el.innerHTML; -+ }; - this._disableJSONLD = !!options.disableJSONLD; - this._allowedVideoRegex = options.allowedVideoRegex || this.REGEXPS.videos; - - // Start with all flags set -- this._flags = this.FLAG_STRIP_UNLIKELYS | -- this.FLAG_WEIGHT_CLASSES | -- this.FLAG_CLEAN_CONDITIONALLY; -- -+ this._flags = -+ this.FLAG_STRIP_UNLIKELYS | -+ this.FLAG_WEIGHT_CLASSES | -+ this.FLAG_CLEAN_CONDITIONALLY; - - // Control whether log messages are sent to the console - if (this._debug) { -- let logNode = function(node) { -+ let logNode = function (node) { - if (node.nodeType == node.TEXT_NODE) { - return `${node.nodeName} ("${node.textContent}")`; - } -- let attrPairs = Array.from(node.attributes || [], function(attr) { -+ let attrPairs = Array.from(node.attributes || [], function (attr) { - return `${attr.name}="${attr.value}"`; - }).join(" "); - return `<${node.localName} ${attrPairs}>`; - }; - this.log = function () { - if (typeof console !== "undefined") { -- let args = Array.from(arguments, arg => { -+ let args = Array.from(arguments, (arg) => { - if (arg && arg.nodeType == this.ELEMENT_NODE) { - return logNode(arg); - } -@@ -84,9 +92,11 @@ function Readability(doc, options) { - console.log.apply(console, args); - } else if (typeof dump !== "undefined") { - /* global dump */ -- var msg = Array.prototype.map.call(arguments, function(x) { -- return (x && x.nodeName) ? logNode(x) : x; -- }).join(" "); -+ var msg = Array.prototype.map -+ .call(arguments, function (x) { -+ return x && x.nodeName ? logNode(x) : x; -+ }) -+ .join(" "); - dump("Reader: (Readability) " + msg + "\n"); - } - }; -@@ -112,7 +122,9 @@ Readability.prototype = { - DEFAULT_N_TOP_CANDIDATES: 5, - - // Element tags to score by default. -- DEFAULT_TAGS_TO_SCORE: "section,h2,h3,h4,h5,h6,p,td,pre".toUpperCase().split(","), -+ DEFAULT_TAGS_TO_SCORE: "section,h2,h3,h4,h5,h6,p,td,pre" -+ .toUpperCase() -+ .split(","), - - // The default number of chars an article must have in order to return a result - DEFAULT_CHAR_THRESHOLD: 500, -@@ -122,16 +134,21 @@ Readability.prototype = { - REGEXPS: { - // NOTE: These two regular expressions are duplicated in - // Readability-readerable.js. Please keep both copies in sync. -- unlikelyCandidates: /-ad-|ai2html|banner|breadcrumbs|combx|comment|community|cover-wrap|disqus|extra|footer|gdpr|header|legends|menu|related|remark|replies|rss|shoutbox|sidebar|skyscraper|social|sponsor|supplemental|ad-break|agegate|pagination|pager|popup|yom-remote/i, -+ unlikelyCandidates: -+ /-ad-|ai2html|banner|breadcrumbs|combx|comment|community|cover-wrap|disqus|extra|footer|gdpr|header|legends|menu|related|remark|replies|rss|shoutbox|sidebar|skyscraper|social|sponsor|supplemental|ad-break|agegate|pagination|pager|popup|yom-remote/i, - okMaybeItsACandidate: /and|article|body|column|content|main|shadow/i, - -- positive: /article|body|content|entry|hentry|h-entry|main|page|pagination|post|text|blog|story/i, -- negative: /-ad-|hidden|^hid$| hid$| hid |^hid |banner|combx|comment|com-|contact|foot|footer|footnote|gdpr|masthead|media|meta|outbrain|promo|related|scroll|share|shoutbox|sidebar|skyscraper|sponsor|shopping|tags|tool|widget/i, -- extraneous: /print|archive|comment|discuss|e[\-]?mail|share|reply|all|login|sign|single|utility/i, -+ positive: -+ /article|body|content|entry|hentry|h-entry|main|page|pagination|post|text|blog|story/i, -+ negative: -+ /-ad-|hidden|^hid$| hid$| hid |^hid |banner|combx|comment|com-|contact|foot|footer|footnote|gdpr|masthead|media|meta|outbrain|promo|related|scroll|share|shoutbox|sidebar|skyscraper|sponsor|shopping|tags|tool|widget/i, -+ extraneous: -+ /print|archive|comment|discuss|e[\-]?mail|share|reply|all|login|sign|single|utility/i, - byline: /byline|author|dateline|writtenby|p-author/i, - replaceFonts: /<(\/?)font[^>]*>/gi, - normalize: /\s{2,}/g, -- videos: /\/\/(www\.)?((dailymotion|youtube|youtube-nocookie|player\.vimeo|v\.qq)\.com|(archive|upload\.wikimedia)\.org|player\.twitch\.tv)/i, -+ videos: -+ /\/\/(www\.)?((dailymotion|youtube|youtube-nocookie|player\.vimeo|v\.qq)\.com|(archive|upload\.wikimedia)\.org|player\.twitch\.tv)/i, - shareElements: /(\b|_)(share|sharedaddy)(\b|_)/i, - nextLink: /(next|weiter|continue|>([^\|]|$)|»([^\|]|$))/i, - prevLink: /(prev|earl|old|new|<|«)/i, -@@ -145,40 +162,106 @@ Readability.prototype = { - // see: https://en.wikipedia.org/wiki/Comma#Comma_variants - commas: /\u002C|\u060C|\uFE50|\uFE10|\uFE11|\u2E41|\u2E34|\u2E32|\uFF0C/g, - // See: https://schema.org/Article -- jsonLdArticleTypes: /^Article|AdvertiserContentArticle|NewsArticle|AnalysisNewsArticle|AskPublicNewsArticle|BackgroundNewsArticle|OpinionNewsArticle|ReportageNewsArticle|ReviewNewsArticle|Report|SatiricalArticle|ScholarlyArticle|MedicalScholarlyArticle|SocialMediaPosting|BlogPosting|LiveBlogPosting|DiscussionForumPosting|TechArticle|APIReference$/ -+ jsonLdArticleTypes: -+ /^Article|AdvertiserContentArticle|NewsArticle|AnalysisNewsArticle|AskPublicNewsArticle|BackgroundNewsArticle|OpinionNewsArticle|ReportageNewsArticle|ReviewNewsArticle|Report|SatiricalArticle|ScholarlyArticle|MedicalScholarlyArticle|SocialMediaPosting|BlogPosting|LiveBlogPosting|DiscussionForumPosting|TechArticle|APIReference$/, - }, - -- UNLIKELY_ROLES: [ "menu", "menubar", "complementary", "navigation", "alert", "alertdialog", "dialog" ], -+ UNLIKELY_ROLES: [ -+ "menu", -+ "menubar", -+ "complementary", -+ "navigation", -+ "alert", -+ "alertdialog", -+ "dialog", -+ ], - -- DIV_TO_P_ELEMS: new Set([ "BLOCKQUOTE", "DL", "DIV", "IMG", "OL", "P", "PRE", "TABLE", "UL" ]), -+ DIV_TO_P_ELEMS: new Set([ -+ "BLOCKQUOTE", -+ "DL", -+ "DIV", -+ "IMG", -+ "OL", -+ "P", -+ "PRE", -+ "TABLE", -+ "UL", -+ ]), - - ALTER_TO_DIV_EXCEPTIONS: ["DIV", "ARTICLE", "SECTION", "P"], - -- PRESENTATIONAL_ATTRIBUTES: [ "align", "background", "bgcolor", "border", "cellpadding", "cellspacing", "frame", "hspace", "rules", "style", "valign", "vspace" ], -+ PRESENTATIONAL_ATTRIBUTES: [ -+ "align", -+ "background", -+ "bgcolor", -+ "border", -+ "cellpadding", -+ "cellspacing", -+ "frame", -+ "hspace", -+ "rules", -+ "style", -+ "valign", -+ "vspace", -+ ], - -- DEPRECATED_SIZE_ATTRIBUTE_ELEMS: [ "TABLE", "TH", "TD", "HR", "PRE" ], -+ DEPRECATED_SIZE_ATTRIBUTE_ELEMS: ["TABLE", "TH", "TD", "HR", "PRE"], - - // The commented out elements qualify as phrasing content but tend to be - // removed by readability when put into paragraphs, so we ignore them here. - PHRASING_ELEMS: [ - // "CANVAS", "IFRAME", "SVG", "VIDEO", -- "ABBR", "AUDIO", "B", "BDO", "BR", "BUTTON", "CITE", "CODE", "DATA", -- "DATALIST", "DFN", "EM", "EMBED", "I", "IMG", "INPUT", "KBD", "LABEL", -- "MARK", "MATH", "METER", "NOSCRIPT", "OBJECT", "OUTPUT", "PROGRESS", "Q", -- "RUBY", "SAMP", "SCRIPT", "SELECT", "SMALL", "SPAN", "STRONG", "SUB", -- "SUP", "TEXTAREA", "TIME", "VAR", "WBR" -+ "ABBR", -+ "AUDIO", -+ "B", -+ "BDO", -+ "BR", -+ "BUTTON", -+ "CITE", -+ "CODE", -+ "DATA", -+ "DATALIST", -+ "DFN", -+ "EM", -+ "EMBED", -+ "I", -+ "IMG", -+ "INPUT", -+ "KBD", -+ "LABEL", -+ "MARK", -+ "MATH", -+ "METER", -+ "NOSCRIPT", -+ "OBJECT", -+ "OUTPUT", -+ "PROGRESS", -+ "Q", -+ "RUBY", -+ "SAMP", -+ "SCRIPT", -+ "SELECT", -+ "SMALL", -+ "SPAN", -+ "STRONG", -+ "SUB", -+ "SUP", -+ "TEXTAREA", -+ "TIME", -+ "VAR", -+ "WBR", - ], - - // These are the classes that readability sets itself. -- CLASSES_TO_PRESERVE: [ "page" ], -+ CLASSES_TO_PRESERVE: ["page"], - - // These are the list of HTML entities that need to be escaped. - HTML_ESCAPE_MAP: { -- "lt": "<", -- "gt": ">", -- "amp": "&", -- "quot": '"', -- "apos": "'", -+ lt: "<", -+ gt: ">", -+ amp: "&", -+ quot: '"', -+ apos: "'", - }, - - /** -@@ -186,8 +269,8 @@ Readability.prototype = { - * - * @param Element - * @return void -- **/ -- _postProcessContent: function(articleContent) { -+ **/ -+ _postProcessContent: function (articleContent) { - // Readability cannot open relative uris so we convert them to absolute uris. - this._fixRelativeUris(articleContent); - -@@ -209,7 +292,7 @@ Readability.prototype = { - * @param Function filterFn the function to use as a filter - * @return void - */ -- _removeNodes: function(nodeList, filterFn) { -+ _removeNodes: function (nodeList, filterFn) { - // Avoid ever operating on live node lists. - if (this._docJSDOMParser && nodeList._isLiveNodeList) { - throw new Error("Do not pass live node lists to _removeNodes"); -@@ -232,7 +315,7 @@ Readability.prototype = { - * @param String newTagName the new tag name to use - * @return void - */ -- _replaceNodeTags: function(nodeList, newTagName) { -+ _replaceNodeTags: function (nodeList, newTagName) { - // Avoid ever operating on live node lists. - if (this._docJSDOMParser && nodeList._isLiveNodeList) { - throw new Error("Do not pass live node lists to _replaceNodeTags"); -@@ -253,7 +336,7 @@ Readability.prototype = { - * @param Function fn The iterate function. - * @return void - */ -- _forEachNode: function(nodeList, fn) { -+ _forEachNode: function (nodeList, fn) { - Array.prototype.forEach.call(nodeList, fn, this); - }, - -@@ -268,7 +351,7 @@ Readability.prototype = { - * @param Function fn The test function. - * @return void - */ -- _findNode: function(nodeList, fn) { -+ _findNode: function (nodeList, fn) { - return Array.prototype.find.call(nodeList, fn, this); - }, - -@@ -283,7 +366,7 @@ Readability.prototype = { - * @param Function fn The iterate function. - * @return Boolean - */ -- _someNode: function(nodeList, fn) { -+ _someNode: function (nodeList, fn) { - return Array.prototype.some.call(nodeList, fn, this); - }, - -@@ -298,7 +381,7 @@ Readability.prototype = { - * @param Function fn The iterate function. - * @return Boolean - */ -- _everyNode: function(nodeList, fn) { -+ _everyNode: function (nodeList, fn) { - return Array.prototype.every.call(nodeList, fn, this); - }, - -@@ -308,23 +391,26 @@ Readability.prototype = { - * @return ...NodeList - * @return Array - */ -- _concatNodeLists: function() { -+ _concatNodeLists: function () { - var slice = Array.prototype.slice; - var args = slice.call(arguments); -- var nodeLists = args.map(function(list) { -+ var nodeLists = args.map(function (list) { - return slice.call(list); - }); - return Array.prototype.concat.apply([], nodeLists); - }, - -- _getAllNodesWithTag: function(node, tagNames) { -+ _getAllNodesWithTag: function (node, tagNames) { - if (node.querySelectorAll) { - return node.querySelectorAll(tagNames.join(",")); - } -- return [].concat.apply([], tagNames.map(function(tag) { -- var collection = node.getElementsByTagName(tag); -- return Array.isArray(collection) ? collection : Array.from(collection); -- })); -+ return [].concat.apply( -+ [], -+ tagNames.map(function (tag) { -+ var collection = node.getElementsByTagName(tag); -+ return Array.isArray(collection) ? collection : Array.from(collection); -+ }) -+ ); - }, - - /** -@@ -335,11 +421,11 @@ Readability.prototype = { - * @param Element - * @return void - */ -- _cleanClasses: function(node) { -+ _cleanClasses: function (node) { - var classesToPreserve = this._classesToPreserve; - var className = (node.getAttribute("class") || "") - .split(/\s+/) -- .filter(function(cls) { -+ .filter(function (cls) { - return classesToPreserve.indexOf(cls) != -1; - }) - .join(" "); -@@ -362,7 +448,7 @@ Readability.prototype = { - * @param Element - * @return void - */ -- _fixRelativeUris: function(articleContent) { -+ _fixRelativeUris: function (articleContent) { - var baseURI = this._doc.baseURI; - var documentURI = this._doc.documentURI; - function toAbsoluteURI(uri) { -@@ -381,14 +467,17 @@ Readability.prototype = { - } - - var links = this._getAllNodesWithTag(articleContent, ["a"]); -- this._forEachNode(links, function(link) { -+ this._forEachNode(links, function (link) { - var href = link.getAttribute("href"); - if (href) { - // Remove links with javascript: URIs, since - // they won't work after scripts have been removed from the page. - if (href.indexOf("javascript:") === 0) { - // if the link only contains simple text content, it can be converted to a text node -- if (link.childNodes.length === 1 && link.childNodes[0].nodeType === this.TEXT_NODE) { -+ if ( -+ link.childNodes.length === 1 && -+ link.childNodes[0].nodeType === this.TEXT_NODE -+ ) { - var text = this._doc.createTextNode(link.textContent); - link.parentNode.replaceChild(text, link); - } else { -@@ -406,10 +495,15 @@ Readability.prototype = { - }); - - var medias = this._getAllNodesWithTag(articleContent, [ -- "img", "picture", "figure", "video", "audio", "source" -+ "img", -+ "picture", -+ "figure", -+ "video", -+ "audio", -+ "source", - ]); - -- this._forEachNode(medias, function(media) { -+ this._forEachNode(medias, function (media) { - var src = media.getAttribute("src"); - var poster = media.getAttribute("poster"); - var srcset = media.getAttribute("srcset"); -@@ -423,27 +517,40 @@ Readability.prototype = { - } - - if (srcset) { -- var newSrcset = srcset.replace(this.REGEXPS.srcsetUrl, function(_, p1, p2, p3) { -- return toAbsoluteURI(p1) + (p2 || "") + p3; -- }); -+ var newSrcset = srcset.replace( -+ this.REGEXPS.srcsetUrl, -+ function (_, p1, p2, p3) { -+ return toAbsoluteURI(p1) + (p2 || "") + p3; -+ } -+ ); - - media.setAttribute("srcset", newSrcset); - } - }); - }, - -- _simplifyNestedElements: function(articleContent) { -+ _simplifyNestedElements: function (articleContent) { - var node = articleContent; - - while (node) { -- if (node.parentNode && ["DIV", "SECTION"].includes(node.tagName) && !(node.id && node.id.startsWith("readability"))) { -+ if ( -+ node.parentNode && -+ ["DIV", "SECTION"].includes(node.tagName) && -+ !(node.id && node.id.startsWith("readability")) -+ ) { - if (this._isElementWithoutContent(node)) { - node = this._removeAndGetNext(node); - continue; -- } else if (this._hasSingleTagInsideElement(node, "DIV") || this._hasSingleTagInsideElement(node, "SECTION")) { -+ } else if ( -+ this._hasSingleTagInsideElement(node, "DIV") || -+ this._hasSingleTagInsideElement(node, "SECTION") -+ ) { - var child = node.children[0]; - for (var i = 0; i < node.attributes.length; i++) { -- child.setAttribute(node.attributes[i].name, node.attributes[i].value); -+ child.setAttribute( -+ node.attributes[i].name, -+ node.attributes[i].value -+ ); - } - node.parentNode.replaceChild(child, node); - node = child; -@@ -460,7 +567,7 @@ Readability.prototype = { - * - * @return string - **/ -- _getArticleTitle: function() { -+ _getArticleTitle: function () { - var doc = this._doc; - var curTitle = ""; - var origTitle = ""; -@@ -470,8 +577,12 @@ Readability.prototype = { - - // If they had an element with id "title" in their HTML - if (typeof curTitle !== "string") -- curTitle = origTitle = this._getInnerText(doc.getElementsByTagName("title")[0]); -- } catch (e) {/* ignore exceptions setting the title. */} -+ curTitle = origTitle = this._getInnerText( -+ doc.getElementsByTagName("title")[0] -+ ); -+ } catch (e) { -+ /* ignore exceptions setting the title. */ -+ } - - var titleHadHierarchicalSeparators = false; - function wordCount(str) { -@@ -479,7 +590,7 @@ Readability.prototype = { - } - - // If there's a separator in the title, first remove the final part -- if ((/ [\|\-\\\/>»] /).test(curTitle)) { -+ if (/ [\|\-\\\/>»] /.test(curTitle)) { - titleHadHierarchicalSeparators = / [\\\/>»] /.test(curTitle); - curTitle = origTitle.replace(/(.*)[\|\-\\\/>»] .*/gi, "$1"); - -@@ -495,7 +606,7 @@ Readability.prototype = { - doc.getElementsByTagName("h2") - ); - var trimmedTitle = curTitle.trim(); -- var match = this._someNode(headings, function(heading) { -+ var match = this._someNode(headings, function (heading) { - return heading.textContent.trim() === trimmedTitle; - }); - -@@ -515,8 +626,7 @@ Readability.prototype = { - } else if (curTitle.length > 150 || curTitle.length < 15) { - var hOnes = doc.getElementsByTagName("h1"); - -- if (hOnes.length === 1) -- curTitle = this._getInnerText(hOnes[0]); -+ if (hOnes.length === 1) curTitle = this._getInnerText(hOnes[0]); - } - - curTitle = curTitle.trim().replace(this.REGEXPS.normalize, " "); -@@ -525,9 +635,12 @@ Readability.prototype = { - // title or we decreased the number of words by more than 1 word, use - // the original title. - var curTitleWordCount = wordCount(curTitle); -- if (curTitleWordCount <= 4 && -- (!titleHadHierarchicalSeparators || -- curTitleWordCount != wordCount(origTitle.replace(/[\|\-\\\/>»]+/g, "")) - 1)) { -+ if ( -+ curTitleWordCount <= 4 && -+ (!titleHadHierarchicalSeparators || -+ curTitleWordCount != -+ wordCount(origTitle.replace(/[\|\-\\\/>»]+/g, "")) - 1) -+ ) { - curTitle = origTitle; - } - -@@ -540,7 +653,7 @@ Readability.prototype = { - * - * @return void - **/ -- _prepDocument: function() { -+ _prepDocument: function () { - var doc = this._doc; - - // Remove all style tags in head -@@ -560,9 +673,11 @@ Readability.prototype = { - */ - _nextNode: function (node) { - var next = node; -- while (next -- && (next.nodeType != this.ELEMENT_NODE) -- && this.REGEXPS.whitespace.test(next.textContent)) { -+ while ( -+ next && -+ next.nodeType != this.ELEMENT_NODE && -+ this.REGEXPS.whitespace.test(next.textContent) -+ ) { - next = next.nextSibling; - } - return next; -@@ -576,7 +691,7 @@ Readability.prototype = { - *
foo
bar

abc

- */ - _replaceBrs: function (elem) { -- this._forEachNode(this._getAllNodesWithTag(elem, ["br"]), function(br) { -+ this._forEachNode(this._getAllNodesWithTag(elem, ["br"]), function (br) { - var next = br.nextSibling; - - // Whether 2 or more
elements have been found and replaced with a -@@ -586,7 +701,7 @@ Readability.prototype = { - // If we find a
chain, remove the
s until we hit another node - // or non-whitespace. This leaves behind the first
in the chain - // (which will be replaced with a

later). -- while ((next = this._nextNode(next)) && (next.tagName == "BR")) { -+ while ((next = this._nextNode(next)) && next.tagName == "BR") { - replaced = true; - var brSibling = next.nextSibling; - next.parentNode.removeChild(next); -@@ -605,12 +720,10 @@ Readability.prototype = { - // If we've hit another

, we're done adding children to this

. - if (next.tagName == "BR") { - var nextElem = this._nextNode(next.nextSibling); -- if (nextElem && nextElem.tagName == "BR") -- break; -+ if (nextElem && nextElem.tagName == "BR") break; - } - -- if (!this._isPhrasingContent(next)) -- break; -+ if (!this._isPhrasingContent(next)) break; - - // Otherwise, make this node a child of the new

. - var sibling = next.nextSibling; -@@ -622,8 +735,7 @@ Readability.prototype = { - p.removeChild(p.lastChild); - } - -- if (p.parentNode.tagName === "P") -- this._setNodeTag(p.parentNode, "DIV"); -+ if (p.parentNode.tagName === "P") this._setNodeTag(p.parentNode, "DIV"); - } - }); - }, -@@ -641,12 +753,14 @@ Readability.prototype = { - replacement.appendChild(node.firstChild); - } - node.parentNode.replaceChild(replacement, node); -- if (node.readability) -- replacement.readability = node.readability; -+ if (node.readability) replacement.readability = node.readability; - - for (var i = 0; i < node.attributes.length; i++) { - try { -- replacement.setAttribute(node.attributes[i].name, node.attributes[i].value); -+ replacement.setAttribute( -+ node.attributes[i].name, -+ node.attributes[i].value -+ ); - } catch (ex) { - /* it's possible for setAttribute() to throw if the attribute name - * isn't a valid XML Name. Such attributes can however be parsed from -@@ -666,7 +780,7 @@ Readability.prototype = { - * @param Element - * @return void - **/ -- _prepArticle: function(articleContent) { -+ _prepArticle: function (articleContent) { - this._cleanStyles(articleContent); - - // Check for data tables before we continue, to avoid removing items in -@@ -692,7 +806,10 @@ Readability.prototype = { - - this._forEachNode(articleContent.children, function (topCandidate) { - this._cleanMatchedNodes(topCandidate, function (node, matchString) { -- return this.REGEXPS.shareElements.test(matchString) && node.textContent.length < shareElementThreshold; -+ return ( -+ this.REGEXPS.shareElements.test(matchString) && -+ node.textContent.length < shareElementThreshold -+ ); - }); - }); - -@@ -710,38 +827,56 @@ Readability.prototype = { - this._cleanConditionally(articleContent, "div"); - - // replace H1 with H2 as H1 should be only title that is displayed separately -- this._replaceNodeTags(this._getAllNodesWithTag(articleContent, ["h1"]), "h2"); -+ this._replaceNodeTags( -+ this._getAllNodesWithTag(articleContent, ["h1"]), -+ "h2" -+ ); - - // Remove extra paragraphs -- this._removeNodes(this._getAllNodesWithTag(articleContent, ["p"]), function (paragraph) { -- var imgCount = paragraph.getElementsByTagName("img").length; -- var embedCount = paragraph.getElementsByTagName("embed").length; -- var objectCount = paragraph.getElementsByTagName("object").length; -- // At this point, nasty iframes have been removed, only remain embedded video ones. -- var iframeCount = paragraph.getElementsByTagName("iframe").length; -- var totalCount = imgCount + embedCount + objectCount + iframeCount; -- -- return totalCount === 0 && !this._getInnerText(paragraph, false); -- }); -+ this._removeNodes( -+ this._getAllNodesWithTag(articleContent, ["p"]), -+ function (paragraph) { -+ var imgCount = paragraph.getElementsByTagName("img").length; -+ var embedCount = paragraph.getElementsByTagName("embed").length; -+ var objectCount = paragraph.getElementsByTagName("object").length; -+ // At this point, nasty iframes have been removed, only remain embedded video ones. -+ var iframeCount = paragraph.getElementsByTagName("iframe").length; -+ var totalCount = imgCount + embedCount + objectCount + iframeCount; -+ -+ return totalCount === 0 && !this._getInnerText(paragraph, false); -+ } -+ ); - -- this._forEachNode(this._getAllNodesWithTag(articleContent, ["br"]), function(br) { -- var next = this._nextNode(br.nextSibling); -- if (next && next.tagName == "P") -- br.parentNode.removeChild(br); -- }); -+ this._forEachNode( -+ this._getAllNodesWithTag(articleContent, ["br"]), -+ function (br) { -+ var next = this._nextNode(br.nextSibling); -+ if (next && next.tagName == "P") br.parentNode.removeChild(br); -+ } -+ ); - - // Remove single-cell tables -- this._forEachNode(this._getAllNodesWithTag(articleContent, ["table"]), function(table) { -- var tbody = this._hasSingleTagInsideElement(table, "TBODY") ? table.firstElementChild : table; -- if (this._hasSingleTagInsideElement(tbody, "TR")) { -- var row = tbody.firstElementChild; -- if (this._hasSingleTagInsideElement(row, "TD")) { -- var cell = row.firstElementChild; -- cell = this._setNodeTag(cell, this._everyNode(cell.childNodes, this._isPhrasingContent) ? "P" : "DIV"); -- table.parentNode.replaceChild(cell, table); -+ this._forEachNode( -+ this._getAllNodesWithTag(articleContent, ["table"]), -+ function (table) { -+ var tbody = this._hasSingleTagInsideElement(table, "TBODY") -+ ? table.firstElementChild -+ : table; -+ if (this._hasSingleTagInsideElement(tbody, "TR")) { -+ var row = tbody.firstElementChild; -+ if (this._hasSingleTagInsideElement(row, "TD")) { -+ var cell = row.firstElementChild; -+ cell = this._setNodeTag( -+ cell, -+ this._everyNode(cell.childNodes, this._isPhrasingContent) -+ ? "P" -+ : "DIV" -+ ); -+ table.parentNode.replaceChild(cell, table); -+ } - } - } -- }); -+ ); - }, - - /** -@@ -750,9 +885,9 @@ Readability.prototype = { - * - * @param Element - * @return void -- **/ -- _initializeNode: function(node) { -- node.readability = {"contentScore": 0}; -+ **/ -+ _initializeNode: function (node) { -+ node.readability = { contentScore: 0 }; - - switch (node.tagName) { - case "DIV": -@@ -790,7 +925,7 @@ Readability.prototype = { - node.readability.contentScore += this._getClassWeight(node); - }, - -- _removeAndGetNext: function(node) { -+ _removeAndGetNext: function (node) { - var nextNode = this._getNextNode(node, true); - node.parentNode.removeChild(node); - return nextNode; -@@ -803,7 +938,7 @@ Readability.prototype = { - * - * Calling this in a loop will traverse the DOM depth-first. - */ -- _getNextNode: function(node, ignoreSelfAndKids) { -+ _getNextNode: function (node, ignoreSelfAndKids) { - // First check for kids if those aren't being ignored - if (!ignoreSelfAndKids && node.firstElementChild) { - return node.firstElementChild; -@@ -825,18 +960,24 @@ Readability.prototype = { - // 1 = same text, 0 = completely different text - // works the way that it splits both texts into words and then finds words that are unique in second text - // the result is given by the lower length of unique parts -- _textSimilarity: function(textA, textB) { -- var tokensA = textA.toLowerCase().split(this.REGEXPS.tokenize).filter(Boolean); -- var tokensB = textB.toLowerCase().split(this.REGEXPS.tokenize).filter(Boolean); -+ _textSimilarity: function (textA, textB) { -+ var tokensA = textA -+ .toLowerCase() -+ .split(this.REGEXPS.tokenize) -+ .filter(Boolean); -+ var tokensB = textB -+ .toLowerCase() -+ .split(this.REGEXPS.tokenize) -+ .filter(Boolean); - if (!tokensA.length || !tokensB.length) { - return 0; - } -- var uniqTokensB = tokensB.filter(token => !tokensA.includes(token)); -+ var uniqTokensB = tokensB.filter((token) => !tokensA.includes(token)); - var distanceB = uniqTokensB.join(" ").length / tokensB.join(" ").length; - return 1 - distanceB; - }, - -- _checkByline: function(node, matchString) { -+ _checkByline: function (node, matchString) { - if (this._articleByline) { - return false; - } -@@ -846,7 +987,12 @@ Readability.prototype = { - var itemprop = node.getAttribute("itemprop"); - } - -- if ((rel === "author" || (itemprop && itemprop.indexOf("author") !== -1) || this.REGEXPS.byline.test(matchString)) && this._isValidByline(node.textContent)) { -+ if ( -+ (rel === "author" || -+ (itemprop && itemprop.indexOf("author") !== -1) || -+ this.REGEXPS.byline.test(matchString)) && -+ this._isValidByline(node.textContent) -+ ) { - this._articleByline = node.textContent.trim(); - return true; - } -@@ -854,13 +1000,13 @@ Readability.prototype = { - return false; - }, - -- _getNodeAncestors: function(node, maxDepth) { -+ _getNodeAncestors: function (node, maxDepth) { - maxDepth = maxDepth || 0; -- var i = 0, ancestors = []; -+ var i = 0, -+ ancestors = []; - while (node.parentNode) { - ancestors.push(node.parentNode); -- if (maxDepth && ++i === maxDepth) -- break; -+ if (maxDepth && ++i === maxDepth) break; - node = node.parentNode; - } - return ancestors; -@@ -872,7 +1018,7 @@ Readability.prototype = { - * - * @param page a document to run upon. Needs to be a full document, complete with body. - * @return Element -- **/ -+ **/ - _grabArticle: function (page) { - this.log("**** grabArticle ****"); - var doc = this._doc; -@@ -889,7 +1035,9 @@ Readability.prototype = { - - while (true) { - this.log("Starting grabArticle loop"); -- var stripUnlikelyCandidates = this._flagIsActive(this.FLAG_STRIP_UNLIKELYS); -+ var stripUnlikelyCandidates = this._flagIsActive( -+ this.FLAG_STRIP_UNLIKELYS -+ ); - - // First, node prepping. Trash nodes that look cruddy (like ones with the - // class name "comment", etc), and turn divs into P tags where they have been -@@ -900,7 +1048,6 @@ Readability.prototype = { - let shouldRemoveTitleHeader = true; - - while (node) { -- - if (node.tagName === "HTML") { - this._articleLang = node.getAttribute("lang"); - } -@@ -914,7 +1061,10 @@ Readability.prototype = { - } - - // User is not able to see elements applied with both "aria-modal = true" and "role = dialog" -- if (node.getAttribute("aria-modal") == "true" && node.getAttribute("role") == "dialog") { -+ if ( -+ node.getAttribute("aria-modal") == "true" && -+ node.getAttribute("role") == "dialog" -+ ) { - node = this._removeAndGetNext(node); - continue; - } -@@ -926,7 +1076,11 @@ Readability.prototype = { - } - - if (shouldRemoveTitleHeader && this._headerDuplicatesTitle(node)) { -- this.log("Removing header: ", node.textContent.trim(), this._articleTitle.trim()); -+ this.log( -+ "Removing header: ", -+ node.textContent.trim(), -+ this._articleTitle.trim() -+ ); - shouldRemoveTitleHeader = false; - node = this._removeAndGetNext(node); - continue; -@@ -934,29 +1088,44 @@ Readability.prototype = { - - // Remove unlikely candidates - if (stripUnlikelyCandidates) { -- if (this.REGEXPS.unlikelyCandidates.test(matchString) && -- !this.REGEXPS.okMaybeItsACandidate.test(matchString) && -- !this._hasAncestorTag(node, "table") && -- !this._hasAncestorTag(node, "code") && -- node.tagName !== "BODY" && -- node.tagName !== "A") { -+ if ( -+ this.REGEXPS.unlikelyCandidates.test(matchString) && -+ !this.REGEXPS.okMaybeItsACandidate.test(matchString) && -+ !this._hasAncestorTag(node, "table") && -+ !this._hasAncestorTag(node, "code") && -+ node.tagName !== "BODY" && -+ node.tagName !== "A" -+ ) { - this.log("Removing unlikely candidate - " + matchString); - node = this._removeAndGetNext(node); - continue; - } - - if (this.UNLIKELY_ROLES.includes(node.getAttribute("role"))) { -- this.log("Removing content with role " + node.getAttribute("role") + " - " + matchString); -+ this.log( -+ "Removing content with role " + -+ node.getAttribute("role") + -+ " - " + -+ matchString -+ ); - node = this._removeAndGetNext(node); - continue; - } - } - - // Remove DIV, SECTION, and HEADER nodes without any content(e.g. text, image, video, or iframe). -- if ((node.tagName === "DIV" || node.tagName === "SECTION" || node.tagName === "HEADER" || -- node.tagName === "H1" || node.tagName === "H2" || node.tagName === "H3" || -- node.tagName === "H4" || node.tagName === "H5" || node.tagName === "H6") && -- this._isElementWithoutContent(node)) { -+ if ( -+ (node.tagName === "DIV" || -+ node.tagName === "SECTION" || -+ node.tagName === "HEADER" || -+ node.tagName === "H1" || -+ node.tagName === "H2" || -+ node.tagName === "H3" || -+ node.tagName === "H4" || -+ node.tagName === "H5" || -+ node.tagName === "H6") && -+ this._isElementWithoutContent(node) -+ ) { - node = this._removeAndGetNext(node); - continue; - } -@@ -993,7 +1162,10 @@ Readability.prototype = { - // element. DIVs with only a P element inside and no text content can be - // safely converted into plain P elements to avoid confusing the scoring - // algorithm with DIVs with are, in practice, paragraphs. -- if (this._hasSingleTagInsideElement(node, "P") && this._getLinkDensity(node) < 0.25) { -+ if ( -+ this._hasSingleTagInsideElement(node, "P") && -+ this._getLinkDensity(node) < 0.25 -+ ) { - var newNode = node.children[0]; - node.parentNode.replaceChild(newNode, node); - node = newNode; -@@ -1011,21 +1183,22 @@ Readability.prototype = { - * Then add their score to their parent node. - * - * A score is determined by things like number of commas, class names, etc. Maybe eventually link density. -- **/ -+ **/ - var candidates = []; -- this._forEachNode(elementsToScore, function(elementToScore) { -- if (!elementToScore.parentNode || typeof(elementToScore.parentNode.tagName) === "undefined") -+ this._forEachNode(elementsToScore, function (elementToScore) { -+ if ( -+ !elementToScore.parentNode || -+ typeof elementToScore.parentNode.tagName === "undefined" -+ ) - return; - - // If this paragraph is less than 25 characters, don't even count it. - var innerText = this._getInnerText(elementToScore); -- if (innerText.length < 25) -- return; -+ if (innerText.length < 25) return; - - // Exclude nodes with no ancestor. - var ancestors = this._getNodeAncestors(elementToScore, 5); -- if (ancestors.length === 0) -- return; -+ if (ancestors.length === 0) return; - - var contentScore = 0; - -@@ -1039,11 +1212,15 @@ Readability.prototype = { - contentScore += Math.min(Math.floor(innerText.length / 100), 3); - - // Initialize and score ancestors. -- this._forEachNode(ancestors, function(ancestor, level) { -- if (!ancestor.tagName || !ancestor.parentNode || typeof(ancestor.parentNode.tagName) === "undefined") -+ this._forEachNode(ancestors, function (ancestor, level) { -+ if ( -+ !ancestor.tagName || -+ !ancestor.parentNode || -+ typeof ancestor.parentNode.tagName === "undefined" -+ ) - return; - -- if (typeof(ancestor.readability) === "undefined") { -+ if (typeof ancestor.readability === "undefined") { - this._initializeNode(ancestor); - candidates.push(ancestor); - } -@@ -1052,12 +1229,9 @@ Readability.prototype = { - // - parent: 1 (no division) - // - grandparent: 2 - // - great grandparent+: ancestor level * 3 -- if (level === 0) -- var scoreDivider = 1; -- else if (level === 1) -- scoreDivider = 2; -- else -- scoreDivider = level * 3; -+ if (level === 0) var scoreDivider = 1; -+ else if (level === 1) scoreDivider = 2; -+ else scoreDivider = level * 3; - ancestor.readability.contentScore += contentScore / scoreDivider; - }); - }); -@@ -1071,7 +1245,9 @@ Readability.prototype = { - // Scale the final candidates score based on link density. Good content - // should have a relatively small link density (5% or less) and be mostly - // unaffected by this operation. -- var candidateScore = candidate.readability.contentScore * (1 - this._getLinkDensity(candidate)); -+ var candidateScore = -+ candidate.readability.contentScore * -+ (1 - this._getLinkDensity(candidate)); - candidate.readability.contentScore = candidateScore; - - this.log("Candidate:", candidate, "with score " + candidateScore); -@@ -1079,7 +1255,10 @@ Readability.prototype = { - for (var t = 0; t < this._nbTopCandidates; t++) { - var aTopCandidate = topCandidates[t]; - -- if (!aTopCandidate || candidateScore > aTopCandidate.readability.contentScore) { -+ if ( -+ !aTopCandidate || -+ candidateScore > aTopCandidate.readability.contentScore -+ ) { - topCandidates.splice(t, 0, candidate); - if (topCandidates.length > this._nbTopCandidates) - topCandidates.pop(); -@@ -1113,8 +1292,14 @@ Readability.prototype = { - // and whose scores are quite closed with current `topCandidate` node. - var alternativeCandidateAncestors = []; - for (var i = 1; i < topCandidates.length; i++) { -- if (topCandidates[i].readability.contentScore / topCandidate.readability.contentScore >= 0.75) { -- alternativeCandidateAncestors.push(this._getNodeAncestors(topCandidates[i])); -+ if ( -+ topCandidates[i].readability.contentScore / -+ topCandidate.readability.contentScore >= -+ 0.75 -+ ) { -+ alternativeCandidateAncestors.push( -+ this._getNodeAncestors(topCandidates[i]) -+ ); - } - } - var MINIMUM_TOPCANDIDATES = 3; -@@ -1122,8 +1307,17 @@ Readability.prototype = { - parentOfTopCandidate = topCandidate.parentNode; - while (parentOfTopCandidate.tagName !== "BODY") { - var listsContainingThisAncestor = 0; -- for (var ancestorIndex = 0; ancestorIndex < alternativeCandidateAncestors.length && listsContainingThisAncestor < MINIMUM_TOPCANDIDATES; ancestorIndex++) { -- listsContainingThisAncestor += Number(alternativeCandidateAncestors[ancestorIndex].includes(parentOfTopCandidate)); -+ for ( -+ var ancestorIndex = 0; -+ ancestorIndex < alternativeCandidateAncestors.length && -+ listsContainingThisAncestor < MINIMUM_TOPCANDIDATES; -+ ancestorIndex++ -+ ) { -+ listsContainingThisAncestor += Number( -+ alternativeCandidateAncestors[ancestorIndex].includes( -+ parentOfTopCandidate -+ ) -+ ); - } - if (listsContainingThisAncestor >= MINIMUM_TOPCANDIDATES) { - topCandidate = parentOfTopCandidate; -@@ -1153,8 +1347,7 @@ Readability.prototype = { - continue; - } - var parentScore = parentOfTopCandidate.readability.contentScore; -- if (parentScore < scoreThreshold) -- break; -+ if (parentScore < scoreThreshold) break; - if (parentScore > lastScore) { - // Alright! We found a better parent to use. - topCandidate = parentOfTopCandidate; -@@ -1167,7 +1360,10 @@ Readability.prototype = { - // If the top candidate is the only child, use parent instead. This will help sibling - // joining logic when adjacent content is actually located in parent's sibling node. - parentOfTopCandidate = topCandidate.parentNode; -- while (parentOfTopCandidate.tagName != "BODY" && parentOfTopCandidate.children.length == 1) { -+ while ( -+ parentOfTopCandidate.tagName != "BODY" && -+ parentOfTopCandidate.children.length == 1 -+ ) { - topCandidate = parentOfTopCandidate; - parentOfTopCandidate = topCandidate.parentNode; - } -@@ -1180,10 +1376,12 @@ Readability.prototype = { - // that might also be related. Things like preambles, content split by ads - // that we removed, etc. - var articleContent = doc.createElement("DIV"); -- if (isPaging) -- articleContent.id = "readability-content"; -+ if (isPaging) articleContent.id = "readability-content"; - -- var siblingScoreThreshold = Math.max(10, topCandidate.readability.contentScore * 0.2); -+ var siblingScoreThreshold = Math.max( -+ 10, -+ topCandidate.readability.contentScore * 0.2 -+ ); - // Keep potential top candidate's parent node to try to get text direction of it later. - parentOfTopCandidate = topCandidate.parentNode; - var siblings = parentOfTopCandidate.children; -@@ -1192,8 +1390,17 @@ Readability.prototype = { - var sibling = siblings[s]; - var append = false; - -- this.log("Looking at sibling node:", sibling, sibling.readability ? ("with score " + sibling.readability.contentScore) : ""); -- this.log("Sibling has score", sibling.readability ? sibling.readability.contentScore : "Unknown"); -+ this.log( -+ "Looking at sibling node:", -+ sibling, -+ sibling.readability -+ ? "with score " + sibling.readability.contentScore -+ : "" -+ ); -+ this.log( -+ "Sibling has score", -+ sibling.readability ? sibling.readability.contentScore : "Unknown" -+ ); - - if (sibling === topCandidate) { - append = true; -@@ -1201,11 +1408,17 @@ Readability.prototype = { - var contentBonus = 0; - - // Give a bonus if sibling nodes and top candidates have the example same classname -- if (sibling.className === topCandidate.className && topCandidate.className !== "") -+ if ( -+ sibling.className === topCandidate.className && -+ topCandidate.className !== "" -+ ) - contentBonus += topCandidate.readability.contentScore * 0.2; - -- if (sibling.readability && -- ((sibling.readability.contentScore + contentBonus) >= siblingScoreThreshold)) { -+ if ( -+ sibling.readability && -+ sibling.readability.contentScore + contentBonus >= -+ siblingScoreThreshold -+ ) { - append = true; - } else if (sibling.nodeName === "P") { - var linkDensity = this._getLinkDensity(sibling); -@@ -1214,8 +1427,12 @@ Readability.prototype = { - - if (nodeLength > 80 && linkDensity < 0.25) { - append = true; -- } else if (nodeLength < 80 && nodeLength > 0 && linkDensity === 0 && -- nodeContent.search(/\.( |$)/) !== -1) { -+ } else if ( -+ nodeLength < 80 && -+ nodeLength > 0 && -+ linkDensity === 0 && -+ nodeContent.search(/\.( |$)/) !== -1 -+ ) { - append = true; - } - } -@@ -1286,15 +1503,27 @@ Readability.prototype = { - - if (this._flagIsActive(this.FLAG_STRIP_UNLIKELYS)) { - this._removeFlag(this.FLAG_STRIP_UNLIKELYS); -- this._attempts.push({articleContent: articleContent, textLength: textLength}); -+ this._attempts.push({ -+ articleContent: articleContent, -+ textLength: textLength, -+ }); - } else if (this._flagIsActive(this.FLAG_WEIGHT_CLASSES)) { - this._removeFlag(this.FLAG_WEIGHT_CLASSES); -- this._attempts.push({articleContent: articleContent, textLength: textLength}); -+ this._attempts.push({ -+ articleContent: articleContent, -+ textLength: textLength, -+ }); - } else if (this._flagIsActive(this.FLAG_CLEAN_CONDITIONALLY)) { - this._removeFlag(this.FLAG_CLEAN_CONDITIONALLY); -- this._attempts.push({articleContent: articleContent, textLength: textLength}); -+ this._attempts.push({ -+ articleContent: articleContent, -+ textLength: textLength, -+ }); - } else { -- this._attempts.push({articleContent: articleContent, textLength: textLength}); -+ this._attempts.push({ -+ articleContent: articleContent, -+ textLength: textLength, -+ }); - // No luck after removing flags, just return the longest text we found during the different loops - this._attempts.sort(function (a, b) { - return b.textLength - a.textLength; -@@ -1312,10 +1541,11 @@ Readability.prototype = { - - if (parseSuccessful) { - // Find out text direction from ancestors of final top candidate. -- var ancestors = [parentOfTopCandidate, topCandidate].concat(this._getNodeAncestors(parentOfTopCandidate)); -- this._someNode(ancestors, function(ancestor) { -- if (!ancestor.tagName) -- return false; -+ var ancestors = [parentOfTopCandidate, topCandidate].concat( -+ this._getNodeAncestors(parentOfTopCandidate) -+ ); -+ this._someNode(ancestors, function (ancestor) { -+ if (!ancestor.tagName) return false; - var articleDir = ancestor.getAttribute("dir"); - if (articleDir) { - this._articleDir = articleDir; -@@ -1336,10 +1566,10 @@ Readability.prototype = { - * @param possibleByline {string} - a string to check whether its a byline. - * @return Boolean - whether the input string is a byline. - */ -- _isValidByline: function(byline) { -+ _isValidByline: function (byline) { - if (typeof byline == "string" || byline instanceof String) { - byline = byline.trim(); -- return (byline.length > 0) && (byline.length < 100); -+ return byline.length > 0 && byline.length < 100; - } - return false; - }, -@@ -1350,18 +1580,23 @@ Readability.prototype = { - * @param str {string} - a string to unescape. - * @return string without HTML entity. - */ -- _unescapeHtmlEntities: function(str) { -+ _unescapeHtmlEntities: function (str) { - if (!str) { - return str; - } - - var htmlEscapeMap = this.HTML_ESCAPE_MAP; -- return str.replace(/&(quot|amp|apos|lt|gt);/g, function(_, tag) { -- return htmlEscapeMap[tag]; -- }).replace(/&#(?:x([0-9a-z]{1,4})|([0-9]{1,4}));/gi, function(_, hex, numStr) { -- var num = parseInt(hex || numStr, hex ? 16 : 10); -- return String.fromCharCode(num); -- }); -+ return str -+ .replace(/&(quot|amp|apos|lt|gt);/g, function (_, tag) { -+ return htmlEscapeMap[tag]; -+ }) -+ .replace( -+ /&#(?:x([0-9a-z]{1,4})|([0-9]{1,4}));/gi, -+ function (_, hex, numStr) { -+ var num = parseInt(hex || numStr, hex ? 16 : 10); -+ return String.fromCharCode(num); -+ } -+ ); - }, - - /** -@@ -1374,11 +1609,17 @@ Readability.prototype = { - - var metadata; - -- this._forEachNode(scripts, function(jsonLdElement) { -- if (!metadata && jsonLdElement.getAttribute("type") === "application/ld+json") { -+ this._forEachNode(scripts, function (jsonLdElement) { -+ if ( -+ !metadata && -+ jsonLdElement.getAttribute("type") === "application/ld+json" -+ ) { - try { - // Strip CDATA markers if present -- var content = jsonLdElement.textContent.replace(/^\s*\s*$/g, ""); -+ var content = jsonLdElement.textContent.replace( -+ /^\s*\s*$/g, -+ "" -+ ); - var parsed = JSON.parse(content); - if ( - !parsed["@context"] || -@@ -1388,10 +1629,8 @@ Readability.prototype = { - } - - if (!parsed["@type"] && Array.isArray(parsed["@graph"])) { -- parsed = parsed["@graph"].find(function(it) { -- return (it["@type"] || "").match( -- this.REGEXPS.jsonLdArticleTypes -- ); -+ parsed = parsed["@graph"].find(function (it) { -+ return (it["@type"] || "").match(this.REGEXPS.jsonLdArticleTypes); - }); - } - -@@ -1405,14 +1644,19 @@ Readability.prototype = { - - metadata = {}; - -- if (typeof parsed.name === "string" && typeof parsed.headline === "string" && parsed.name !== parsed.headline) { -+ if ( -+ typeof parsed.name === "string" && -+ typeof parsed.headline === "string" && -+ parsed.name !== parsed.headline -+ ) { - // we have both name and headline element in the JSON-LD. They should both be the same but some websites like aktualne.cz - // put their own name into "name" and the article title to "headline" which confuses Readability. So we try to check if either - // "name" or "headline" closely matches the html title, and if so, use that one. If not, then we use "name" by default. - - var title = this._getArticleTitle(); - var nameMatches = this._textSimilarity(parsed.name, title) > 0.75; -- var headlineMatches = this._textSimilarity(parsed.headline, title) > 0.75; -+ var headlineMatches = -+ this._textSimilarity(parsed.headline, title) > 0.75; - - if (headlineMatches && !nameMatches) { - metadata.title = parsed.headline; -@@ -1427,12 +1671,16 @@ Readability.prototype = { - if (parsed.author) { - if (typeof parsed.author.name === "string") { - metadata.byline = parsed.author.name.trim(); -- } else if (Array.isArray(parsed.author) && parsed.author[0] && typeof parsed.author[0].name === "string") { -+ } else if ( -+ Array.isArray(parsed.author) && -+ parsed.author[0] && -+ typeof parsed.author[0].name === "string" -+ ) { - metadata.byline = parsed.author -- .filter(function(author) { -+ .filter(function (author) { - return author && typeof author.name === "string"; - }) -- .map(function(author) { -+ .map(function (author) { - return author.name.trim(); - }) - .join(", "); -@@ -1441,10 +1689,7 @@ Readability.prototype = { - if (typeof parsed.description === "string") { - metadata.excerpt = parsed.description.trim(); - } -- if ( -- parsed.publisher && -- typeof parsed.publisher.name === "string" -- ) { -+ if (parsed.publisher && typeof parsed.publisher.name === "string") { - metadata.siteName = parsed.publisher.name.trim(); - } - if (typeof parsed.datePublished === "string") { -@@ -1467,19 +1712,21 @@ Readability.prototype = { - * - * @return Object with optional "excerpt" and "byline" properties - */ -- _getArticleMetadata: function(jsonld) { -+ _getArticleMetadata: function (jsonld) { - var metadata = {}; - var values = {}; - var metaElements = this._doc.getElementsByTagName("meta"); - - // property is a space-separated list of values -- var propertyPattern = /\s*(article|dc|dcterm|og|twitter)\s*:\s*(author|creator|description|published_time|title|site_name)\s*/gi; -+ var propertyPattern = -+ /\s*(article|dc|dcterm|og|twitter)\s*:\s*(author|creator|description|published_time|title|site_name)\s*/gi; - - // name is a single value -- var namePattern = /^\s*(?:(dc|dcterm|og|twitter|weibo:(article|webpage))\s*[\.:]\s*)?(author|creator|description|title|site_name)\s*$/i; -+ var namePattern = -+ /^\s*(?:(dc|dcterm|og|twitter|weibo:(article|webpage))\s*[\.:]\s*)?(author|creator|description|title|site_name)\s*$/i; - - // Find description tags. -- this._forEachNode(metaElements, function(element) { -+ this._forEachNode(metaElements, function (element) { - var elementName = element.getAttribute("name"); - var elementProperty = element.getAttribute("property"); - var content = element.getAttribute("content"); -@@ -1511,42 +1758,44 @@ Readability.prototype = { - }); - - // get title -- metadata.title = jsonld.title || -- values["dc:title"] || -- values["dcterm:title"] || -- values["og:title"] || -- values["weibo:article:title"] || -- values["weibo:webpage:title"] || -- values["title"] || -- values["twitter:title"]; -+ metadata.title = -+ jsonld.title || -+ values["dc:title"] || -+ values["dcterm:title"] || -+ values["og:title"] || -+ values["weibo:article:title"] || -+ values["weibo:webpage:title"] || -+ values["title"] || -+ values["twitter:title"]; - - if (!metadata.title) { - metadata.title = this._getArticleTitle(); - } - - // get author -- metadata.byline = jsonld.byline || -- values["dc:creator"] || -- values["dcterm:creator"] || -- values["author"]; -+ metadata.byline = -+ jsonld.byline || -+ values["dc:creator"] || -+ values["dcterm:creator"] || -+ values["author"]; - - // get description -- metadata.excerpt = jsonld.excerpt || -- values["dc:description"] || -- values["dcterm:description"] || -- values["og:description"] || -- values["weibo:article:description"] || -- values["weibo:webpage:description"] || -- values["description"] || -- values["twitter:description"]; -+ metadata.excerpt = -+ jsonld.excerpt || -+ values["dc:description"] || -+ values["dcterm:description"] || -+ values["og:description"] || -+ values["weibo:article:description"] || -+ values["weibo:webpage:description"] || -+ values["description"] || -+ values["twitter:description"]; - - // get site name -- metadata.siteName = jsonld.siteName || -- values["og:site_name"]; -+ metadata.siteName = jsonld.siteName || values["og:site_name"]; - - // get article published time -- metadata.publishedTime = jsonld.datePublished || -- values["article:published_time"] || null; -+ metadata.publishedTime = -+ jsonld.datePublished || values["article:published_time"] || null; - - // in many sites the meta value is escaped with HTML entities, - // so here we need to unescape it -@@ -1564,8 +1813,8 @@ Readability.prototype = { - * whether as a direct child or as its descendants. - * - * @param Element -- **/ -- _isSingleImage: function(node) { -+ **/ -+ _isSingleImage: function (node) { - if (node.tagName === "IMG") { - return true; - } -@@ -1584,12 +1833,12 @@ Readability.prototype = { - * some sites (e.g. Medium). - * - * @param Element -- **/ -- _unwrapNoscriptImages: function(doc) { -+ **/ -+ _unwrapNoscriptImages: function (doc) { - // Find img without source or attributes that might contains image, and remove it. - // This is done to prevent a placeholder img is replaced by img from noscript in next step. - var imgs = Array.from(doc.getElementsByTagName("img")); -- this._forEachNode(imgs, function(img) { -+ this._forEachNode(imgs, function (img) { - for (var i = 0; i < img.attributes.length; i++) { - var attr = img.attributes[i]; - switch (attr.name) { -@@ -1610,7 +1859,7 @@ Readability.prototype = { - - // Next find noscript and try to extract its image - var noscripts = Array.from(doc.getElementsByTagName("noscript")); -- this._forEachNode(noscripts, function(noscript) { -+ this._forEachNode(noscripts, function (noscript) { - // Parse content of noscript and make sure it only contains image - var tmp = doc.createElement("div"); - tmp.innerHTML = noscript.innerHTML; -@@ -1635,7 +1884,11 @@ Readability.prototype = { - continue; - } - -- if (attr.name === "src" || attr.name === "srcset" || /\.(jpg|jpeg|png|webp)/i.test(attr.value)) { -+ if ( -+ attr.name === "src" || -+ attr.name === "srcset" || -+ /\.(jpg|jpeg|png|webp)/i.test(attr.value) -+ ) { - if (newImg.getAttribute(attr.name) === attr.value) { - continue; - } -@@ -1658,8 +1911,8 @@ Readability.prototype = { - * Removes script tags from the document. - * - * @param Element -- **/ -- _removeScripts: function(doc) { -+ **/ -+ _removeScripts: function (doc) { - this._removeNodes(this._getAllNodesWithTag(doc, ["script", "noscript"])); - }, - -@@ -1670,25 +1923,31 @@ Readability.prototype = { - * - * @param Element - * @param string tag of child element -- **/ -- _hasSingleTagInsideElement: function(element, tag) { -+ **/ -+ _hasSingleTagInsideElement: function (element, tag) { - // There should be exactly 1 element child with given tag - if (element.children.length != 1 || element.children[0].tagName !== tag) { - return false; - } - - // And there should be no text nodes with real content -- return !this._someNode(element.childNodes, function(node) { -- return node.nodeType === this.TEXT_NODE && -- this.REGEXPS.hasContent.test(node.textContent); -+ return !this._someNode(element.childNodes, function (node) { -+ return ( -+ node.nodeType === this.TEXT_NODE && -+ this.REGEXPS.hasContent.test(node.textContent) -+ ); - }); - }, - -- _isElementWithoutContent: function(node) { -- return node.nodeType === this.ELEMENT_NODE && -+ _isElementWithoutContent: function (node) { -+ return ( -+ node.nodeType === this.ELEMENT_NODE && - node.textContent.trim().length == 0 && - (node.children.length == 0 || -- node.children.length == node.getElementsByTagName("br").length + node.getElementsByTagName("hr").length); -+ node.children.length == -+ node.getElementsByTagName("br").length + -+ node.getElementsByTagName("hr").length) -+ ); - }, - - /** -@@ -1697,25 +1956,35 @@ Readability.prototype = { - * @param Element - */ - _hasChildBlockElement: function (element) { -- return this._someNode(element.childNodes, function(node) { -- return this.DIV_TO_P_ELEMS.has(node.tagName) || -- this._hasChildBlockElement(node); -+ return this._someNode(element.childNodes, function (node) { -+ return ( -+ this.DIV_TO_P_ELEMS.has(node.tagName) || -+ this._hasChildBlockElement(node) -+ ); - }); - }, - - /*** - * Determine if a node qualifies as phrasing content. - * https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Content_categories#Phrasing_content -- **/ -- _isPhrasingContent: function(node) { -- return node.nodeType === this.TEXT_NODE || this.PHRASING_ELEMS.indexOf(node.tagName) !== -1 || -- ((node.tagName === "A" || node.tagName === "DEL" || node.tagName === "INS") && -- this._everyNode(node.childNodes, this._isPhrasingContent)); -+ **/ -+ _isPhrasingContent: function (node) { -+ return ( -+ node.nodeType === this.TEXT_NODE || -+ this.PHRASING_ELEMS.indexOf(node.tagName) !== -1 || -+ ((node.tagName === "A" || -+ node.tagName === "DEL" || -+ node.tagName === "INS") && -+ this._everyNode(node.childNodes, this._isPhrasingContent)) -+ ); - }, - -- _isWhitespace: function(node) { -- return (node.nodeType === this.TEXT_NODE && node.textContent.trim().length === 0) || -- (node.nodeType === this.ELEMENT_NODE && node.tagName === "BR"); -+ _isWhitespace: function (node) { -+ return ( -+ (node.nodeType === this.TEXT_NODE && -+ node.textContent.trim().length === 0) || -+ (node.nodeType === this.ELEMENT_NODE && node.tagName === "BR") -+ ); - }, - - /** -@@ -1725,9 +1994,10 @@ Readability.prototype = { - * @param Element - * @param Boolean normalizeSpaces (default: true) - * @return string -- **/ -- _getInnerText: function(e, normalizeSpaces) { -- normalizeSpaces = (typeof normalizeSpaces === "undefined") ? true : normalizeSpaces; -+ **/ -+ _getInnerText: function (e, normalizeSpaces) { -+ normalizeSpaces = -+ typeof normalizeSpaces === "undefined" ? true : normalizeSpaces; - var textContent = e.textContent.trim(); - - if (normalizeSpaces) { -@@ -1742,8 +2012,8 @@ Readability.prototype = { - * @param Element - * @param string - what to split on. Default is "," - * @return number (integer) -- **/ -- _getCharCount: function(e, s) { -+ **/ -+ _getCharCount: function (e, s) { - s = s || ","; - return this._getInnerText(e).split(s).length - 1; - }, -@@ -1754,10 +2024,9 @@ Readability.prototype = { - * - * @param Element - * @return void -- **/ -- _cleanStyles: function(e) { -- if (!e || e.tagName.toLowerCase() === "svg") -- return; -+ **/ -+ _cleanStyles: function (e) { -+ if (!e || e.tagName.toLowerCase() === "svg") return; - - // Remove `style` and deprecated presentational attributes - for (var i = 0; i < this.PRESENTATIONAL_ATTRIBUTES.length; i++) { -@@ -1782,16 +2051,15 @@ Readability.prototype = { - * - * @param Element - * @return number (float) -- **/ -- _getLinkDensity: function(element) { -+ **/ -+ _getLinkDensity: function (element) { - var textLength = this._getInnerText(element).length; -- if (textLength === 0) -- return 0; -+ if (textLength === 0) return 0; - - var linkLength = 0; - - // XXX implement _reduceNodeList? -- this._forEachNode(element.getElementsByTagName("a"), function(linkNode) { -+ this._forEachNode(element.getElementsByTagName("a"), function (linkNode) { - var href = linkNode.getAttribute("href"); - var coefficient = href && this.REGEXPS.hashUrl.test(href) ? 0.3 : 1; - linkLength += this._getInnerText(linkNode).length * coefficient; -@@ -1806,29 +2074,24 @@ Readability.prototype = { - * - * @param Element - * @return number (Integer) -- **/ -- _getClassWeight: function(e) { -- if (!this._flagIsActive(this.FLAG_WEIGHT_CLASSES)) -- return 0; -+ **/ -+ _getClassWeight: function (e) { -+ if (!this._flagIsActive(this.FLAG_WEIGHT_CLASSES)) return 0; - - var weight = 0; - - // Look for a special classname -- if (typeof(e.className) === "string" && e.className !== "") { -- if (this.REGEXPS.negative.test(e.className)) -- weight -= 25; -+ if (typeof e.className === "string" && e.className !== "") { -+ if (this.REGEXPS.negative.test(e.className)) weight -= 25; - -- if (this.REGEXPS.positive.test(e.className)) -- weight += 25; -+ if (this.REGEXPS.positive.test(e.className)) weight += 25; - } - - // Look for a special ID -- if (typeof(e.id) === "string" && e.id !== "") { -- if (this.REGEXPS.negative.test(e.id)) -- weight -= 25; -+ if (typeof e.id === "string" && e.id !== "") { -+ if (this.REGEXPS.negative.test(e.id)) weight -= 25; - -- if (this.REGEXPS.positive.test(e.id)) -- weight += 25; -+ if (this.REGEXPS.positive.test(e.id)) weight += 25; - } - - return weight; -@@ -1842,10 +2105,10 @@ Readability.prototype = { - * @param string tag to clean - * @return void - **/ -- _clean: function(e, tag) { -+ _clean: function (e, tag) { - var isEmbed = ["object", "embed", "iframe"].indexOf(tag) !== -1; - -- this._removeNodes(this._getAllNodesWithTag(e, [tag]), function(element) { -+ this._removeNodes(this._getAllNodesWithTag(e, [tag]), function (element) { - // Allow youtube and vimeo videos through as people usually want to see those. - if (isEmbed) { - // First, check the elements attributes to see if any of them contain youtube or vimeo -@@ -1856,7 +2119,10 @@ Readability.prototype = { - } - - // For embed with tag, check inner HTML as well. -- if (element.tagName === "object" && this._allowedVideoRegex.test(element.innerHTML)) { -+ if ( -+ element.tagName === "object" && -+ this._allowedVideoRegex.test(element.innerHTML) -+ ) { - return false; - } - } -@@ -1874,14 +2140,16 @@ Readability.prototype = { - * @param Function filterFn a filter to invoke to determine whether this node 'counts' - * @return Boolean - */ -- _hasAncestorTag: function(node, tagName, maxDepth, filterFn) { -+ _hasAncestorTag: function (node, tagName, maxDepth, filterFn) { - maxDepth = maxDepth || 3; - tagName = tagName.toUpperCase(); - var depth = 0; - while (node.parentNode) { -- if (maxDepth > 0 && depth > maxDepth) -- return false; -- if (node.parentNode.tagName === tagName && (!filterFn || filterFn(node.parentNode))) -+ if (maxDepth > 0 && depth > maxDepth) return false; -+ if ( -+ node.parentNode.tagName === tagName && -+ (!filterFn || filterFn(node.parentNode)) -+ ) - return true; - node = node.parentNode; - depth++; -@@ -1892,7 +2160,7 @@ Readability.prototype = { - /** - * Return an object indicating how many rows and columns this table has. - */ -- _getRowAndColumnCount: function(table) { -+ _getRowAndColumnCount: function (table) { - var rows = 0; - var columns = 0; - var trs = table.getElementsByTagName("tr"); -@@ -1901,7 +2169,7 @@ Readability.prototype = { - if (rowspan) { - rowspan = parseInt(rowspan, 10); - } -- rows += (rowspan || 1); -+ rows += rowspan || 1; - - // Now look for column-related info - var columnsInThisRow = 0; -@@ -1911,11 +2179,11 @@ Readability.prototype = { - if (colspan) { - colspan = parseInt(colspan, 10); - } -- columnsInThisRow += (colspan || 1); -+ columnsInThisRow += colspan || 1; - } - columns = Math.max(columns, columnsInThisRow); - } -- return {rows: rows, columns: columns}; -+ return { rows: rows, columns: columns }; - }, - - /** -@@ -1923,7 +2191,7 @@ Readability.prototype = { - * similar checks as - * https://searchfox.org/mozilla-central/rev/f82d5c549f046cb64ce5602bfd894b7ae807c8f8/accessible/generic/TableAccessible.cpp#19 - */ -- _markDataTables: function(root) { -+ _markDataTables: function (root) { - var tables = root.getElementsByTagName("table"); - for (var i = 0; i < tables.length; i++) { - var table = tables[i]; -@@ -1951,7 +2219,7 @@ Readability.prototype = { - - // If the table has a descendant with any of these tags, consider a data table: - var dataTableDescendants = ["col", "colgroup", "tfoot", "thead", "th"]; -- var descendantExists = function(tag) { -+ var descendantExists = function (tag) { - return !!table.getElementsByTagName(tag)[0]; - }; - if (dataTableDescendants.some(descendantExists)) { -@@ -1978,82 +2246,98 @@ Readability.prototype = { - - /* convert images and figures that have properties like data-src into images that can be loaded without JS */ - _fixLazyImages: function (root) { -- this._forEachNode(this._getAllNodesWithTag(root, ["img", "picture", "figure"]), function (elem) { -- // In some sites (e.g. Kotaku), they put 1px square image as base64 data uri in the src attribute. -- // So, here we check if the data uri is too short, just might as well remove it. -- if (elem.src && this.REGEXPS.b64DataUrl.test(elem.src)) { -- // Make sure it's not SVG, because SVG can have a meaningful image in under 133 bytes. -- var parts = this.REGEXPS.b64DataUrl.exec(elem.src); -- if (parts[1] === "image/svg+xml") { -- return; -- } -- -- // Make sure this element has other attributes which contains image. -- // If it doesn't, then this src is important and shouldn't be removed. -- var srcCouldBeRemoved = false; -- for (var i = 0; i < elem.attributes.length; i++) { -- var attr = elem.attributes[i]; -- if (attr.name === "src") { -- continue; -+ this._forEachNode( -+ this._getAllNodesWithTag(root, ["img", "picture", "figure"]), -+ function (elem) { -+ // In some sites (e.g. Kotaku), they put 1px square image as base64 data uri in the src attribute. -+ // So, here we check if the data uri is too short, just might as well remove it. -+ if (elem.src && this.REGEXPS.b64DataUrl.test(elem.src)) { -+ // Make sure it's not SVG, because SVG can have a meaningful image in under 133 bytes. -+ var parts = this.REGEXPS.b64DataUrl.exec(elem.src); -+ if (parts[1] === "image/svg+xml") { -+ return; - } - -- if (/\.(jpg|jpeg|png|webp)/i.test(attr.value)) { -- srcCouldBeRemoved = true; -- break; -+ // Make sure this element has other attributes which contains image. -+ // If it doesn't, then this src is important and shouldn't be removed. -+ var srcCouldBeRemoved = false; -+ for (var i = 0; i < elem.attributes.length; i++) { -+ var attr = elem.attributes[i]; -+ if (attr.name === "src") { -+ continue; -+ } -+ -+ if (/\.(jpg|jpeg|png|webp)/i.test(attr.value)) { -+ srcCouldBeRemoved = true; -+ break; -+ } - } -- } - -- // Here we assume if image is less than 100 bytes (or 133B after encoded to base64) -- // it will be too small, therefore it might be placeholder image. -- if (srcCouldBeRemoved) { -- var b64starts = elem.src.search(/base64\s*/i) + 7; -- var b64length = elem.src.length - b64starts; -- if (b64length < 133) { -- elem.removeAttribute("src"); -+ // Here we assume if image is less than 100 bytes (or 133B after encoded to base64) -+ // it will be too small, therefore it might be placeholder image. -+ if (srcCouldBeRemoved) { -+ var b64starts = elem.src.search(/base64\s*/i) + 7; -+ var b64length = elem.src.length - b64starts; -+ if (b64length < 133) { -+ elem.removeAttribute("src"); -+ } - } - } -- } - -- // also check for "null" to work around https://github.com/jsdom/jsdom/issues/2580 -- if ((elem.src || (elem.srcset && elem.srcset != "null")) && elem.className.toLowerCase().indexOf("lazy") === -1) { -- return; -- } -- -- for (var j = 0; j < elem.attributes.length; j++) { -- attr = elem.attributes[j]; -- if (attr.name === "src" || attr.name === "srcset" || attr.name === "alt") { -- continue; -- } -- var copyTo = null; -- if (/\.(jpg|jpeg|png|webp)\s+\d/.test(attr.value)) { -- copyTo = "srcset"; -- } else if (/^\s*\S+\.(jpg|jpeg|png|webp)\S*\s*$/.test(attr.value)) { -- copyTo = "src"; -+ // also check for "null" to work around https://github.com/jsdom/jsdom/issues/2580 -+ if ( -+ (elem.src || (elem.srcset && elem.srcset != "null")) && -+ elem.className.toLowerCase().indexOf("lazy") === -1 -+ ) { -+ return; - } -- if (copyTo) { -- //if this is an img or picture, set the attribute directly -- if (elem.tagName === "IMG" || elem.tagName === "PICTURE") { -- elem.setAttribute(copyTo, attr.value); -- } else if (elem.tagName === "FIGURE" && !this._getAllNodesWithTag(elem, ["img", "picture"]).length) { -- //if the item is a
that does not contain an image or picture, create one and place it inside the figure -- //see the nytimes-3 testcase for an example -- var img = this._doc.createElement("img"); -- img.setAttribute(copyTo, attr.value); -- elem.appendChild(img); -+ -+ for (var j = 0; j < elem.attributes.length; j++) { -+ attr = elem.attributes[j]; -+ if ( -+ attr.name === "src" || -+ attr.name === "srcset" || -+ attr.name === "alt" -+ ) { -+ continue; -+ } -+ var copyTo = null; -+ if (/\.(jpg|jpeg|png|webp)\s+\d/.test(attr.value)) { -+ copyTo = "srcset"; -+ } else if (/^\s*\S+\.(jpg|jpeg|png|webp)\S*\s*$/.test(attr.value)) { -+ copyTo = "src"; -+ } -+ if (copyTo) { -+ //if this is an img or picture, set the attribute directly -+ if (elem.tagName === "IMG" || elem.tagName === "PICTURE") { -+ elem.setAttribute(copyTo, attr.value); -+ } else if ( -+ elem.tagName === "FIGURE" && -+ !this._getAllNodesWithTag(elem, ["img", "picture"]).length -+ ) { -+ //if the item is a
that does not contain an image or picture, create one and place it inside the figure -+ //see the nytimes-3 testcase for an example -+ var img = this._doc.createElement("img"); -+ img.setAttribute(copyTo, attr.value); -+ elem.appendChild(img); -+ } - } - } - } -- }); -+ ); - }, - -- _getTextDensity: function(e, tags) { -+ _getTextDensity: function (e, tags) { - var textLength = this._getInnerText(e, true).length; - if (textLength === 0) { - return 0; - } - var childrenLength = 0; - var children = this._getAllNodesWithTag(e, tags); -- this._forEachNode(children, (child) => childrenLength += this._getInnerText(child, true).length); -+ this._forEachNode( -+ children, -+ (child) => (childrenLength += this._getInnerText(child, true).length) -+ ); - return childrenLength / textLength; - }, - -@@ -2063,18 +2347,17 @@ Readability.prototype = { - * - * @return void - **/ -- _cleanConditionally: function(e, tag) { -- if (!this._flagIsActive(this.FLAG_CLEAN_CONDITIONALLY)) -- return; -+ _cleanConditionally: function (e, tag) { -+ if (!this._flagIsActive(this.FLAG_CLEAN_CONDITIONALLY)) return; - - // Gather counts for other typical elements embedded within. - // Traverse backwards so we can remove nodes at the same time - // without effecting the traversal. - // - // TODO: Consider taking into account original contentScore here. -- this._removeNodes(this._getAllNodesWithTag(e, [tag]), function(node) { -+ this._removeNodes(this._getAllNodesWithTag(e, [tag]), function (node) { - // First check if this node IS data table, in which case don't remove it. -- var isDataTable = function(t) { -+ var isDataTable = function (t) { - return t._readabilityDataTable; - }; - -@@ -2082,7 +2365,10 @@ Readability.prototype = { - if (!isList) { - var listLength = 0; - var listNodes = this._getAllNodesWithTag(node, ["ul", "ol"]); -- this._forEachNode(listNodes, (list) => listLength += this._getInnerText(list).length); -+ this._forEachNode( -+ listNodes, -+ (list) => (listLength += this._getInnerText(list).length) -+ ); - isList = listLength / this._getInnerText(node).length > 0.9; - } - -@@ -2117,10 +2403,21 @@ Readability.prototype = { - var img = node.getElementsByTagName("img").length; - var li = node.getElementsByTagName("li").length - 100; - var input = node.getElementsByTagName("input").length; -- var headingDensity = this._getTextDensity(node, ["h1", "h2", "h3", "h4", "h5", "h6"]); -+ var headingDensity = this._getTextDensity(node, [ -+ "h1", -+ "h2", -+ "h3", -+ "h4", -+ "h5", -+ "h6", -+ ]); - - var embedCount = 0; -- var embeds = this._getAllNodesWithTag(node, ["object", "embed", "iframe"]); -+ var embeds = this._getAllNodesWithTag(node, [ -+ "object", -+ "embed", -+ "iframe", -+ ]); - - for (var i = 0; i < embeds.length; i++) { - // If this embed has attribute that matches video regex, don't delete it. -@@ -2131,7 +2428,10 @@ Readability.prototype = { - } - - // For embed with tag, check inner HTML as well. -- if (embeds[i].tagName === "object" && this._allowedVideoRegex.test(embeds[i].innerHTML)) { -+ if ( -+ embeds[i].tagName === "object" && -+ this._allowedVideoRegex.test(embeds[i].innerHTML) -+ ) { - return false; - } - -@@ -2144,11 +2444,16 @@ Readability.prototype = { - var haveToRemove = - (img > 1 && p / img < 0.5 && !this._hasAncestorTag(node, "figure")) || - (!isList && li > p) || -- (input > Math.floor(p/3)) || -- (!isList && headingDensity < 0.9 && contentLength < 25 && (img === 0 || img > 2) && !this._hasAncestorTag(node, "figure")) || -+ input > Math.floor(p / 3) || -+ (!isList && -+ headingDensity < 0.9 && -+ contentLength < 25 && -+ (img === 0 || img > 2) && -+ !this._hasAncestorTag(node, "figure")) || - (!isList && weight < 25 && linkDensity > 0.2) || - (weight >= 25 && linkDensity > 0.5) || -- ((embedCount === 1 && contentLength < 75) || embedCount > 1); -+ (embedCount === 1 && contentLength < 75) || -+ embedCount > 1; - // Allow simple lists of images to remain in pages - if (isList && haveToRemove) { - for (var x = 0; x < node.children.length; x++) { -@@ -2177,7 +2482,7 @@ Readability.prototype = { - * @param Function determines whether a node should be removed - * @return void - **/ -- _cleanMatchedNodes: function(e, filter) { -+ _cleanMatchedNodes: function (e, filter) { - var endOfSearchMarkerNode = this._getNextNode(e, true); - var next = this._getNextNode(e); - while (next && next != endOfSearchMarkerNode) { -@@ -2194,10 +2499,10 @@ Readability.prototype = { - * - * @param Element - * @return void -- **/ -- _cleanHeaders: function(e) { -+ **/ -+ _cleanHeaders: function (e) { - let headingNodes = this._getAllNodesWithTag(e, ["h1", "h2"]); -- this._removeNodes(headingNodes, function(node) { -+ this._removeNodes(headingNodes, function (node) { - let shouldRemove = this._getClassWeight(node) < 0; - if (shouldRemove) { - this.log("Removing header with low class weight:", node); -@@ -2213,7 +2518,7 @@ Readability.prototype = { - * @param Element the node to check. - * @return boolean indicating whether this is a title-like header. - */ -- _headerDuplicatesTitle: function(node) { -+ _headerDuplicatesTitle: function (node) { - if (node.tagName != "H1" && node.tagName != "H2") { - return false; - } -@@ -2222,21 +2527,27 @@ Readability.prototype = { - return this._textSimilarity(this._articleTitle, heading) > 0.75; - }, - -- _flagIsActive: function(flag) { -+ _flagIsActive: function (flag) { - return (this._flags & flag) > 0; - }, - -- _removeFlag: function(flag) { -+ _removeFlag: function (flag) { - this._flags = this._flags & ~flag; - }, - -- _isProbablyVisible: function(node) { -+ _isProbablyVisible: function (node) { - // Have to null-check node.style and node.className.indexOf to deal with SVG and MathML nodes. -- return (!node.style || node.style.display != "none") -- && (!node.style || node.style.visibility != "hidden") -- && !node.hasAttribute("hidden") -+ return ( -+ (!node.style || node.style.display != "none") && -+ (!node.style || node.style.visibility != "hidden") && -+ !(node.hasAttribute("hidden") && !node.id.startsWith("S:")) && - //check for "fallback-image" so that wikimedia math images are displayed -- && (!node.hasAttribute("aria-hidden") || node.getAttribute("aria-hidden") != "true" || (node.className && node.className.indexOf && node.className.indexOf("fallback-image") !== -1)); -+ (!node.hasAttribute("aria-hidden") || -+ node.getAttribute("aria-hidden") != "true" || -+ (node.className && -+ node.className.indexOf && -+ node.className.indexOf("fallback-image") !== -1)) -+ ); - }, - - /** -@@ -2256,7 +2567,9 @@ Readability.prototype = { - if (this._maxElemsToParse > 0) { - var numTags = this._doc.getElementsByTagName("*").length; - if (numTags > this._maxElemsToParse) { -- throw new Error("Aborting parsing document; " + numTags + " elements found"); -+ throw new Error( -+ "Aborting parsing document; " + numTags + " elements found" -+ ); - } - } - -@@ -2275,8 +2588,7 @@ Readability.prototype = { - this._articleTitle = metadata.title; - - var articleContent = this._grabArticle(); -- if (!articleContent) -- return null; -+ if (!articleContent) return null; - - this.log("Grabbed: " + articleContent.innerHTML); - -@@ -2303,9 +2615,9 @@ Readability.prototype = { - length: textContent.length, - excerpt: metadata.excerpt, - siteName: metadata.siteName || this._articleSiteName, -- publishedTime: metadata.publishedTime -+ publishedTime: metadata.publishedTime, - }; -- } -+ }, - }; - - if (typeof module === "object") { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 68033b355..b8e485b16 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -9,9 +9,9 @@ overrides: isarray: npm:@nolyfill/isarray@^1 patchedDependencies: - '@mozilla/readability@0.5.0': - hash: fgkvsbckled47trggkhdkimzbm - path: patches/@mozilla__readability@0.5.0.patch + '@mozilla/readability': + hash: 43niildbdafdxi7qfcwhpkkxwa + path: patches/@mozilla__readability.patch electron-context-menu: hash: c53at4t5fflixuwjz35hmcqdu4 path: patches/electron-context-menu.patch @@ -88,7 +88,7 @@ importers: version: 4.3.1 '@mozilla/readability': specifier: ^0.5.0 - version: 0.5.0(patch_hash=fgkvsbckled47trggkhdkimzbm) + version: 0.5.0(patch_hash=43niildbdafdxi7qfcwhpkkxwa) '@pengx17/electron-forge-maker-appimage': specifier: 1.2.1 version: 1.2.1(dmg-builder@25.0.5(electron-builder-squirrel-windows@25.0.5))(electron-builder-squirrel-windows@25.0.5(dmg-builder@25.0.5)) @@ -155,6 +155,9 @@ importers: fake-indexeddb: specifier: 6.0.0 version: 6.0.0 + happy-dom: + specifier: 15.7.4 + version: 15.7.4 hono: specifier: 4.6.3 version: 4.6.3(patch_hash=iej2g43ojhll5opwbnvyorjq4e) @@ -214,7 +217,7 @@ importers: version: 5.0.1(typescript@5.6.2)(vite@5.4.8(@types/node@22.7.4)(terser@5.34.1)) vitest: specifier: 2.0.5 - version: 2.0.5(@types/node@22.7.4)(terser@5.34.1) + version: 2.0.5(@types/node@22.7.4)(happy-dom@15.7.4)(terser@5.34.1) apps/main: dependencies: @@ -235,7 +238,7 @@ importers: version: link:../../packages/shared '@mozilla/readability': specifier: ^0.5.0 - version: 0.5.0(patch_hash=fgkvsbckled47trggkhdkimzbm) + version: 0.5.0(patch_hash=43niildbdafdxi7qfcwhpkkxwa) '@sentry/electron': specifier: 5.4.0 version: 5.4.0 @@ -350,7 +353,7 @@ importers: version: 4.3.1 '@mozilla/readability': specifier: ^0.5.0 - version: 0.5.0(patch_hash=fgkvsbckled47trggkhdkimzbm) + version: 0.5.0(patch_hash=43niildbdafdxi7qfcwhpkkxwa) '@radix-ui/react-avatar': specifier: 1.1.0 version: 1.1.0(@types/react-dom@18.3.0)(@types/react@18.3.10)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) @@ -642,7 +645,7 @@ importers: version: 18.3.1(react@18.3.1) vitest: specifier: '2.0' - version: 2.0.5(@types/node@22.7.4)(terser@5.34.1) + version: 2.0.5(@types/node@22.7.4)(happy-dom@15.7.4)(terser@5.34.1) packages/shared: dependencies: @@ -5672,6 +5675,10 @@ packages: engines: {node: '>=0.4.7'} hasBin: true + happy-dom@15.7.4: + resolution: {integrity: sha512-r1vadDYGMtsHAAsqhDuk4IpPvr6N8MGKy5ntBo7tSdim+pWDxus2PNqOcOt8LuDZ4t3KJHE+gCuzupcx/GKnyQ==} + engines: {node: '>=18.0.0'} + has-flag@3.0.0: resolution: {integrity: sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==} engines: {node: '>=4'} @@ -8760,6 +8767,10 @@ packages: webidl-conversions@4.0.2: resolution: {integrity: sha512-YQ+BmxuTgd6UXZW3+ICGfyqRyHXVlD5GtQr5+qjiNW7bF0cqrzX500HVXPBOvgXb5YnzDd+h0zqyv61KUD7+Sg==} + webidl-conversions@7.0.0: + resolution: {integrity: sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==} + engines: {node: '>=12'} + webpack-sources@3.2.3: resolution: {integrity: sha512-/DyMEOrDgLKKIG0fmvtz+4dUX/3Ghozwgm6iPp8KRhvn+eQf9+Q7GWxVNMk3+uCPWfdXYC4ExGBckIXdFEfH1w==} engines: {node: '>=10.13.0'} @@ -8771,6 +8782,10 @@ packages: resolution: {integrity: sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==} engines: {node: '>=18'} + whatwg-mimetype@3.0.0: + resolution: {integrity: sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==} + engines: {node: '>=12'} + whatwg-mimetype@4.0.0: resolution: {integrity: sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==} engines: {node: '>=18'} @@ -10768,7 +10783,7 @@ snapshots: transitivePeerDependencies: - supports-color - '@mozilla/readability@0.5.0(patch_hash=fgkvsbckled47trggkhdkimzbm)': {} + '@mozilla/readability@0.5.0(patch_hash=43niildbdafdxi7qfcwhpkkxwa)': {} '@nodelib/fs.scandir@2.1.5': dependencies: @@ -15116,6 +15131,12 @@ snapshots: optionalDependencies: uglify-js: 3.19.2 + happy-dom@15.7.4: + dependencies: + entities: 4.5.0 + webidl-conversions: 7.0.0 + whatwg-mimetype: 3.0.0 + has-flag@3.0.0: {} has-flag@4.0.0: {} @@ -18570,7 +18591,7 @@ snapshots: fsevents: 2.3.3 terser: 5.34.1 - vitest@2.0.5(@types/node@22.7.4)(terser@5.34.1): + vitest@2.0.5(@types/node@22.7.4)(happy-dom@15.7.4)(terser@5.34.1): dependencies: '@ampproject/remapping': 2.3.0 '@vitest/expect': 2.0.5 @@ -18593,6 +18614,7 @@ snapshots: why-is-node-running: 2.3.0 optionalDependencies: '@types/node': 22.7.4 + happy-dom: 15.7.4 transitivePeerDependencies: - less - lightningcss @@ -18617,6 +18639,8 @@ snapshots: webidl-conversions@4.0.2: {} + webidl-conversions@7.0.0: {} + webpack-sources@3.2.3: {} webpack-virtual-modules@0.5.0: {} @@ -18625,6 +18649,8 @@ snapshots: dependencies: iconv-lite: 0.6.3 + whatwg-mimetype@3.0.0: {} + whatwg-mimetype@4.0.0: {} whatwg-url@5.0.0: From f84c12e099c118e449ddd473830465b9bf21caea Mon Sep 17 00:00:00 2001 From: Innei Date: Mon, 14 Oct 2024 13:12:15 +0800 Subject: [PATCH 10/52] fix(code): bypass if no `` wrapper Signed-off-by: Innei --- apps/renderer/src/lib/parse-html.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/apps/renderer/src/lib/parse-html.ts b/apps/renderer/src/lib/parse-html.ts index d63d0f531..0d75ef6f3 100644 --- a/apps/renderer/src/lib/parse-html.ts +++ b/apps/renderer/src/lib/parse-html.ts @@ -177,11 +177,12 @@ export const parseHtml = ( codeString = props.children.toString() } else { const propsChildren = props.children - let children = Array.isArray(propsChildren) + const children = Array.isArray(propsChildren) ? propsChildren.find((i) => i.type === "code") : propsChildren - if (!children) children = createElement("pre", props, props.children) + // Don't process not code block + if (!children) return createElement("pre", props, props.children) if ( "type" in children && From ef8939868986cbbdc3f00cc865b3b435a611b936 Mon Sep 17 00:00:00 2001 From: Innei Date: Mon, 14 Oct 2024 16:35:23 +0800 Subject: [PATCH 11/52] feat: support latex, resolve #917 Signed-off-by: Innei --- apps/renderer/package.json | 2 ++ .../src/components/ui/katex/index.tsx | 30 +++++++++++++++++++ .../src/components/ui/markdown/Markdown.tsx | 2 ++ .../ui/markdown/renderers/MarkdownP.tsx | 7 ++++- .../components/ui/markdown/renderers/ctx.tsx | 10 +++++++ apps/renderer/src/lib/parse-html.ts | 18 +++++++++++ pnpm-lock.yaml | 25 ++++++++++++++++ 7 files changed, 93 insertions(+), 1 deletion(-) create mode 100644 apps/renderer/src/components/ui/katex/index.tsx create mode 100644 apps/renderer/src/components/ui/markdown/renderers/ctx.tsx diff --git a/apps/renderer/package.json b/apps/renderer/package.json index 1eb1f6944..30798219f 100644 --- a/apps/renderer/package.json +++ b/apps/renderer/package.json @@ -66,6 +66,7 @@ "idb-keyval": "6.2.1", "immer": "10.1.1", "jotai": "2.10.0", + "katex": "0.16.11", "lethargy": "1.0.9", "lodash-es": "4.17.21", "masonic": "4.0.1", @@ -111,6 +112,7 @@ "devDependencies": { "@babel/generator": "7.25.6", "@hono/node-server": "1.13.1", + "@types/katex": "0.16.7", "@types/lodash-es": "4.17.12", "@types/node": "^22.7.4", "@types/react": "^18.3.10", diff --git a/apps/renderer/src/components/ui/katex/index.tsx b/apps/renderer/src/components/ui/katex/index.tsx new file mode 100644 index 000000000..9a5b2a02b --- /dev/null +++ b/apps/renderer/src/components/ui/katex/index.tsx @@ -0,0 +1,30 @@ +import katex from "katex" +import type { FC } from "react" +import { useMemo } from "react" + +type KateXProps = { + children: string + mode?: "display" | "inline" +} + +export const KateX: FC = (props) => { + const { children, mode } = props + + const displayMode = mode === "display" + + const throwOnError = false // render unsupported commands as text instead of throwing a `ParseError` + + return ( + ({ + __html: katex.renderToString(children, { + displayMode, + throwOnError, + }), + }), + [children, displayMode, throwOnError], + )} + /> + ) +} diff --git a/apps/renderer/src/components/ui/markdown/Markdown.tsx b/apps/renderer/src/components/ui/markdown/Markdown.tsx index 0600963e4..d4f68a1b7 100644 --- a/apps/renderer/src/components/ui/markdown/Markdown.tsx +++ b/apps/renderer/src/components/ui/markdown/Markdown.tsx @@ -1,3 +1,4 @@ +import katexStyle from "katex/dist/katex.min.css?url" import { createElement, Fragment, memo, useEffect, useMemo, useRef, useState } from "react" import { parseHtml } from "~/lib/parse-html" @@ -108,6 +109,7 @@ const HTMLImpl = ( + {createElement(as, { ...rest, ref: setRefElement }, markdownElement)} diff --git a/apps/renderer/src/components/ui/markdown/renderers/MarkdownP.tsx b/apps/renderer/src/components/ui/markdown/renderers/MarkdownP.tsx index 6a594f79b..8c0e7a6f7 100644 --- a/apps/renderer/src/components/ui/markdown/renderers/MarkdownP.tsx +++ b/apps/renderer/src/components/ui/markdown/renderers/MarkdownP.tsx @@ -4,6 +4,7 @@ import { FeedViewType } from "~/lib/enum" import { useEntryContentContextSelector } from "~/modules/entry-content/hooks" import { ensureAndRenderTimeStamp } from "../utils" +import { IsInParagraphContext } from "./ctx" export const MarkdownP: Component< React.DetailedHTMLProps, HTMLParagraphElement> @@ -29,5 +30,9 @@ export const MarkdownP: Component< ) } - return

{children}

+ return ( +

+ {children} +

+ ) } diff --git a/apps/renderer/src/components/ui/markdown/renderers/ctx.tsx b/apps/renderer/src/components/ui/markdown/renderers/ctx.tsx new file mode 100644 index 000000000..335a5f82d --- /dev/null +++ b/apps/renderer/src/components/ui/markdown/renderers/ctx.tsx @@ -0,0 +1,10 @@ +import { createContext, useContext } from "react" + +/** + * @internal + */ +export const IsInParagraphContext = createContext(false) + +export const useIsInParagraphContext = () => { + return useContext(IsInParagraphContext) +} diff --git a/apps/renderer/src/lib/parse-html.ts b/apps/renderer/src/lib/parse-html.ts index 0d75ef6f3..fb96ea42d 100644 --- a/apps/renderer/src/lib/parse-html.ts +++ b/apps/renderer/src/lib/parse-html.ts @@ -18,8 +18,10 @@ import { VFile } from "vfile" import { ShadowDOM } from "~/components/common/ShadowDOM" import { Checkbox } from "~/components/ui/checkbox" import { ShikiHighLighter } from "~/components/ui/code-highlighter" +import { KateX } from "~/components/ui/katex" import { MarkdownBlockImage, MarkdownLink, MarkdownP } from "~/components/ui/markdown/renderers" import { BlockError } from "~/components/ui/markdown/renderers/BlockErrorBoundary" +import { useIsInParagraphContext } from "~/components/ui/markdown/renderers/ctx" import { createHeadingRenderer } from "~/components/ui/markdown/renderers/Heading" import { MarkdownInlineImage } from "~/components/ui/markdown/renderers/InlineImage" import { Media } from "~/components/ui/media" @@ -68,6 +70,7 @@ export const parseHtml = ( const { renderInlineStyle = false, noMedia = false } = options || {} const rehypeSchema: Schema = { ...defaultSchema } + rehypeSchema.tagNames = [...rehypeSchema.tagNames!, "math"] if (noMedia) { rehypeSchema.tagNames = rehypeSchema.tagNames?.filter( @@ -148,6 +151,8 @@ export const parseHtml = ( markInlineImage(node) return createElement("span", props, props.children) }, + // @ts-expect-error + math: Math, hr: ({ node, ...props }) => createElement("hr", { ...props, @@ -359,3 +364,16 @@ function rehypeUrlToAnchor(tree: Node) { ;(parent.children as (Text | Element)[]).splice(index, 1, ...newNodes) }) } + +const Math = ({ node }) => { + const annotation = node.children.at(-1) + + const isInParagraph = useIsInParagraphContext() + if (!annotation) return null + const latex = annotation.value + + return createElement(KateX, { + children: latex, + mode: isInParagraph ? "inline" : "display", + }) +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b8e485b16..26a0f431a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -492,6 +492,9 @@ importers: jotai: specifier: 2.10.0 version: 2.10.0(@types/react@18.3.10)(react@18.3.1) + katex: + specifier: 0.16.11 + version: 0.16.11 lethargy: specifier: 1.0.9 version: 1.0.9 @@ -622,6 +625,9 @@ importers: '@hono/node-server': specifier: 1.13.1 version: 1.13.1(hono@4.6.3(patch_hash=iej2g43ojhll5opwbnvyorjq4e)) + '@types/katex': + specifier: 0.16.7 + version: 0.16.7 '@types/lodash-es': specifier: 4.17.12 version: 4.17.12 @@ -3605,6 +3611,9 @@ packages: '@types/json-schema@7.0.15': resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==} + '@types/katex@0.16.7': + resolution: {integrity: sha512-HMwFiRujE5PjrgwHQ25+bsLJgowjGjm5Z8FVSf0N6PwgJrwxH0QxzHYDcKsTfV3wva0vzrpqMTJS2jXPr5BMEQ==} + '@types/keyv@3.1.4': resolution: {integrity: sha512-BQ5aZNSCpj7D6K2ksrRCTmKRLEpnPvWDiLPfoGyhZ++8YtiK9d/3DBKPJgry359X/P1PfruyYwvnvwFjuEiEIg==} @@ -4405,6 +4414,10 @@ packages: resolution: {integrity: sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==} engines: {node: '>= 10'} + commander@8.3.0: + resolution: {integrity: sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==} + engines: {node: '>= 12'} + commander@9.5.0: resolution: {integrity: sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ==} engines: {node: ^12.20.0 || >=14} @@ -6190,6 +6203,10 @@ packages: jws@3.2.2: resolution: {integrity: sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==} + katex@0.16.11: + resolution: {integrity: sha512-RQrI8rlHY92OLf3rho/Ts8i/XvjgguEjOkO1BEXcU3N8BqPpSzBNwV/G0Ukr+P/l3ivvJUE/Fa/CwbS6HesGNQ==} + hasBin: true + keycode@2.2.1: resolution: {integrity: sha512-Rdgz9Hl9Iv4QKi8b0OlCRQEzp4AgVxyCtz5S/+VIHezDmrDhkp2N2TqBWOLz0/gbeREXOOiI9/4b8BY9uw2vFg==} @@ -12482,6 +12499,8 @@ snapshots: '@types/json-schema@7.0.15': {} + '@types/katex@0.16.7': {} + '@types/keyv@3.1.4': dependencies: '@types/node': 22.7.4 @@ -13533,6 +13552,8 @@ snapshots: commander@7.2.0: {} + commander@8.3.0: {} + commander@9.5.0: {} comment-parser@1.4.1: {} @@ -15706,6 +15727,10 @@ snapshots: jwa: 1.4.1 safe-buffer: 5.2.1 + katex@0.16.11: + dependencies: + commander: 8.3.0 + keycode@2.2.1: {} keycon@1.4.0: From 25234e1bc1b6cd695f93d51b52fb62ddc9adba63 Mon Sep 17 00:00:00 2001 From: Konv Suu <2583695112@qq.com> Date: Mon, 14 Oct 2024 16:45:57 +0800 Subject: [PATCH 12/52] fix: update DropdownMenuTrigger class for open state styling (#931) --- apps/renderer/src/modules/user/ProfileButton.tsx | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/apps/renderer/src/modules/user/ProfileButton.tsx b/apps/renderer/src/modules/user/ProfileButton.tsx index 6b17be689..34af4e669 100644 --- a/apps/renderer/src/modules/user/ProfileButton.tsx +++ b/apps/renderer/src/modules/user/ProfileButton.tsx @@ -49,7 +49,10 @@ export const ProfileButton: FC = memo((props) => { return ( <> - + From cb6eeb132b5088cadfeaae3226429962064273dd Mon Sep 17 00:00:00 2001 From: Innei Date: Mon, 14 Oct 2024 16:47:36 +0800 Subject: [PATCH 13/52] perf: lazy load katex and inline katex style Signed-off-by: Innei --- .../common/MemoedDangerousHTMLStyle.tsx | 19 ++++++++++++ .../src/components/common/ShadowDOM.tsx | 29 ++----------------- .../renderer/src/components/ui/katex/lazy.tsx | 12 ++++++++ .../src/components/ui/markdown/Markdown.tsx | 5 ++-- apps/renderer/src/lib/parse-html.ts | 4 +-- 5 files changed, 39 insertions(+), 30 deletions(-) create mode 100644 apps/renderer/src/components/common/MemoedDangerousHTMLStyle.tsx create mode 100644 apps/renderer/src/components/ui/katex/lazy.tsx diff --git a/apps/renderer/src/components/common/MemoedDangerousHTMLStyle.tsx b/apps/renderer/src/components/common/MemoedDangerousHTMLStyle.tsx new file mode 100644 index 000000000..cad4cf7d5 --- /dev/null +++ b/apps/renderer/src/components/common/MemoedDangerousHTMLStyle.tsx @@ -0,0 +1,19 @@ +import type { FC } from "react" +import { memo, useMemo } from "react" + +export const MemoedDangerousHTMLStyle: FC< + { + children: string + } & React.DetailedHTMLProps, HTMLStyleElement> & + Record +> = memo(({ children, ...rest }) => ( +