An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Improve marketplace configuration maintainability https://github.com/siyuan-note/siyuan/issues/19082
Daniel0c9558ae93a3
diff --git a/app/src/config/bazaar.ts b/app/src/config/bazaar.tsindex 0f9c5f54b3..9b58de2280 100644--- a/app/src/config/bazaar.ts+++ b/app/src/config/bazaar.ts@@ -3,26 +3,17 @@ import {fetchPost} from "../util/fetch";import {confirmDialog} from "../dialog/confirmDialog";import {highlightRender} from "../protyle/render/highlightRender";import {Constants} from "../constants";-/// #if !BROWSER-import * as path from "path";-/// #endifimport {getFrontend, isBrowser, isMobile} from "../util/functions";-import {setStorageVal, writeText} from "../protyle/util/compatibility";-import {hasClosestByAttribute, hasClosestByClassName} from "../protyle/util/hasClosest";-import {Plugin} from "../plugin";+import {hasPluginSetting, Plugin} from "../plugin";import type {App} from "../index";import {escapeAttr, escapeHtml} from "../util/escape";import {formatCount} from "../util/number";import {loadPlugin, unloadPlugin} from "../plugin/loader";-import {setGlobalPluginsDisabled, subscribeGlobalPluginState} from "../plugin/globalState";-import {useShell} from "../util/pathName";+import {subscribeGlobalPluginState} from "../plugin/globalState";import {switchSettingPanelSubTab} from "./setting/mount";import {isThemeFrontendSupported} from "../util/themeCompatibility";import {applyBazaarPackageDeprecation,- applyBazaarPackageRatingToItem,- beginBazaarRatingSubmission,- beginBazaarRatingRequest,getBazaarBackendSystemLabels,getBazaarCompatibilityData,getBazaarCompatibilityFieldVisibility,@@ -30,26 +21,42 @@ import {getBazaarFundingItems,getBazaarKernelSystemLabels,getBazaarPackageInvalidLanguageKey,- getDisplayableBazaarRating,- getBazaarRatingErrorLanguageKey,- getBazaarRatingMutationVersion,getBazaarThemeModeLabels,isBazaarPackageEnableDisabled,- isBazaarPackageRatingEditable,isBazaarPackageRatingLoaded,isBazaarPluginEnabledInPublish,- isBazaarRatingRemovalAvailable,- isLatestBazaarRatingRequest,- isBazaarRatingMutationVersionCurrent,- normalizeBazaarPackageRatingResponse,- normalizeBazaarPackageRatingsResponse,- normalizeBazaarPackageUserRatingsResponse,- normalizeBazaarUserRating,- sortBazaarPackagesByRating,+ sortBazaarPackages,} from "../util/bazaarPackage";-import {Dialog} from "../dialog";-import {previewImages} from "../protyle/preview/image";import {BAZAAR_README_SANITIZE_OPTIONS} from "./bazaarReadmeSanitize";+import {+ BAZAAR_PACKAGE_CONFIG,+ BAZAAR_PACKAGE_TYPES,+} from "./bazaar/packageConfig";+import {genBazaarPackagePanelHTML} from "./bazaar/html";+import {bindBazaarEvents} from "./bazaar/events";+import {+ applyPackageRating,+ applyPackageRatingResponse,+ bindRatingUserChange,+ fetchPackageRating,+ genCardRatingHTML,+ genRatePackageActionHTML,+ genRatingDistributionHTML,+ genRatingStarsHTML,+ genReadmeRatingHTML,+ getRatingItem,+ getRatingKey,+ getRatingSummaryText,+ loadDownloadedRatings,+ loadDownloadedUserRatings,+ loadReadmeRating,+ loadUpdatedRatings,+ openRatingDialog,+ refreshRatingUI,+ refreshVisibleRatingUI,+ submitPackageRating,+ syncRatingUser,+} from "./bazaar/rating";interface IBazaarMountSnapshot {element: HTMLElement;@@ -283,122 +290,11 @@ export const bazaar = {${loadingHTML}</div></div>- <div data-type="theme" class="config-bazaar__panel fn__none">- <div class="fn__flex config-bazaar__title">- <svg class="svg ft__on-surface fn__flex-center"><use xlink:href="#iconSort"></use></svg>- <div class="fn__space"></div>- <select class="b3-select">- <option ${localSort.theme === "0" ? "selected" : ""} value="0">${window.siyuan.languages.sortByUpdateTimeDesc}</option>- <option ${localSort.theme === "1" ? "selected" : ""} value="1">${window.siyuan.languages.sortByUpdateTimeAsc}</option>- <option ${localSort.theme === "2" ? "selected" : ""} value="2">${window.siyuan.languages.sortByDownloadsDesc}</option>- <option ${localSort.theme === "3" ? "selected" : ""} value="3">${window.siyuan.languages.sortByDownloadsAsc}</option>- <option ${localSort.theme === "4" ? "selected" : ""} value="4">${window.siyuan.languages.sortByRatingDesc}</option>- <option ${localSort.theme === "5" ? "selected" : ""} value="5">${window.siyuan.languages.sortByRatingAsc}</option>- </select>- <div class="fn__space"></div>- <select id="bazaarSelect" class="b3-select">- <option selected value="2">${window.siyuan.languages.all}</option>- <option value="0">${window.siyuan.languages.themeLight}</option>- <option value="1">${window.siyuan.languages.themeDark}</option>- </select>- <div class="fn__space"></div>- <div class="fn__flex config-bazaar__filter-row">- <input class="b3-text-field" placeholder="${window.siyuan.languages.enterKey} ${window.siyuan.languages.search}">- <div class="counter counter--bg fn__flex-center ariaLabel" data-position="north" aria-label="${window.siyuan.languages.total}"></div>- </div>- </div>- <div id="configBazaarTheme" class="config-bazaar__content">- ${loadingHTML}- </div>- </div>- <div class="fn__none config-bazaar__panel" data-type="template">- <div class="fn__flex config-bazaar__title">- <svg class="svg ft__on-surface fn__flex-center"><use xlink:href="#iconSort"></use></svg>- <div class="fn__space"></div>- <select class="b3-select">- <option ${localSort.template === "0" ? "selected" : ""} value="0">${window.siyuan.languages.sortByUpdateTimeDesc}</option>- <option ${localSort.template === "1" ? "selected" : ""} value="1">${window.siyuan.languages.sortByUpdateTimeAsc}</option>- <option ${localSort.template === "2" ? "selected" : ""} value="2">${window.siyuan.languages.sortByDownloadsDesc}</option>- <option ${localSort.template === "3" ? "selected" : ""} value="3">${window.siyuan.languages.sortByDownloadsAsc}</option>- <option ${localSort.template === "4" ? "selected" : ""} value="4">${window.siyuan.languages.sortByRatingDesc}</option>- <option ${localSort.template === "5" ? "selected" : ""} value="5">${window.siyuan.languages.sortByRatingAsc}</option>- </select>- <div class="fn__space"></div>- <div class="fn__flex config-bazaar__filter-row">- <input class="b3-text-field" placeholder="${window.siyuan.languages.enterKey} ${window.siyuan.languages.search}">- <div class="counter counter--bg fn__flex-center ariaLabel" data-position="north" aria-label="${window.siyuan.languages.total}"></div>- </div>- </div>- <div id="configBazaarTemplate" class="config-bazaar__content">- ${loadingHTML}- </div>- </div>- <div class="fn__none config-bazaar__panel" data-type="plugin">- <div class="fn__flex config-bazaar__title">- <svg class="svg ft__on-surface fn__flex-center"><use xlink:href="#iconSort"></use></svg>- <div class="fn__space"></div>- <select class="b3-select">- <option ${localSort.plugin === "0" ? "selected" : ""} value="0">${window.siyuan.languages.sortByUpdateTimeDesc}</option>- <option ${localSort.plugin === "1" ? "selected" : ""} value="1">${window.siyuan.languages.sortByUpdateTimeAsc}</option>- <option ${localSort.plugin === "2" ? "selected" : ""} value="2">${window.siyuan.languages.sortByDownloadsDesc}</option>- <option ${localSort.plugin === "3" ? "selected" : ""} value="3">${window.siyuan.languages.sortByDownloadsAsc}</option>- <option ${localSort.plugin === "4" ? "selected" : ""} value="4">${window.siyuan.languages.sortByRatingDesc}</option>- <option ${localSort.plugin === "5" ? "selected" : ""} value="5">${window.siyuan.languages.sortByRatingAsc}</option>- </select>- <div class="fn__space"></div>- <div class="fn__flex config-bazaar__filter-row">- <input class="b3-text-field" placeholder="${window.siyuan.languages.enterKey} ${window.siyuan.languages.search}">- <div class="counter counter--bg fn__flex-center ariaLabel" data-position="north" aria-label="${window.siyuan.languages.total}"></div>- </div>- </div>- <div id="configBazaarPlugin" class="config-bazaar__content">- ${loadingHTML}- </div>- </div>- <div class="fn__none config-bazaar__panel" data-type="icon">- <div class="fn__flex config-bazaar__title">- <svg class="svg ft__on-surface fn__flex-center"><use xlink:href="#iconSort"></use></svg>- <div class="fn__space"></div>- <select class="b3-select">- <option ${localSort.icon === "0" ? "selected" : ""} value="0">${window.siyuan.languages.sortByUpdateTimeDesc}</option>- <option ${localSort.icon === "1" ? "selected" : ""} value="1">${window.siyuan.languages.sortByUpdateTimeAsc}</option>- <option ${localSort.icon === "2" ? "selected" : ""} value="2">${window.siyuan.languages.sortByDownloadsDesc}</option>- <option ${localSort.icon === "3" ? "selected" : ""} value="3">${window.siyuan.languages.sortByDownloadsAsc}</option>- <option ${localSort.icon === "4" ? "selected" : ""} value="4">${window.siyuan.languages.sortByRatingDesc}</option>- <option ${localSort.icon === "5" ? "selected" : ""} value="5">${window.siyuan.languages.sortByRatingAsc}</option>- </select>- <div class="fn__space"></div>- <div class="fn__flex config-bazaar__filter-row">- <input class="b3-text-field" placeholder="${window.siyuan.languages.enterKey} ${window.siyuan.languages.search}">- <div class="counter counter--bg fn__flex-center ariaLabel" data-position="north" aria-label="${window.siyuan.languages.total}"></div>- </div>- </div>- <div id="configBazaarIcon" class="config-bazaar__content">- ${loadingHTML}- </div>- </div>- <div class="fn__none config-bazaar__panel" data-type="widget">- <div class="fn__flex config-bazaar__title">- <svg class="svg ft__on-surface fn__flex-center"><use xlink:href="#iconSort"></use></svg>- <div class="fn__space"></div>- <select class="b3-select">- <option ${localSort.widget === "0" ? "selected" : ""} value="0">${window.siyuan.languages.sortByUpdateTimeDesc}</option>- <option ${localSort.widget === "1" ? "selected" : ""} value="1">${window.siyuan.languages.sortByUpdateTimeAsc}</option>- <option ${localSort.widget === "2" ? "selected" : ""} value="2">${window.siyuan.languages.sortByDownloadsDesc}</option>- <option ${localSort.widget === "3" ? "selected" : ""} value="3">${window.siyuan.languages.sortByDownloadsAsc}</option>- <option ${localSort.widget === "4" ? "selected" : ""} value="4">${window.siyuan.languages.sortByRatingDesc}</option>- <option ${localSort.widget === "5" ? "selected" : ""} value="5">${window.siyuan.languages.sortByRatingAsc}</option>- </select>- <div class="fn__space"></div>- <div class="fn__flex config-bazaar__filter-row">- <input class="b3-text-field" placeholder="${window.siyuan.languages.enterKey} ${window.siyuan.languages.search}">- <div class="counter counter--bg fn__flex-center ariaLabel" data-position="north" aria-label="${window.siyuan.languages.total}"></div>- </div>- </div>- <div id="configBazaarWidget" class="config-bazaar__content">- ${loadingHTML}- </div>- </div>+ ${genBazaarPackagePanelHTML("themes", localSort.theme, loadingHTML)}+ ${genBazaarPackagePanelHTML("templates", localSort.template, loadingHTML)}+ ${genBazaarPackagePanelHTML("plugins", localSort.plugin, loadingHTML)}+ ${genBazaarPackagePanelHTML("icons", localSort.icon, loadingHTML)}+ ${genBazaarPackagePanelHTML("widgets", localSort.widget, loadingHTML)}</div></div><div id="configBazaarReadme" class="config-bazaar__readme config__view"></div>@@ -610,162 +506,34 @@ ${primaryAction ? '<div class="fn__hr"></div>' : ""}<button class="b3-button b3-button--remove fn__block" data-type="uninstall">${window.siyuan.languages.uninstall}</button>`;},_getRatingKey(bazaarType: TBazaarType, packageName: string) {- return `${bazaarType}:${packageName}`;+ return getRatingKey(bazaarType, packageName);},_syncRatingUser() {- const userID = window.siyuan.user ? `${window.siyuan.config.cloudRegion}:${window.siyuan.user.userId}` : "";- if (bazaar._ratingUserID !== userID) {- bazaar._ratingUserID = userID;- bazaar._data.userRatings.clear();- bazaar._data.userRatingKeys.clear();- bazaar._data.userRatingLoadingKeys.clear();- bazaar._data.userRatingSubmitRequestIDs.clear();- bazaar._data.userRatingBatchRequestIDs.clear();- return true;- }- return false;+ return syncRatingUser(this);},_refreshVisibleRatingUI() {- const keys = new Set<string>();- bazaar.element?.querySelectorAll<HTMLElement>("[data-package-type][data-name]").forEach((element) => {- const bazaarType = element.dataset.packageType as TBazaarType;- const packageName = element.dataset.name;- if (bazaarType && packageName) {- keys.add(bazaar._getRatingKey(bazaarType, packageName));- }- });- keys.forEach((key) => {- const separator = key.indexOf(":");- bazaar._refreshRatingUI(key.slice(0, separator) as TBazaarType, key.slice(separator + 1));- });- const sideElement = bazaar.element?.querySelector("#configBazaarReadme.config__view--show .item__side");- const bazaarType = sideElement?.getAttribute("data-package-type") as TBazaarType;- const packageName = sideElement?.getAttribute("data-name");- const from = sideElement?.getAttribute("data-from") as "downloaded" | "updated" | "bazaar";- if (bazaarType && packageName && from) {- bazaar._loadReadmeRating(bazaarType, packageName, from);- }- if (window.siyuan.user) {- if (bazaar._isUpdatePanelActive()) {- bazaar._loadUpdatedRatings();- } else if (bazaar._data.downloadedType) {- bazaar._loadDownloadedUserRatings(bazaar._data.downloadedType, bazaar._data.downloadedDefault);- }- }+ return refreshVisibleRatingUI(this);},_bindRatingUserChange() {- if (bazaar._ratingUserChangeHandler) {- window.removeEventListener("siyuan-login-success", bazaar._ratingUserChangeHandler);- }- const mount = bazaar._captureMount();- bazaar._ratingUserChangeHandler = () => {- if (!bazaar._isMountCurrent(mount)) {- return;- }- bazaar._syncRatingUser();- bazaar._refreshVisibleRatingUI();- };- window.addEventListener("siyuan-login-success", bazaar._ratingUserChangeHandler);+ return bindRatingUserChange(this);},_getRatingSummaryText(rating?: IBazaarRating) {- const normalized = getDisplayableBazaarRating(rating);- if (!normalized) {- return window.siyuan.languages.bazaarNoRatings;- }- return window.siyuan.languages.bazaarRatingSummary- .replace("${average}", normalized.average.toLocaleString(undefined, {- minimumFractionDigits: 1,- maximumFractionDigits: 1,- }))- .replace("${count}", normalized.count.toLocaleString());+ return getRatingSummaryText(rating);},_genRatingStarsHTML(value: number) {- const activePercentage = Math.max(0, Math.min(100, value / 5 * 100));- const inactiveStars = Array.from({length: 5}, () => '<svg class="config-bazaar__rating-star config-bazaar__rating-star--outline"><use xlink:href="#iconStar"></use></svg>').join("");- const activeStars = Array.from({length: 5}, () => '<svg class="config-bazaar__rating-star"><use xlink:href="#iconStar"></use></svg>').join("");- return `<span class="config-bazaar__rating-stars" aria-hidden="true">- ${inactiveStars}- <span class="config-bazaar__rating-stars--active" style="width: ${activePercentage}%">${activeStars}</span>-</span>`;+ return genRatingStarsHTML(value);},_genCardRatingHTML(item: Pick<IBazaarItem, "rating">, loaded = true) {- const rating = getDisplayableBazaarRating(item.rating);- const hidden = !loaded || !rating;- const summary = bazaar._getRatingSummaryText(rating);- const average = rating?.average.toLocaleString(undefined, {- minimumFractionDigits: 1,- maximumFractionDigits: 1,- });- return `<span data-rating-card-slot data-position="north" class="ariaLabel block__icon block__icon--show block__icon--text${hidden ? " fn__none" : ""}" aria-label="${escapeAttr(summary)}">- <svg aria-hidden="true"><use xlink:href="#iconStar"></use></svg>- <span class="fn__space--small"></span>- <span>${escapeHtml(average || "")}</span>-</span>`;+ return genCardRatingHTML(this, item, loaded);},_genRatePackageActionHTML(loaded: boolean, rating?: unknown) {- const userRating = normalizeBazaarUserRating(rating);- const rated = userRating !== undefined && userRating > 0;- const ariaLabel = rated ? window.siyuan.languages.bazaarYourRatingValue.replace("${rating}", userRating.toString()) :- window.siyuan.languages.bazaarRatePackage;- return `<span data-rating-card-slot data-position="north" data-type="rate-package"${rated ? ` data-user-rating="${userRating}"` : ""} class="ariaLabel block__icon block__icon--show${loaded ? "" : " fn__none"}" aria-label="${escapeAttr(ariaLabel)}">- <svg aria-hidden="true"><use xlink:href="#iconStar"></use></svg>-</span>`;+ return genRatePackageActionHTML(loaded, rating);},_genRatingDistributionHTML(rating?: IBazaarRating) {- const normalized = getDisplayableBazaarRating(rating);- return [5, 4, 3, 2, 1].map((star) => {- const count = normalized?.distribution[star - 1] || 0;- const ratio = normalized ? Math.min(1, count / normalized.count) : 0;- const percentage = ratio * 100;- const percentageText = new Intl.NumberFormat(undefined, {- style: "percent",- maximumFractionDigits: 0,- }).format(ratio);- const label = window.siyuan.languages.bazaarRatingDistributionLabel- .replace("${star}", star.toString())- .replace("${count}", count.toLocaleString());- return `<div class="config-bazaar__rating-row" aria-label="${escapeAttr(`${label} ${percentageText}`)}">- <span>${star}</span>- <svg class="config-bazaar__rating-star" aria-hidden="true"><use xlink:href="#iconStar"></use></svg>- <span class="config-bazaar__rating-track" aria-hidden="true"><span style="width: ${percentage}%"></span></span>- <span>${escapeHtml(percentageText)}</span>- <span>${count.toLocaleString()}</span>-</div>`;- }).join("");+ return genRatingDistributionHTML(rating);},_genReadmeRatingHTML(bazaarType: TBazaarType, item: IBazaarItem, loaded: boolean) {- if (!loaded) {- return "";- }- bazaar._syncRatingUser();- const rating = getDisplayableBazaarRating(item.rating);- const userRating = bazaar._data.userRatings.get(bazaar._getRatingKey(bazaarType, item.name)) || 0;- let action = "";- if (item.installed) {- if (window.siyuan.user) {- const actionText = userRating ? window.siyuan.languages.bazaarYourRatingValue.replace("${rating}", userRating.toString()) :- window.siyuan.languages.bazaarRatePackage;- action = `<button type="button" class="config-bazaar__rating-action" data-type="rate-package" aria-label="${escapeAttr(actionText)}">- ${bazaar._genRatingStarsHTML(userRating)}- <span>${escapeHtml(actionText)}</span>-</button>`;- } else {- action = `<div class="config-bazaar__rating-tip">${window.siyuan.languages.bazaarRatingLoginTip}</div>`;- }- } else {- action = `<div class="config-bazaar__rating-tip">${window.siyuan.languages.bazaarRatingInstallTip}</div>`;- }- const summary = rating ? bazaar._getRatingSummaryText(rating) : "";- const aggregate = rating ? `<div class="config-bazaar__rating-summary" aria-label="${escapeAttr(summary)}">- ${bazaar._genRatingStarsHTML(rating.average)}- <span>${escapeHtml(summary)}</span>- </div>- <div class="config-bazaar__rating-distribution">${bazaar._genRatingDistributionHTML(rating)}</div>` : "";- return `<section class="item__meta-section config-bazaar__rating-detail">- <div class="item__meta-title">${window.siyuan.languages.bazaarRating}</div>- ${aggregate}- ${action}-</section>`;+ return genReadmeRatingHTML(this, bazaarType, item, loaded);},_genCardHTML(item: IBazaarItem, bazaarType: TBazaarType) {const showSwitch = item.installed && !item.current && ["icons", "themes"].includes(bazaarType);@@ -878,7 +646,7 @@ ${primaryAction ? '<div class="fn__hr"></div>' : ""}},_getUpdatedItems(): Array<{type: TBazaarType, item: IUpdatedBazaarItem}> {const items: Array<{type: TBazaarType, item: IUpdatedBazaarItem}> = [];- (["plugins", "themes", "icons", "templates", "widgets"] as TBazaarType[]).forEach((type) => {+ BAZAAR_PACKAGE_TYPES.forEach((type) => {bazaar._data.update[type].forEach((item) => items.push({type, item}));});return items;@@ -1007,17 +775,11 @@ ${primaryAction ? '<div class="fn__hr"></div>' : ""}bazaar._data.deprecationTypesLoading.has(bazaarType)) {return;}- const bazaarAPI: Record<TBazaarType, string> = {- plugins: "/api/bazaar/getBazaarPlugin",- themes: "/api/bazaar/getBazaarTheme",- icons: "/api/bazaar/getBazaarIcon",- templates: "/api/bazaar/getBazaarTemplate",- widgets: "/api/bazaar/getBazaarWidget",- };const mount = bazaar._captureMount();bazaar._data.deprecationTypesLoading.add(bazaarType);- const requestData = ["plugins", "themes"].includes(bazaarType) ? {frontend: getFrontend()} : {};- fetchPost(bazaarAPI[bazaarType], requestData, response => {+ const config = BAZAAR_PACKAGE_CONFIG[bazaarType];+ const requestData = config.bazaarRequestUsesFrontend ? {frontend: getFrontend()} : {};+ fetchPost(config.api.bazaar, requestData, response => {bazaar._data.deprecationTypesLoading.delete(bazaarType);if (!bazaar._isMountCurrent(mount) || response.code !== 0 || !Array.isArray(response.data?.packages)) {return;@@ -1030,14 +792,15 @@ ${primaryAction ? '<div class="fn__hr"></div>' : ""}const activeBtn = contentElement?.previousElementSibling?.querySelector('.b3-button[data-type^="my"]:not(.b3-button--outline)') as HTMLElement;- if (activeBtn?.getAttribute("data-type") === bazaar._type2myType(bazaarType)) {+ if (activeBtn?.getAttribute("data-type") === config.myType) {bazaar._genMyHTML(bazaarType, app, true);}});},_genMyHTML(bazaarType: TBazaarType, app: App, preserveOrder = false) {const contentElement = bazaar.element.querySelector("#configBazaarDownloaded");- const myType = bazaar._type2myType(bazaarType);+ const config = BAZAAR_PACKAGE_CONFIG[bazaarType];+ const myType = config.myType;const typeBtn = contentElement.previousElementSibling.querySelector(`[data-type="${myType}"]`) as HTMLElement;if (contentElement.getAttribute("data-loading") === "true" ||typeBtn?.classList.contains("b3-button--outline")) {@@ -1049,21 +812,10 @@ ${primaryAction ? '<div class="fn__hr"></div>' : ""}}bazaar._updateDownloadedToolbar(bazaarType);contentElement.setAttribute("data-loading", "true");- const installedAPI: Record<TBazaarType, string> = {- plugins: "/api/bazaar/getInstalledPlugin",- themes: "/api/bazaar/getInstalledTheme",- icons: "/api/bazaar/getInstalledIcon",- templates: "/api/bazaar/getInstalledTemplate",- widgets: "/api/bazaar/getInstalledWidget",- };- if (!(bazaarType in installedAPI)) {- contentElement.removeAttribute("data-loading");- return false;- }bazaar._updateDownloadedSortSelect(bazaarType);const initialSortValue = bazaar._getDownloadedSortValue(bazaarType);const mount = bazaar._captureMount();- fetchPost(installedAPI[bazaarType], {+ fetchPost(config.api.installed, {frontend: getFrontend(),keyword: (contentElement.previousElementSibling.querySelector(".b3-text-field") as HTMLInputElement)?.value || "",}, response => {@@ -1094,12 +846,9 @@ ${primaryAction ? '<div class="fn__hr"></div>' : ""}}const showSwitch = ["icons", "themes"].includes(bazaarType) && !bazaarItem.current;const showDisable = ["icons", "themes"].includes(bazaarType) && bazaarItem.current;- let hasSetting = false;- if (bazaarType === "plugins") {- const plugin = app.plugins.find((p: Plugin) => p.name === bazaarItem.name);- // @ts-ignore- hasSetting = plugin && (plugin.setting || plugin.__proto__.hasOwnProperty("openSetting"));- }+ const plugin = bazaarType === "plugins" ?+ app.plugins.find((item: Plugin) => item.name === bazaarItem.name) : undefined;+ const hasSetting = plugin ? hasPluginSetting(plugin) : false;const showPublishSwitch = bazaarType === "plugins" && window.siyuan.config.publish.enable;const publishEnabled = isBazaarPluginEnabledInPublish(bazaarItem);const publishSwitchHTML = showPublishSwitch ? `<label data-type="plugin-publish-enable-label" class="config-bazaar__publish-switch" title="${escapeAttr(bazaarItem.disabledInPublish ? window.siyuan.languages.pluginDisabledInPublishTip : window.siyuan.languages.publishService)}">@@ -1236,16 +985,7 @@ type="checkbox">_renderReadme(bazaarType: TBazaarType, from: "downloaded" | "updated" | "bazaar", data: IBazaarItem, detail?: IBazaarPackageDetail) {const mount = bazaar._captureMount();const readmeElement = bazaar.element.querySelector("#configBazaarReadme") as HTMLElement;- const navTitles: Record<TBazaarType, string> = {- plugins: window.siyuan.languages.plugin,- themes: window.siyuan.languages.theme,- icons: window.siyuan.languages.icon,- templates: window.siyuan.languages.template,- widgets: window.siyuan.languages.widget,- };- if (!(bazaarType in navTitles)) {- return;- }+ const navTitle = window.siyuan.languages[BAZAAR_PACKAGE_CONFIG[bazaarType].languageKey];bazaar._upsertReadmeData(bazaarType, from, data);const updatedDetail = from === "updated" ? bazaar._getUpdatedItem(bazaarType, data.name) : undefined;const installed = detail?.installed || updatedDetail?.installed || (from === "downloaded" ? data : undefined);@@ -1329,7 +1069,7 @@ type="checkbox"></section>`;const backHeaderHTML = `<div class="item__header fn__pointer" data-type="goBack"><svg class="b3-list-item__graphic"><use xlink:href="#iconLeft"></use></svg>- <span class="b3-list-item__text ft__breakword">${navTitles[bazaarType]}</span>+ <span class="b3-list-item__text ft__breakword">${navTitle}</span></div>`;const readmeActionsHTML = `<div class="item__actions${isMobile() ? " item__actions--mobile" : ""}" data-from="${from}" data-name="${escapeAttr(displayData.name)}" data-package-type="${bazaarType}">${bazaar._genReadmeActionsHTML(bazaarType, installed, available)}@@ -1445,22 +1185,8 @@ type="checkbox">});}},- _myType2Type(myType: string) {- return myType.replace("my", "").toLowerCase() + "s" as TBazaarType;- },- _type2tabType(type: TBazaarType) {- return type.slice(0, -1);- },- _type2myType(type: TBazaarType) {- const tab = bazaar._type2tabType(type);- return "my" + tab.charAt(0).toUpperCase() + tab.slice(1);- },- _getDownloadedSortStorageKey(type: TBazaarType) {- const tab = bazaar._type2tabType(type);- return "downloaded" + tab.charAt(0).toUpperCase() + tab.slice(1);- },_getDownloadedSortValue(type: TBazaarType) {- const value = window.siyuan.storage[Constants.LOCAL_BAZAAR][bazaar._getDownloadedSortStorageKey(type)] || "0";+ const value = window.siyuan.storage[Constants.LOCAL_BAZAAR][BAZAAR_PACKAGE_CONFIG[type].downloadedSortKey] || "0";if (type !== "plugins" && ["5", "6"].includes(value)) {return "0";}@@ -1562,506 +1288,40 @@ type="checkbox">bazaar._data.downloaded = packages;},_applyPackageRating(bazaarType: TBazaarType, packageName: string, rating?: IBazaarRating, refreshUI = true) {- const key = bazaar._getRatingKey(bazaarType, packageName);- if (rating) {- bazaar._data.ratings.set(key, rating);- } else {- bazaar._data.ratings.delete(key);- }- const updateItem = (item?: IBazaarItem) => {- applyBazaarPackageRatingToItem(item, packageName, rating);- };- bazaar._data[bazaarType].forEach(updateItem);- if (bazaar._data.downloadedType === bazaarType) {- bazaar._data.downloadedDefault.forEach(updateItem);- bazaar._data.downloaded.forEach(updateItem);- }- bazaar._data.update[bazaarType].forEach((item) => {- updateItem(item.installed);- updateItem(item.available);- });- const detail = bazaar._getPackageDetail(bazaarType, packageName);- updateItem(detail?.installed);- updateItem(detail?.available);- if (refreshUI) {- bazaar._refreshRatingUI(bazaarType, packageName);- }+ return applyPackageRating(this, bazaarType, packageName, rating, refreshUI);},_applyPackageRatingResponse(bazaarType: TBazaarType, packageName: string, data: {ratingAvailable?: unknown;rating?: Partial<IBazaarRating> | null;}, refreshUI = true) {- const key = bazaar._getRatingKey(bazaarType, packageName);- const publicRating = normalizeBazaarPackageRatingResponse(data);- if (publicRating.loaded) {- bazaar._data.downloadedRatingKeys.add(key);- bazaar._applyPackageRating(bazaarType, packageName, publicRating.rating, refreshUI);- } else {- bazaar._data.downloadedRatingKeys.delete(key);- if (refreshUI) {- bazaar._refreshRatingUI(bazaarType, packageName);- }- }- return publicRating.loaded;+ return applyPackageRatingResponse(this, bazaarType, packageName, data, refreshUI);},_getRatingItem(bazaarType: TBazaarType, packageName: string, from: "downloaded" | "updated" | "bazaar") {- const detail = bazaar._getPackageDetail(bazaarType, packageName);- if (from === "downloaded") {- return detail?.installed || (bazaar._data.downloadedType === bazaarType ?- bazaar._data.downloaded.find((item) => item.name === packageName) : undefined);- }- if (from === "updated") {- return detail?.available || bazaar._getUpdatedItem(bazaarType, packageName)?.available;- }- return detail?.available || bazaar._data[bazaarType].find((item) => item.name === packageName);+ return getRatingItem(this, bazaarType, packageName, from);},_refreshRatingUI(bazaarType: TBazaarType, packageName: string) {- bazaar._syncRatingUser();- bazaar.element?.querySelectorAll(`.b3-card[data-package-type="${bazaarType}"]`).forEach((card) => {- if (card.getAttribute("data-name") !== packageName) {- return;- }- const source = card.getAttribute("data-package-source") as "downloaded" | "updated" | "bazaar";- const item = bazaar._getRatingItem(bazaarType, packageName, source);- const slot = card.querySelector<HTMLElement>("[data-rating-card-slot]");- if (item && slot) {- const key = bazaar._getRatingKey(bazaarType, packageName);- const loaded = isBazaarPackageRatingLoaded(source, bazaar._data.downloadedRatingKeys.has(key),- item.ratingAvailable);- if (source === "bazaar") {- const rating = loaded ? getDisplayableBazaarRating(item.rating) : undefined;- slot.classList.toggle("fn__none", !rating);- if (rating) {- slot.setAttribute("aria-label", bazaar._getRatingSummaryText(rating));- const averageElement = slot.lastElementChild;- if (averageElement) {- averageElement.textContent = rating.average.toLocaleString(undefined, {- minimumFractionDigits: 1,- maximumFractionDigits: 1,- });- }- }- } else {- slot.classList.toggle("fn__none", !loaded);- const userRating = bazaar._data.userRatingKeys.has(key) ?- normalizeBazaarUserRating(bazaar._data.userRatings.get(key)) : undefined;- if (userRating !== undefined && userRating > 0) {- slot.dataset.userRating = userRating.toString();- slot.setAttribute("aria-label", window.siyuan.languages.bazaarYourRatingValue- .replace("${rating}", userRating.toString()));- } else {- slot.removeAttribute("data-user-rating");- slot.setAttribute("aria-label", window.siyuan.languages.bazaarRatePackage);- }- }- }- });- const sideElement = bazaar.element?.querySelector("#configBazaarReadme.config__view--show .item__side");- if (sideElement?.getAttribute("data-package-type") !== bazaarType ||- sideElement.getAttribute("data-name") !== packageName) {- return;- }- const from = sideElement.getAttribute("data-from") as "downloaded" | "updated" | "bazaar";- const item = bazaar._getRatingItem(bazaarType, packageName, from);- const slot = sideElement.querySelector('[data-type="rating-detail-slot"]');- if (item && slot) {- const key = bazaar._getRatingKey(bazaarType, packageName);- const loaded = isBazaarPackageRatingLoaded(from, bazaar._data.downloadedRatingKeys.has(key),- item.ratingAvailable);- const displayItem = from === "bazaar" ? item : {...item, rating: bazaar._data.ratings.get(key)};- slot.innerHTML = bazaar._genReadmeRatingHTML(bazaarType, displayItem, loaded);- }+ return refreshRatingUI(this, bazaarType, packageName);},_loadDownloadedRatings(bazaarType: TBazaarType, packages: IBazaarItem[]) {- const packageNames = packages.filter((item) => !item.invalidReason).map((item) => item.name);- if (packageNames.length === 0) {- return;- }- const requestID = (bazaar._data.ratingBatchRequestIDs.get(bazaarType) || 0) + 1;- bazaar._data.ratingBatchRequestIDs.set(bazaarType, requestID);- const mutationVersions = new Map(packageNames.map((packageName) => {- const key = bazaar._getRatingKey(bazaarType, packageName);- return [packageName, getBazaarRatingMutationVersion(bazaar._data.ratingMutationVersions, key)];- }));- const mount = bazaar._captureMount();- fetchPost("/api/bazaar/getBazaarPackageRatings", {- packageType: bazaarType,- packageNames,- }, response => {- if (response.code !== 0 || bazaar._data.ratingBatchRequestIDs.get(bazaarType) !== requestID ||- !bazaar._isMountCurrent(mount) || !bazaar.element?.isConnected) {- return;- }- const ratings = normalizeBazaarPackageRatingsResponse(packageNames, response.data);- if (!ratings) {- return;- }- ratings.forEach((ratingResponse, packageName) => {- const key = bazaar._getRatingKey(bazaarType, packageName);- if (isBazaarRatingMutationVersionCurrent(bazaar._data.ratingMutationVersions, key,- mutationVersions.get(packageName) || 0)) {- bazaar._applyPackageRatingResponse(bazaarType, packageName, ratingResponse);- }- });- });+ return loadDownloadedRatings(this, bazaarType, packages);},_loadDownloadedUserRatings(bazaarType: TBazaarType, packages: IBazaarItem[]) {- bazaar._syncRatingUser();- if (!window.siyuan.user) {- return;- }- const requestedUserID = bazaar._ratingUserID;- const packageNames = Array.from(new Set(packages.filter((item) => !item.invalidReason).map((item) => item.name)))- .filter((packageName) => {- const key = bazaar._getRatingKey(bazaarType, packageName);- return !bazaar._data.userRatingKeys.has(key) &&- !bazaar._data.userRatingLoadingKeys.has(`${requestedUserID}|${key}`);- });- if (packageNames.length === 0) {- return;- }- const requestKey = `${requestedUserID}|${bazaarType}|${JSON.stringify(packageNames)}`;- const requestID = (bazaar._data.userRatingBatchRequestIDs.get(requestKey) || 0) + 1;- bazaar._data.userRatingBatchRequestIDs.set(requestKey, requestID);- const loadingKeys = packageNames.map((packageName) => {- const loadingKey = `${requestedUserID}|${bazaar._getRatingKey(bazaarType, packageName)}`;- bazaar._data.userRatingLoadingKeys.add(loadingKey);- return loadingKey;- });- const mutationVersions = new Map(packageNames.map((packageName) => {- const key = bazaar._getRatingKey(bazaarType, packageName);- return [packageName, getBazaarRatingMutationVersion(bazaar._data.ratingMutationVersions, key)];- }));- const mount = bazaar._captureMount();- fetchPost("/api/bazaar/getBazaarPackageUserRatings", {- packageType: bazaarType,- packageNames,- }, response => {- bazaar._syncRatingUser();- if (response.code !== 0 || requestedUserID !== bazaar._ratingUserID ||- bazaar._data.userRatingBatchRequestIDs.get(requestKey) !== requestID ||- !bazaar._isMountCurrent(mount) || !bazaar.element?.isConnected) {- return;- }- const userRatings = normalizeBazaarPackageUserRatingsResponse(packageNames, response.data);- if (!userRatings) {- return;- }- userRatings.forEach((userRating, packageName) => {- const key = bazaar._getRatingKey(bazaarType, packageName);- if (isBazaarRatingMutationVersionCurrent(bazaar._data.ratingMutationVersions, key,- mutationVersions.get(packageName) || 0)) {- bazaar._data.userRatings.set(key, userRating);- bazaar._data.userRatingKeys.add(key);- bazaar._refreshRatingUI(bazaarType, packageName);- }- });- }).finally(() => {- loadingKeys.forEach((loadingKey) => bazaar._data.userRatingLoadingKeys.delete(loadingKey));- if (bazaar._data.userRatingBatchRequestIDs.get(requestKey) === requestID) {- bazaar._data.userRatingBatchRequestIDs.delete(requestKey);- }- });+ return loadDownloadedUserRatings(this, bazaarType, packages);},_loadUpdatedRatings() {- (["plugins", "themes", "icons", "templates", "widgets"] as TBazaarType[]).forEach((bazaarType) => {- const items = bazaar._data.update[bazaarType];- const installed = items.map((item) => item.installed);- if (items.length && !items.every((item) => bazaar._data.downloadedRatingKeys.has(- bazaar._getRatingKey(bazaarType, item.installed.name)))) {- bazaar._loadDownloadedRatings(bazaarType, installed);- }- if (items.length && window.siyuan.user) {- bazaar._loadDownloadedUserRatings(bazaarType, installed);- }- });+ return loadUpdatedRatings(this);},_fetchPackageRating(bazaarType: TBazaarType, packageName: string, callback?: () => void, silent = true) {- bazaar._syncRatingUser();- const requestedUserID = bazaar._ratingUserID;- const key = bazaar._getRatingKey(bazaarType, packageName);- const loadingKey = `${requestedUserID}|${key}`;- bazaar._data.userRatingLoadingKeys.add(loadingKey);- const mount = bazaar._captureMount();- let handled = false;- fetchPost("/api/bazaar/getBazaarPackageRating", {- packageType: bazaarType,- packageName,- }, response => {- handled = true;- bazaar._syncRatingUser();- if (requestedUserID !== bazaar._ratingUserID || !bazaar._isMountCurrent(mount)) {- return;- }- if (response.code !== 0 || !response.data) {- if (!silent) {- const languageKey = getBazaarRatingErrorLanguageKey(response.data);- showMessage(languageKey ? window.siyuan.languages[languageKey] :- response.msg || window.siyuan.languages.bazaarRatingFailed);- }- return;- }- const userRating = response.data.userRating;- bazaar._data.userRatings.set(key, normalizeBazaarUserRating(userRating) || 0);- bazaar._data.userRatingKeys.add(key);- if (!bazaar._applyPackageRatingResponse(bazaarType, packageName, response.data)) {- if (!silent) {- showMessage(window.siyuan.languages.bazaarRatingFailed);- }- return;- }- callback?.();- }).finally(() => {- bazaar._data.userRatingLoadingKeys.delete(loadingKey);- if (!handled && !silent && requestedUserID === bazaar._ratingUserID) {- showMessage(window.siyuan.languages.bazaarRatingFailed);- }- });+ return fetchPackageRating(this, bazaarType, packageName, callback, silent);},_loadReadmeRating(bazaarType: TBazaarType, packageName: string, from: "downloaded" | "updated" | "bazaar") {- bazaar._syncRatingUser();- const key = bazaar._getRatingKey(bazaarType, packageName);- const loadingKey = `${bazaar._ratingUserID}|${key}`;- if (bazaar._getRatingItem(bazaarType, packageName, from)?.installed && window.siyuan.user &&- !bazaar._data.userRatingKeys.has(key) &&- !bazaar._data.userRatingLoadingKeys.has(loadingKey)) {- bazaar._fetchPackageRating(bazaarType, packageName);- }+ return loadReadmeRating(this, bazaarType, packageName, from);},_submitPackageRating(bazaarType: TBazaarType, packageName: string, rating: number, callback: (success: boolean) => void) {- bazaar._syncRatingUser();- const mount = bazaar._captureMount();- const removing = rating === 0;- const failureMessage = removing ? window.siyuan.languages.bazaarRemoveRatingFailed :- window.siyuan.languages.bazaarRatingFailed;- if (normalizeBazaarUserRating(rating) === undefined) {- showMessage(failureMessage);- callback(false);- return;- }- const requestedUserID = bazaar._ratingUserID;- const key = bazaar._getRatingKey(bazaarType, packageName);- const requestKey = `${requestedUserID}|${key}`;- if (!beginBazaarRatingSubmission(bazaar._data.userRatingSubmittingKeys, requestKey)) {- showMessage(window.siyuan.languages.loading);- callback(false);- return;- }- const requestID = beginBazaarRatingRequest(bazaar._data.userRatingSubmitRequestIDs, requestKey);- let handled = false;- let settled = false;- const isLatestRequest = () => requestedUserID === bazaar._ratingUserID &&- isLatestBazaarRatingRequest(bazaar._data.userRatingSubmitRequestIDs, requestKey, requestID);- const settle = (success: boolean) => {- if (!settled) {- settled = true;- callback(success);- }- };- fetchPost("/api/bazaar/setBazaarPackageRating", {- packageType: bazaarType,- packageName,- rating,- }, response => {- handled = true;- bazaar._syncRatingUser();- if (!isLatestRequest()) {- settle(false);- return;- }- if (response.code !== 0 || !response.data) {- const languageKey = getBazaarRatingErrorLanguageKey(response.data);- showMessage(languageKey ? window.siyuan.languages[languageKey] :- response.msg || failureMessage);- settle(false);- return;- }- const userRating = response.data.userRating;- bazaar._data.userRatings.set(key, normalizeBazaarUserRating(userRating) ?? rating);- bazaar._data.userRatingKeys.add(key);- beginBazaarRatingRequest(bazaar._data.ratingMutationVersions, key);- const refreshUI = bazaar._isMountCurrent(mount);- bazaar._applyPackageRatingResponse(bazaarType, packageName, response.data, refreshUI);- const sortValue = window.siyuan.storage[Constants.LOCAL_BAZAAR][bazaar._type2tabType(bazaarType)];- if (refreshUI && ["4", "5"].includes(sortValue)) {- bazaar._renderBazaarCards(- bazaar.element.querySelector({- plugins: "#configBazaarPlugin",- themes: "#configBazaarTheme",- icons: "#configBazaarIcon",- templates: "#configBazaarTemplate",- widgets: "#configBazaarWidget",- }[bazaarType]),- bazaar._sortPackages(bazaar._data[bazaarType], sortValue),- bazaarType,- bazaarType === "themes" ? (bazaar.element.querySelector("#bazaarSelect") as HTMLSelectElement)?.value : undefined,- );- }- showMessage(removing ? window.siyuan.languages.bazaarRatingRemoved :- window.siyuan.languages.bazaarRatingSubmitted);- settle(true);- }).finally(() => {- bazaar._data.userRatingSubmittingKeys.delete(requestKey);- if (settled) {- return;- }- bazaar._syncRatingUser();- if (!handled && isLatestRequest()) {- showMessage(failureMessage);- }- settle(false);- });+ return submitPackageRating(this, bazaarType, packageName, rating, callback);},_openRatingDialog(bazaarType: TBazaarType, packageName: string) {- bazaar._syncRatingUser();- if (!window.siyuan.user) {- showMessage(window.siyuan.languages.bazaarRatingLoginTip);- return;- }- const key = bazaar._getRatingKey(bazaarType, packageName);- const submitKey = `${bazaar._ratingUserID}|${key}`;- if (bazaar._data.userRatingSubmittingKeys.has(submitKey)) {- showMessage(window.siyuan.languages.loading);- return;- }- if (!bazaar._data.userRatingKeys.has(key)) {- const loadingKey = `${bazaar._ratingUserID}|${key}`;- if (bazaar._data.userRatingLoadingKeys.has(loadingKey)) {- showMessage(window.siyuan.languages.loading);- return;- }- bazaar._fetchPackageRating(bazaarType, packageName, () => {- bazaar._openRatingDialog(bazaarType, packageName);- }, false);- return;- }- const previousActiveElement = document.activeElement as HTMLElement;- let selectedRating = bazaar._data.userRatings.get(key) || 0;- const canRemoveRating = isBazaarRatingRemovalAvailable(selectedRating);- const buttons = [1, 2, 3, 4, 5].map((rating) => {- const label = window.siyuan.languages.bazaarRatingStarLabel.replace("${star}", rating.toString());- return `<button type="button" role="radio" data-rating-value="${rating}" aria-checked="${selectedRating === rating}" aria-label="${escapeAttr(label)}" tabindex="${selectedRating === rating || (!selectedRating && rating === 1) ? "0" : "-1"}">- <svg class="config-bazaar__rating-star config-bazaar__rating-star--outline" aria-hidden="true"><use xlink:href="#iconStar"></use></svg>-</button>`;- }).join("");- const dialog = new Dialog({- title: window.siyuan.languages.bazaarRatePackage,- content: `<div class="b3-dialog__content">- <div class="config-bazaar__rating-picker" role="radiogroup" aria-label="${escapeAttr(window.siyuan.languages.bazaarYourRating)}">${buttons}</div>-</div>-<div class="b3-dialog__action">- ${canRemoveRating ? `<button type="button" class="b3-button b3-button--remove" data-type="rating-remove">${window.siyuan.languages.bazaarRemoveRating}</button><div class="fn__space"></div>` : ""}- <button type="button" class="b3-button b3-button--cancel" data-type="rating-cancel">${window.siyuan.languages.cancel}</button>- <div class="fn__space"></div>- <button type="button" class="b3-button b3-button--text" data-type="rating-confirm"${selectedRating ? "" : " disabled"}>${window.siyuan.languages.confirm}</button>-</div>`,- width: isMobile() ? "92vw" : "360px",- destroyCallback: () => {- if (previousActiveElement?.isConnected) {- previousActiveElement.focus({preventScroll: true});- }- },- });- const picker = dialog.element.querySelector(".config-bazaar__rating-picker") as HTMLElement;- const cancelButton = dialog.element.querySelector('[data-type="rating-cancel"]') as HTMLButtonElement;- const confirmButton = dialog.element.querySelector('[data-type="rating-confirm"]') as HTMLButtonElement;- const removeButton = dialog.element.querySelector('[data-type="rating-remove"]') as HTMLButtonElement | null;- let submitting = false;- const setSubmitting = (value: boolean) => {- submitting = value;- picker.querySelectorAll<HTMLButtonElement>("[data-rating-value]").forEach((button) => {- button.disabled = value;- });- if (removeButton) {- removeButton.disabled = value;- }- cancelButton.disabled = value;- confirmButton.disabled = value || !selectedRating;- };- const highlightRating = (rating: number) => {- picker.querySelectorAll<HTMLButtonElement>("[data-rating-value]").forEach((button) => {- button.classList.toggle("config-bazaar__rating-picker--active", Number(button.dataset.ratingValue) <= rating);- });- };- const selectRating = (rating: number, focus = false) => {- if (submitting) {- return;- }- selectedRating = rating;- highlightRating(rating);- picker.querySelectorAll<HTMLButtonElement>("[data-rating-value]").forEach((button) => {- const value = Number(button.dataset.ratingValue);- button.setAttribute("aria-checked", (value === rating).toString());- button.tabIndex = value === rating ? 0 : -1;- if (focus && value === rating) {- button.focus();- }- });- confirmButton.disabled = false;- };- if (selectedRating) {- selectRating(selectedRating);- }- picker.addEventListener("click", (event) => {- const button = (event.target as HTMLElement).closest<HTMLButtonElement>("[data-rating-value]");- if (button) {- selectRating(Number(button.dataset.ratingValue));- }- });- picker.addEventListener("mouseover", (event) => {- const button = (event.target as HTMLElement).closest<HTMLButtonElement>("[data-rating-value]");- if (button) {- highlightRating(Number(button.dataset.ratingValue));- }- });- picker.addEventListener("mouseleave", () => highlightRating(selectedRating));- picker.addEventListener("keydown", (event: KeyboardEvent) => {- if (!["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Home", "End"].includes(event.key)) {- return;- }- let next = selectedRating || Number((event.target as HTMLElement).closest<HTMLElement>("[data-rating-value]")?.dataset.ratingValue) || 1;- if (["ArrowLeft", "ArrowUp"].includes(event.key)) {- next = next === 1 ? 5 : next - 1;- } else if (["ArrowRight", "ArrowDown"].includes(event.key)) {- next = next === 5 ? 1 : next + 1;- } else {- next = event.key === "Home" ? 1 : 5;- }- selectRating(next, true);- event.preventDefault();- });- cancelButton.addEventListener("click", () => {- if (!submitting) {- dialog.destroy();- }- });- removeButton?.addEventListener("click", () => {- if (submitting) {- return;- }- setSubmitting(true);- bazaar._submitPackageRating(bazaarType, packageName, 0, (success) => {- if (success) {- dialog.destroy();- } else {- setSubmitting(false);- }- });- });- confirmButton.addEventListener("click", () => {- if (!selectedRating || submitting) {- return;- }- setSubmitting(true);- bazaar._submitPackageRating(bazaarType, packageName, selectedRating, (success) => {- if (success) {- dialog.destroy();- } else {- setSubmitting(false);- }- });- });- (picker.querySelector('[tabindex="0"]') as HTMLButtonElement)?.focus({preventScroll: true});+ return openRatingDialog(this, bazaarType, packageName);},_refreshReadmeDetail(bazaarType: TBazaarType, packageName: string) {const sideElement = bazaar.element.querySelector("#configBazaarReadme.config__view--show .item__side");@@ -2087,17 +1347,9 @@ type="checkbox">});},_reloadBazaarType(bazaarType: TBazaarType) {- const bazaarAPI: Record<TBazaarType, string> = {- plugins: "/api/bazaar/getBazaarPlugin",- themes: "/api/bazaar/getBazaarTheme",- icons: "/api/bazaar/getBazaarIcon",- templates: "/api/bazaar/getBazaarTemplate",- widgets: "/api/bazaar/getBazaarWidget",- };+ const config = BAZAAR_PACKAGE_CONFIG[bazaarType];const mount = bazaar._beginBazaarRequest(bazaarType);- fetchPost(bazaarAPI[bazaarType], {- frontend: getFrontend(),- }, response => {+ fetchPost(config.api.bazaar, {frontend: getFrontend()}, response => {if (response.code === 0) {bazaar._onBazaar(response, bazaarType, mount);}@@ -2245,40 +1497,15 @@ type="checkbox">callback();});},- _initBazaarPanel(app: App, bazaarType: TBazaarType, panel: HTMLElement) {+ _initBazaarPanel(bazaarType: TBazaarType, panel: HTMLElement) {if (panel.getAttribute("data-init")) {return;}const mount = bazaar._beginBazaarRequest(bazaarType);- switch (bazaar._type2tabType(bazaarType)) {- case "template":- fetchPost("/api/bazaar/getBazaarTemplate", {}, response => {- bazaar._onBazaar(response, "templates", mount);- });- break;- case "icon":- fetchPost("/api/bazaar/getBazaarIcon", {}, response => {- bazaar._onBazaar(response, "icons", mount);- });- break;- case "widget":- fetchPost("/api/bazaar/getBazaarWidget", {}, response => {- bazaar._onBazaar(response, "widgets", mount);- });- break;- case "theme":- fetchPost("/api/bazaar/getBazaarTheme", {frontend: getFrontend()}, response => {- bazaar._onBazaar(response, "themes", mount);- });- break;- case "plugin":- fetchPost("/api/bazaar/getBazaarPlugin", {- frontend: getFrontend()- }, response => {- bazaar._onBazaar(response, "plugins", mount);- });- break;- }+ const config = BAZAAR_PACKAGE_CONFIG[bazaarType];+ fetchPost(config.api.bazaar, config.bazaarRequestUsesFrontend ? {frontend: getFrontend()} : {}, response => {+ bazaar._onBazaar(response, bazaarType, mount);+ });panel.setAttribute("data-init", "true");},/** 切换集市顶部 Tab */@@ -2286,7 +1513,7 @@ type="checkbox">if (!bazaar.element) {return;}- const layoutTabType = from === "bazaar" ? bazaar._type2tabType(bazaarType) : "downloaded";+ const layoutTabType = from === "bazaar" ? BAZAAR_PACKAGE_CONFIG[bazaarType].tabType : "downloaded";const focusItem = bazaar.element.querySelector(`.layout-tab-bar .item[data-type="${layoutTabType}"]`);const currentFocus = bazaar.element.querySelector(".layout-tab-bar .item--focus");if (focusItem && focusItem !== currentFocus) {@@ -2298,11 +1525,11 @@ type="checkbox">const isActive = panelType === layoutTabType;panel.classList.toggle("fn__none", !isActive);if (isActive && from === "bazaar") {- bazaar._initBazaarPanel(app, bazaarType, panel as HTMLElement);+ bazaar._initBazaarPanel(bazaarType, panel as HTMLElement);}});if (from !== "bazaar") {- const myType = from === "updated" ? "myUpdate" : bazaar._type2myType(bazaarType);+ const myType = from === "updated" ? "myUpdate" : BAZAAR_PACKAGE_CONFIG[bazaarType].myType;const titleBar = bazaar.element.querySelector('.config-bazaar__panel[data-type="downloaded"] .config-bazaar__title');titleBar?.querySelectorAll('.b3-button[data-type^="my"]').forEach((btn) => {btn.classList.toggle("b3-button--outline", btn.getAttribute("data-type") !== myType);@@ -2481,7 +1708,7 @@ type="checkbox">this._syncRatingUser();this._bindRatingUserChange();const mount = this._captureMount();- (["plugins", "themes", "icons", "templates", "widgets"] as TBazaarType[]).forEach((type) => {+ BAZAAR_PACKAGE_TYPES.forEach((type) => {this._data.update[type] = [];});this._downloadedPluginsReady = false;@@ -2507,504 +1734,7 @@ type="checkbox">this._checkUpdate(true);this._setLocalPackageUploading(this._localPackageUploading, mount);this._bindLocalPackageEvent(app, mount);- bazaar.element.firstElementChild.addEventListener("click", (event) => {- if (bazaar._syncRatingUser()) {- bazaar._refreshVisibleRatingUI();- }- let target = event.target as HTMLElement;- const packageElement = hasClosestByAttribute(target, "data-name", null);- let pkgType: TBazaarType | undefined;- let pkgItem: IBazaarItem;- let updatedItem: IUpdatedBazaarItem;- let packageSource: "downloaded" | "updated" | "bazaar";- let packageName: string | undefined;- if (packageElement) {- packageName = packageElement.getAttribute("data-name") || undefined;- pkgType = packageElement.getAttribute("data-package-type") as TBazaarType;- packageSource = (packageElement.getAttribute("data-package-source") ||- packageElement.getAttribute("data-from")) as "downloaded" | "updated" | "bazaar";- if (packageName && pkgType && packageSource === "downloaded") {- pkgItem = bazaar._data.downloaded.find((item) => item.name === packageName);- } else if (packageName && pkgType && packageSource === "updated") {- updatedItem = bazaar._getUpdatedItem(pkgType, packageName);- pkgItem = updatedItem?.available;- } else if (packageName && pkgType && packageSource === "bazaar") {- pkgItem = bazaar._data[pkgType]?.find((item) => item.name === packageName);- }- }- const packageDetail = packageName && pkgType ? bazaar._getPackageDetail(pkgType, packageName) : undefined;- const installedItem = packageDetail?.installed || updatedItem?.installed ||- (packageSource === "downloaded" ? pkgItem : undefined);- const availableItem = packageDetail?.available || updatedItem?.available ||- (packageSource === "bazaar" ? pkgItem : undefined);- while (target && !target.isEqualNode(bazaar.element)) {- const type = target.getAttribute("data-type");- if (target.tagName === "A") {- break;- }- const packageInstalled = Boolean(installedItem) ||- (packageSource === "bazaar" && pkgItem?.installed === true);- if (type === "rate-package" && pkgType && packageName &&- isBazaarPackageRatingEditable(packageSource, packageInstalled)) {- bazaar._openRatingDialog(pkgType, packageName);- event.preventDefault();- event.stopPropagation();- break;- } else if (type === "copy-funding") {- const funding = target.getAttribute("data-funding");- if (funding) {- writeText(funding);- showMessage(window.siyuan.languages.copied);- }- event.preventDefault();- event.stopPropagation();- break;- } else if (type === "keywords-expand") {- target.parentElement?.querySelectorAll("[data-keyword-hidden]").forEach((item) => {- item.classList.remove("fn__none");- });- target.remove();- event.preventDefault();- event.stopPropagation();- break;- } else if (type === "bazaar-alternative") {- const alternativeType = target.getAttribute("data-package-type") as TBazaarType;- const alternativeName = target.getAttribute("data-package-name");- if (alternativeType && alternativeName) {- bazaar._openBazaarAlternative(alternativeType, alternativeName);- }- event.preventDefault();- event.stopPropagation();- break;- } else if (type === "open" && (installedItem || pkgItem) && pkgType) {- const item = installedItem || pkgItem;- /// #if !BROWSER- if (["icons", "themes"].includes(pkgType)) {- useShell("openPath", path.join(window.siyuan.config.system.confDir, "appearance", pkgType, item.name));- } else {- useShell("openPath", path.join(window.siyuan.config.system.dataDir, pkgType, item.name));- }- /// #endif- event.preventDefault();- event.stopPropagation();- break;- } else if (["myTheme", "myTemplate", "myIcon", "myWidget", "myPlugin", "myUpdate"].includes(type)) {- const downloadedLoading = bazaar.element.querySelector("#configBazaarDownloaded")- .getAttribute("data-loading");- if (target.classList.contains("b3-button--outline") &&- (type === "myUpdate" || !downloadedLoading)) {- target.parentElement.querySelectorAll('.b3-button[data-type^="my"]').forEach((item: HTMLElement) => {- item.classList.add("b3-button--outline");- });- target.classList.remove("b3-button--outline");- if (type === "myUpdate") {- bazaar._updateDownloadedToolbar("update");- bazaar._renderUpdatePanel();- bazaar._checkUpdate();- } else {- this._genMyHTML(bazaar._myType2Type(type), app);- }- }- event.preventDefault();- event.stopPropagation();- break;- } else if (type === "retry-update") {- bazaar._checkUpdate(true);- event.preventDefault();- event.stopPropagation();- break;- } else if (type === "goBack") {- bazaar.element.querySelector("#configBazaarReadme").classList.remove("config__view--show");- event.preventDefault();- event.stopPropagation();- break;- } else if (type === "install") {- event.preventDefault();- event.stopPropagation();- const installItem = availableItem || pkgItem;- if (!target.classList.contains("b3-button--progress") && !target.hasAttribute("disabled") && installItem && pkgType) {- const installAPI: Record<TBazaarType, string> = {- plugins: "/api/bazaar/installBazaarPlugin",- themes: "/api/bazaar/installBazaarTheme",- icons: "/api/bazaar/installBazaarIcon",- templates: "/api/bazaar/installBazaarTemplate",- widgets: "/api/bazaar/installBazaarWidget",- };- const themeAppearanceMode = pkgType === "themes" ?- bazaar._resolveThemeAppearanceMode(installItem) : {};- const request = bazaar._beginBazaarRequest(pkgType, mount);- fetchPost(installAPI[pkgType], {- keyword: (mount.element.querySelector(`.config-bazaar__panel[data-type="${bazaar._type2tabType(pkgType)}"] .b3-text-field`) as HTMLInputElement).value,- repoURL: installItem.repoURL,- packageName: installItem.name,- repoHash: installItem.repoHash,- repoRef: installItem.repoRef || "",- ...themeAppearanceMode,- frontend: getFrontend()- }, response => {- bazaar._onBazaar(response, pkgType, request);- if (response.code !== 0) {- if (bazaar._isBazaarRequestCurrent(pkgType, request)) {- bazaar._refreshReadmeDetail(pkgType, installItem.name);- }- return;- }- if (bazaar._isMountCurrent(mount)) {- bazaar._genMyHTML(pkgType, app, false);- bazaar._refreshReadmeDetail(pkgType, installItem.name);- }- if (pkgType === "plugins") {- if (window.siyuan.config.bazaar.petalDisabled) {- confirmDialog(window.siyuan.languages.confirm, window.siyuan.languages.enablePluginTip2);- } else {- confirmDialog("💡 " + window.siyuan.languages.enablePlugin, window.siyuan.languages.enablePluginTip, () => {- bazaar._setPluginEnabled(app, installItem, true, () => {- if (bazaar._isMountCurrent(mount)) {- bazaar._genMyHTML(pkgType, app, false);- bazaar._refreshReadmeDetail(pkgType, installItem.name);- }- });- });- }- }- });- }- break;- } else if (type === "install-all") {- confirmDialog("⬆️ " + window.siyuan.languages.updateAll, window.siyuan.languages.confirmUpdateAll, () => {- fetchPost("/api/bazaar/batchUpdatePackage", {frontend: getFrontend()}, (response) => {- if (response.code !== 0) {- showMessage(response.msg);- return;- }- if (bazaar._isMountCurrent(mount)) {- mount.element.querySelector("#configBazaarReadme")?.classList.remove("config__view--show");- bazaar._checkUpdate(true);- }- });- });- event.preventDefault();- event.stopPropagation();- break;- } else if (type === "feedback") {- event.preventDefault();- event.stopPropagation();- break;- } else if (type === "install-t") {- const packageName = updatedItem?.installed.name || pkgItem?.name;- if (!target.classList.contains("b3-button--progress") && !target.hasAttribute("disabled") && packageName && pkgType) {- confirmDialog("⬆️ " + window.siyuan.languages.update, window.siyuan.languages.confirmUpdate, () => {- if (!target.classList.contains("b3-button")) {- target.parentElement.insertAdjacentHTML("afterend", '<img data-type="img-loading" style="position: absolute;top: 0;left: 0;height: 100%;width: 100%;padding: 16px;box-sizing: border-box;" src="/stage/loading-pure.svg">');- }- const request = bazaar._beginBazaarRequest(pkgType, mount);- fetchPost("/api/bazaar/updateBazaarPackage", {- packageType: pkgType,- packageName,- frontend: getFrontend()- }, response => {- if (response.code !== 0) {- showMessage(response.msg);- target.parentElement.parentElement.querySelector("img[data-type='img-loading']")?.remove();- return;- }- bazaar._onBazaar(response, pkgType, request);- if (bazaar._isMountCurrent(mount)) {- mount.element.querySelector("#configBazaarReadme")?.classList.remove("config__view--show");- this._genMyHTML(pkgType, app);- bazaar._checkUpdate(true);- }- });- });- }- event.preventDefault();- event.stopPropagation();- break;- } else if (type === "uninstall" && installedItem && pkgType) {- event.preventDefault();- event.stopPropagation();- const uninstallAPI: Record<TBazaarType, string> = {- plugins: "/api/bazaar/uninstallBazaarPlugin",- themes: "/api/bazaar/uninstallBazaarTheme",- icons: "/api/bazaar/uninstallBazaarIcon",- templates: "/api/bazaar/uninstallBazaarTemplate",- widgets: "/api/bazaar/uninstallBazaarWidget",- };- const uninstallName = installedItem.name;- const keyword = (mount.element.querySelector(`.config-bazaar__panel[data-type="${bazaar._type2tabType(pkgType)}"] .b3-text-field`) as HTMLInputElement).value;- confirmDialog("⚠️ " + window.siyuan.languages.uninstall, window.siyuan.languages.confirmUninstall.replace("${name}", escapeHtml(uninstallName)), () => {- const request = bazaar._beginBazaarRequest(pkgType, mount);- fetchPost(uninstallAPI[pkgType], {- packageName: uninstallName,- keyword,- frontend: getFrontend()- }, response => {- if (response.code !== 0) {- showMessage(response.msg);- return;- }- bazaar._data.details.delete(bazaar._getDetailKey(pkgType, uninstallName));- bazaar._onBazaar(response, pkgType, request);- if (bazaar._isMountCurrent(mount)) {- mount.element.querySelector("#configBazaarReadme")?.classList.remove("config__view--show");- this._genMyHTML(pkgType, app);- bazaar._checkUpdate(true);- }- });- });- break;- } else if (type === "switch" && (installedItem || pkgItem) && pkgType && ["icons", "themes"].includes(pkgType)) {- event.preventDefault();- event.stopPropagation();- if (target.hasAttribute("disabled")) {- break;- }- const appearanceItem = installedItem || pkgItem;- target.setAttribute("disabled", "disabled");- bazaar._setAppearancePackage(pkgType as "themes" | "icons", appearanceItem, true, () => {- if (bazaar._isMountCurrent(mount)) {- bazaar._refreshPackageUI(pkgType, appearanceItem.name, app);- }- });- break;- } else if (["package-enable", "package-disable"].includes(type) && (installedItem || pkgItem) && pkgType) {- event.preventDefault();- event.stopPropagation();- if (target.hasAttribute("disabled")) {- break;- }- const enabled = type === "package-enable";- const actionItem = installedItem || pkgItem;- target.setAttribute("disabled", "disabled");- if (pkgType === "plugins" && installedItem) {- bazaar._setPluginEnabled(app, installedItem, enabled, () => {- if (bazaar._isMountCurrent(mount)) {- bazaar._refreshPackageUI(pkgType, installedItem.name, app);- }- });- } else if (["icons", "themes"].includes(pkgType)) {- bazaar._setAppearancePackage(pkgType as "themes" | "icons", actionItem, enabled, () => {- if (bazaar._isMountCurrent(mount)) {- bazaar._refreshPackageUI(pkgType, actionItem.name, app);- }- });- }- break;- } else if (type === "setting" && pkgItem) {- if (window.siyuan.config.bazaar.petalDisabled) {- event.preventDefault();- event.stopPropagation();- break;- }- app.plugins.find((item: Plugin) => {- if (item.name === pkgItem.name) {- item.openSetting();- return true;- }- });- event.preventDefault();- event.stopPropagation();- break;- } else if (type === "plugins-enable") {- if (!target.getAttribute("disabled")) {- const requestID = ++this._pluginGlobalRequestID;- this._pluginGlobalRequestPending = true;- this._syncPluginGlobalSwitch();- void setGlobalPluginsDisabled(app, !(target as HTMLInputElement).checked).catch((error) => {- console.error(error);- }).finally(() => {- if (requestID !== this._pluginGlobalRequestID) {- return;- }- this._pluginGlobalRequestPending = false;- this._syncPluginGlobalSwitch();- });- }- event.stopPropagation();- break;- } else if (type === "plugin-publish-enable-label") {- event.stopPropagation();- break;- } else if (type === "plugin-publish-enable" && installedItem) {- if (!target.hasAttribute("disabled")) {- target.setAttribute("disabled", "disabled");- const enabled = (target as HTMLInputElement).checked;- bazaar._setPluginPublishEnabled(installedItem, enabled, () => {- if (bazaar._isMountCurrent(mount)) {- target.removeAttribute("disabled");- this._genMyHTML("plugins", app, true);- }- });- }- event.stopPropagation();- break;- } else if (type === "plugin-enable" && (installedItem || pkgItem)) {- if (!target.hasAttribute("disabled")) {- target.setAttribute("disabled", "disabled");- const enabled = (target as HTMLInputElement).checked;- const pluginItem = installedItem || pkgItem;- bazaar._setPluginEnabled(app, pluginItem, enabled, () => {- if (bazaar._isMountCurrent(mount)) {- target.removeAttribute("disabled");- this._genMyHTML("plugins", app, true);- }- });- }- event.stopPropagation();- break;- } else if (target.classList.contains("b3-card")) {- if (!hasClosestByClassName(event.target as HTMLElement, "b3-card__actions--right") &&- pkgItem && !pkgItem.invalidReason && pkgType) {- bazaar._renderReadme(pkgType, packageSource, pkgItem);- }- event.preventDefault();- event.stopPropagation();- break;- } else if (target.classList.contains("item") && !target.classList.contains("item--focus")) {- // switch tab- bazaar.element.querySelector(".layout-tab-bar .item--focus").classList.remove("item--focus");- target.classList.add("item--focus");- bazaar.element.querySelectorAll(".config-bazaar__panel").forEach(item => {- if (type === item.getAttribute("data-type")) {- item.classList.remove("fn__none");- if (type !== "downloaded") {- bazaar._initBazaarPanel(app, (type + "s") as TBazaarType, item as HTMLElement);- }- } else {- item.classList.add("fn__none");- }- });- event.preventDefault();- event.stopPropagation();- break;- } else if (target.classList.contains("item__preview")) {- if (isMobile()) {- const previewURL = target.dataset.previewUrl;- if (previewURL) {- previewImages([previewURL], previewURL);- }- } else {- target.classList.toggle("item__preview--fullscreen");- }- event.preventDefault();- event.stopPropagation();- break;- }- target = target.parentElement;- }- });-- bazaar.element.querySelectorAll(".config-bazaar__panel .b3-text-field").forEach((inputElement: HTMLInputElement) => {- inputElement.addEventListener("keydown", (event) => {- if (event.isComposing) {- return;- }- if (event.key === "Enter") {- const keyword = inputElement.value.trim();- const type = (hasClosestByClassName(inputElement, "config-bazaar__panel") as HTMLElement).getAttribute("data-type");- if (type === "template") {- const request = bazaar._beginBazaarRequest("templates", mount);- fetchPost("/api/bazaar/getBazaarTemplate", {keyword}, response => {- bazaar._onBazaar(response, "templates", request);- });- } else if (type === "icon") {- const request = bazaar._beginBazaarRequest("icons", mount);- fetchPost("/api/bazaar/getBazaarIcon", {keyword}, response => {- bazaar._onBazaar(response, "icons", request);- });- } else if (type === "widget") {- const request = bazaar._beginBazaarRequest("widgets", mount);- fetchPost("/api/bazaar/getBazaarWidget", {keyword}, response => {- bazaar._onBazaar(response, "widgets", request);- });- } else if (type === "theme") {- const request = bazaar._beginBazaarRequest("themes", mount);- fetchPost("/api/bazaar/getBazaarTheme", {frontend: getFrontend(), keyword}, response => {- bazaar._onBazaar(response, "themes", request);- });- } else if (type === "plugin") {- const request = bazaar._beginBazaarRequest("plugins", mount);- fetchPost("/api/bazaar/getBazaarPlugin", {- frontend: getFrontend(),- keyword- }, response => {- bazaar._onBazaar(response, "plugins", request);- });- } else if (type === "downloaded") {- const activeType = inputElement.closest(".config-bazaar__title")?.querySelector('.b3-button[data-type^="my"]:not(.b3-button--outline)')?.getAttribute("data-type");- if (activeType && activeType !== "myUpdate") {- this._genMyHTML(bazaar._myType2Type(activeType), app);- }- }- event.preventDefault();- return;- }- });- });-- bazaar.element.querySelectorAll(".b3-select").forEach((selectElement: HTMLSelectElement) => {- selectElement.addEventListener("change", () => {- if (selectElement.getAttribute("data-type") === "downloaded-sort") {- const activeBtn = bazaar.element.querySelector("#configBazaarDownloaded")?.previousElementSibling?.querySelector('.b3-button[data-type^="my"]:not(.b3-button--outline)') as HTMLElement;- if (activeBtn?.getAttribute("data-type") === "myUpdate") {- return;- }- const bazaarType = bazaar._myType2Type(activeBtn.getAttribute("data-type"));- window.siyuan.storage[Constants.LOCAL_BAZAAR][bazaar._getDownloadedSortStorageKey(bazaarType)] = selectElement.value;- setStorageVal(Constants.LOCAL_BAZAAR, window.siyuan.storage[Constants.LOCAL_BAZAAR]);- bazaar._reorderDownloadedCards(bazaar._sortDownloadedPackages(bazaar._data.downloadedDefault, selectElement.value));- } else if (selectElement.id === "bazaarSelect") {- bazaar._renderBazaarCards(- bazaar.element.querySelector("#configBazaarTheme"),- bazaar._data.themes,- "themes",- selectElement.value- );- } else {- // sort- const panelElement = selectElement.parentElement.parentElement;- const panelType = panelElement.getAttribute("data-type");- const bazaarType = {- plugin: "plugins",- theme: "themes",- icon: "icons",- template: "templates",- widget: "widgets",- }[panelType] as TBazaarType;- bazaar._renderBazaarCards(- panelElement.querySelector(".config-bazaar__content"),- bazaar._sortPackages(bazaar._data[bazaarType], selectElement.value),- bazaarType,- bazaarType === "themes" ? (bazaar.element.querySelector("#bazaarSelect") as HTMLSelectElement).value : undefined- );- window.siyuan.storage[Constants.LOCAL_BAZAAR][panelType] = selectElement.value;- setStorageVal(Constants.LOCAL_BAZAAR, window.siyuan.storage[Constants.LOCAL_BAZAAR]);- }- });- });- },- _sortPackages(packages: IBazaarItem[], sortValue: string): IBazaarItem[] {- const sorted = [...packages];- // 更新时间降序- if (sortValue === "0") {- return sorted.sort((a, b) => (b.updated < a.updated ? -1 : 1));- }- // 更新时间升序- if (sortValue === "1") {- return sorted.sort((a, b) => (b.updated < a.updated ? 1 : -1));- }- // 下载次数降序- if (sortValue === "2") {- return sorted.sort((a, b) => (b.downloads < a.downloads ? -1 : 1));- }- // 下载次数升序- if (sortValue === "3") {- return sorted.sort((a, b) => (b.downloads < a.downloads ? 1 : -1));- }- if (["4", "5"].includes(sortValue)) {- return sortBazaarPackagesByRating(sorted, sortValue === "4");- }- return sorted;+ bindBazaarEvents(this, app, mount);},_renderBazaarCards(container: Element, packages: IBazaarItem[], bazaarType: TBazaarType, themeModeValue?: string) {const htmlParts: string[] = [];@@ -3025,14 +1755,7 @@ type="checkbox">if (!bazaar._isBazaarRequestCurrent(bazaarType, mount)) {return;}- const panelSelector: Record<TBazaarType, string> = {- plugins: "#configBazaarPlugin",- themes: "#configBazaarTheme",- icons: "#configBazaarIcon",- templates: "#configBazaarTemplate",- widgets: "#configBazaarWidget",- };- const element = bazaar.element.querySelector(panelSelector[bazaarType]);+ const element = bazaar.element.querySelector(`#${BAZAAR_PACKAGE_CONFIG[bazaarType].panelID}`);if (!element) {return;}@@ -3046,8 +1769,8 @@ type="checkbox">}bazaar._data[bazaarType] = response.data.packages;bazaar._cacheBazaarDeprecations(bazaarType, response.data.packages);- const sortValue = window.siyuan.storage[Constants.LOCAL_BAZAAR][bazaar._type2tabType(bazaarType)];- const packages = sortValue && sortValue !== "0" ? bazaar._sortPackages(response.data.packages, sortValue) : response.data.packages;+ const sortValue = window.siyuan.storage[Constants.LOCAL_BAZAAR][BAZAAR_PACKAGE_CONFIG[bazaarType].tabType];+ const packages = sortValue && sortValue !== "0" ? sortBazaarPackages(response.data.packages, sortValue) : response.data.packages;bazaar._renderBazaarCards(element, packages, bazaarType,bazaarType === "themes" ? (bazaar.element.querySelector("#bazaarSelect") as HTMLSelectElement)?.value : undefined);}diff --git a/app/src/config/bazaar/events.ts b/app/src/config/bazaar/events.tsnew file mode 100644index 0000000000..a3cf5d1288--- /dev/null+++ b/app/src/config/bazaar/events.ts@@ -0,0 +1,616 @@+import {showMessage} from "../../dialog/message";+import {fetchPost} from "../../util/fetch";+import {confirmDialog} from "../../dialog/confirmDialog";+/// #if !BROWSER+import * as path from "path";+/// #endif+import {getFrontend, isMobile} from "../../util/functions";+import {setStorageVal, writeText} from "../../protyle/util/compatibility";+import {hasClosestByAttribute, hasClosestByClassName} from "../../protyle/util/hasClosest";+import {Plugin} from "../../plugin";+import type {App} from "../../index";+import {escapeHtml} from "../../util/escape";+import {setGlobalPluginsDisabled} from "../../plugin/globalState";+import {useShell} from "../../util/pathName";+import {previewImages} from "../../protyle/preview/image";+import {isBazaarPackageRatingEditable, sortBazaarPackages} from "../../util/bazaarPackage";+import {Constants} from "../../constants";+import {+ BAZAAR_PACKAGE_CONFIG,+ getBazaarTypeByMyType,+ getBazaarTypeByTab,+ isBazaarPackageType,+} from "./packageConfig";++type TBazaarController = typeof import("../bazaar").bazaar;+type TBazaarPackageSource = "downloaded" | "updated" | "bazaar";++interface IBazaarMountSnapshot {+ element: HTMLElement;+ generation: number;+ requestID?: number;+}++interface IBazaarClickContext {+ controller: TBazaarController;+ app: App;+ mount: IBazaarMountSnapshot;+ packageSource?: TBazaarPackageSource;+ packageName?: string;+ pkgType?: TBazaarType;+ pkgItem?: IBazaarItem;+ updatedItem?: IUpdatedBazaarItem;+ installedItem?: IBazaarItem;+ availableItem?: IBazaarItem;+}++interface IBazaarActionResult {+ handled: boolean;+ preventDefault?: boolean;+ stopPropagation?: boolean;+}++type TBazaarActionHandler = (context: IBazaarClickContext, target: HTMLElement) => IBazaarActionResult;++const CONTINUE: IBazaarActionResult = {handled: false};+const HANDLED: IBazaarActionResult = {handled: true, preventDefault: true, stopPropagation: true};+const HANDLED_NATIVE: IBazaarActionResult = {handled: true, stopPropagation: true};++const handleDownloadedTab: TBazaarActionHandler = (context, target) => {+ const {controller, app} = context;+ const type = target.getAttribute("data-type");+ const bazaarType = getBazaarTypeByMyType(type);+ if (!bazaarType && type !== "myUpdate") {+ return CONTINUE;+ }+ const downloadedLoading = controller.element.querySelector("#configBazaarDownloaded")+ .getAttribute("data-loading");+ if (target.classList.contains("b3-button--outline") && (type === "myUpdate" || !downloadedLoading)) {+ target.parentElement.querySelectorAll('.b3-button[data-type^="my"]').forEach((item: HTMLElement) => {+ item.classList.add("b3-button--outline");+ });+ target.classList.remove("b3-button--outline");+ if (type === "myUpdate") {+ controller._updateDownloadedToolbar("update");+ controller._renderUpdatePanel();+ controller._checkUpdate();+ } else if (bazaarType) {+ controller._genMyHTML(bazaarType, app);+ }+ }+ return HANDLED;+};++const ACTION_HANDLERS = {+ "rate-package": ((context) => {+ const {controller, packageSource, packageName, pkgType, installedItem, pkgItem} = context;+ const packageInstalled = Boolean(installedItem) ||+ (packageSource === "bazaar" && pkgItem?.installed === true);+ if (!pkgType || !packageName || !isBazaarPackageRatingEditable(packageSource, packageInstalled)) {+ return CONTINUE;+ }+ controller._openRatingDialog(pkgType, packageName);+ return HANDLED;+ }) satisfies TBazaarActionHandler,+ "copy-funding": ((context, target) => {+ const funding = target.getAttribute("data-funding");+ if (funding) {+ writeText(funding);+ showMessage(window.siyuan.languages.copied);+ }+ return HANDLED;+ }) satisfies TBazaarActionHandler,+ "keywords-expand": ((context, target) => {+ target.parentElement?.querySelectorAll("[data-keyword-hidden]").forEach((item) => {+ item.classList.remove("fn__none");+ });+ target.remove();+ return HANDLED;+ }) satisfies TBazaarActionHandler,+ "bazaar-alternative": ((context, target) => {+ const alternativeType = target.getAttribute("data-package-type");+ const alternativeName = target.getAttribute("data-package-name");+ if (isBazaarPackageType(alternativeType) && alternativeName) {+ context.controller._openBazaarAlternative(alternativeType, alternativeName);+ }+ return HANDLED;+ }) satisfies TBazaarActionHandler,+ open: ((context) => {+ const {installedItem, pkgItem, pkgType} = context;+ if ((!installedItem && !pkgItem) || !pkgType) {+ return CONTINUE;+ }+ const item = installedItem || pkgItem;+ /// #if !BROWSER+ if (["icons", "themes"].includes(pkgType)) {+ useShell("openPath", path.join(window.siyuan.config.system.confDir, "appearance", pkgType, item.name));+ } else {+ useShell("openPath", path.join(window.siyuan.config.system.dataDir, pkgType, item.name));+ }+ /// #endif+ return HANDLED;+ }) satisfies TBazaarActionHandler,+ "retry-update": ((context) => {+ context.controller._checkUpdate(true);+ return HANDLED;+ }) satisfies TBazaarActionHandler,+ goBack: ((context) => {+ context.controller.element.querySelector("#configBazaarReadme").classList.remove("config__view--show");+ return HANDLED;+ }) satisfies TBazaarActionHandler,+ install: ((context, target) => {+ const {controller, app, mount, availableItem, pkgItem, pkgType} = context;+ const installItem = availableItem || pkgItem;+ if (target.classList.contains("b3-button--progress") || target.hasAttribute("disabled") ||+ !installItem || !pkgType) {+ return HANDLED;+ }+ const themeAppearanceMode = pkgType === "themes" ? controller._resolveThemeAppearanceMode(installItem) : {};+ const request = controller._beginBazaarRequest(pkgType, mount);+ const config = BAZAAR_PACKAGE_CONFIG[pkgType];+ fetchPost(config.api.install, {+ keyword: (mount.element.querySelector(`.config-bazaar__panel[data-type="${config.tabType}"] .b3-text-field`) as HTMLInputElement).value,+ repoURL: installItem.repoURL,+ packageName: installItem.name,+ repoHash: installItem.repoHash,+ repoRef: installItem.repoRef || "",+ ...themeAppearanceMode,+ frontend: getFrontend()+ }, response => {+ controller._onBazaar(response, pkgType, request);+ if (response.code !== 0) {+ if (controller._isBazaarRequestCurrent(pkgType, request)) {+ controller._refreshReadmeDetail(pkgType, installItem.name);+ }+ return;+ }+ if (controller._isMountCurrent(mount)) {+ controller._genMyHTML(pkgType, app, false);+ controller._refreshReadmeDetail(pkgType, installItem.name);+ }+ if (pkgType === "plugins") {+ if (window.siyuan.config.bazaar.petalDisabled) {+ confirmDialog(window.siyuan.languages.confirm, window.siyuan.languages.enablePluginTip2);+ } else {+ confirmDialog("💡 " + window.siyuan.languages.enablePlugin, window.siyuan.languages.enablePluginTip, () => {+ controller._setPluginEnabled(app, installItem, true, () => {+ if (controller._isMountCurrent(mount)) {+ controller._genMyHTML(pkgType, app, false);+ controller._refreshReadmeDetail(pkgType, installItem.name);+ }+ });+ });+ }+ }+ });+ return HANDLED;+ }) satisfies TBazaarActionHandler,+ "install-all": ((context) => {+ const {controller, mount} = context;+ confirmDialog("⬆️ " + window.siyuan.languages.updateAll, window.siyuan.languages.confirmUpdateAll, () => {+ fetchPost("/api/bazaar/batchUpdatePackage", {frontend: getFrontend()}, (response) => {+ if (response.code !== 0) {+ showMessage(response.msg);+ return;+ }+ if (controller._isMountCurrent(mount)) {+ mount.element.querySelector("#configBazaarReadme")?.classList.remove("config__view--show");+ controller._checkUpdate(true);+ }+ });+ });+ return HANDLED;+ }) satisfies TBazaarActionHandler,+ feedback: (() => HANDLED) satisfies TBazaarActionHandler,+ "install-t": ((context, target) => {+ const {controller, app, mount, updatedItem, pkgItem, pkgType} = context;+ const packageName = updatedItem?.installed.name || pkgItem?.name;+ if (!target.classList.contains("b3-button--progress") && !target.hasAttribute("disabled") &&+ packageName && pkgType) {+ confirmDialog("⬆️ " + window.siyuan.languages.update, window.siyuan.languages.confirmUpdate, () => {+ if (!target.classList.contains("b3-button")) {+ target.parentElement.insertAdjacentHTML("afterend", '<img data-type="img-loading" style="position: absolute;top: 0;left: 0;height: 100%;width: 100%;padding: 16px;box-sizing: border-box;" src="/stage/loading-pure.svg">');+ }+ const request = controller._beginBazaarRequest(pkgType, mount);+ fetchPost("/api/bazaar/updateBazaarPackage", {+ packageType: pkgType,+ packageName,+ frontend: getFrontend()+ }, response => {+ if (response.code !== 0) {+ showMessage(response.msg);+ target.parentElement.parentElement.querySelector("img[data-type='img-loading']")?.remove();+ return;+ }+ controller._onBazaar(response, pkgType, request);+ if (controller._isMountCurrent(mount)) {+ mount.element.querySelector("#configBazaarReadme")?.classList.remove("config__view--show");+ controller._genMyHTML(pkgType, app);+ controller._checkUpdate(true);+ }+ });+ });+ }+ return HANDLED;+ }) satisfies TBazaarActionHandler,+ uninstall: ((context) => {+ const {controller, app, mount, installedItem, pkgType} = context;+ if (!installedItem || !pkgType) {+ return CONTINUE;+ }+ const uninstallName = installedItem.name;+ const config = BAZAAR_PACKAGE_CONFIG[pkgType];+ const keyword = (mount.element.querySelector(`.config-bazaar__panel[data-type="${config.tabType}"] .b3-text-field`) as HTMLInputElement).value;+ confirmDialog("⚠️ " + window.siyuan.languages.uninstall,+ window.siyuan.languages.confirmUninstall.replace("${name}", escapeHtml(uninstallName)), () => {+ const request = controller._beginBazaarRequest(pkgType, mount);+ fetchPost(config.api.uninstall, {+ packageName: uninstallName,+ keyword,+ frontend: getFrontend()+ }, response => {+ if (response.code !== 0) {+ showMessage(response.msg);+ return;+ }+ controller._data.details.delete(controller._getDetailKey(pkgType, uninstallName));+ controller._onBazaar(response, pkgType, request);+ if (controller._isMountCurrent(mount)) {+ mount.element.querySelector("#configBazaarReadme")?.classList.remove("config__view--show");+ controller._genMyHTML(pkgType, app);+ controller._checkUpdate(true);+ }+ });+ });+ return HANDLED;+ }) satisfies TBazaarActionHandler,+ switch: ((context, target) => {+ const {controller, app, mount, installedItem, pkgItem, pkgType} = context;+ if ((!installedItem && !pkgItem) || !pkgType || !["icons", "themes"].includes(pkgType)) {+ return CONTINUE;+ }+ if (!target.hasAttribute("disabled")) {+ const appearanceItem = installedItem || pkgItem;+ target.setAttribute("disabled", "disabled");+ controller._setAppearancePackage(pkgType as "themes" | "icons", appearanceItem, true, () => {+ if (controller._isMountCurrent(mount)) {+ controller._refreshPackageUI(pkgType, appearanceItem.name, app);+ }+ });+ }+ return HANDLED;+ }) satisfies TBazaarActionHandler,+ "package-enable": ((context, target) => handlePackageEnabled(context, target, true)) satisfies TBazaarActionHandler,+ "package-disable": ((context, target) => handlePackageEnabled(context, target, false)) satisfies TBazaarActionHandler,+ setting: ((context) => {+ const {app, pkgItem} = context;+ if (!pkgItem) {+ return CONTINUE;+ }+ if (!window.siyuan.config.bazaar.petalDisabled) {+ app.plugins.find((item: Plugin) => {+ if (item.name === pkgItem.name) {+ item.openSetting();+ return true;+ }+ });+ }+ return HANDLED;+ }) satisfies TBazaarActionHandler,+ "plugins-enable": ((context, target) => {+ const {controller, app} = context;+ if (!target.getAttribute("disabled")) {+ const requestID = ++controller._pluginGlobalRequestID;+ controller._pluginGlobalRequestPending = true;+ controller._syncPluginGlobalSwitch();+ void setGlobalPluginsDisabled(app, !(target as HTMLInputElement).checked).catch((error) => {+ console.error(error);+ }).finally(() => {+ if (requestID !== controller._pluginGlobalRequestID) {+ return;+ }+ controller._pluginGlobalRequestPending = false;+ controller._syncPluginGlobalSwitch();+ });+ }+ return HANDLED_NATIVE;+ }) satisfies TBazaarActionHandler,+ "plugin-publish-enable-label": (() => HANDLED_NATIVE) satisfies TBazaarActionHandler,+ "plugin-publish-enable": ((context, target) => {+ const {controller, app, mount, installedItem} = context;+ if (!installedItem) {+ return CONTINUE;+ }+ if (!target.hasAttribute("disabled")) {+ target.setAttribute("disabled", "disabled");+ const enabled = (target as HTMLInputElement).checked;+ controller._setPluginPublishEnabled(installedItem, enabled, () => {+ if (controller._isMountCurrent(mount)) {+ target.removeAttribute("disabled");+ controller._genMyHTML("plugins", app, true);+ }+ });+ }+ return HANDLED_NATIVE;+ }) satisfies TBazaarActionHandler,+ "plugin-enable": ((context, target) => {+ const {controller, app, mount, installedItem, pkgItem} = context;+ if (!installedItem && !pkgItem) {+ return CONTINUE;+ }+ if (!target.hasAttribute("disabled")) {+ target.setAttribute("disabled", "disabled");+ const enabled = (target as HTMLInputElement).checked;+ const pluginItem = installedItem || pkgItem;+ controller._setPluginEnabled(app, pluginItem, enabled, () => {+ if (controller._isMountCurrent(mount)) {+ target.removeAttribute("disabled");+ controller._genMyHTML("plugins", app, true);+ }+ });+ }+ return HANDLED_NATIVE;+ }) satisfies TBazaarActionHandler,+} as const;++function handlePackageEnabled(context: IBazaarClickContext, target: HTMLElement, enabled: boolean) {+ const {controller, app, mount, installedItem, pkgItem, pkgType} = context;+ if ((!installedItem && !pkgItem) || !pkgType) {+ return CONTINUE;+ }+ if (target.hasAttribute("disabled")) {+ return HANDLED;+ }+ const actionItem = installedItem || pkgItem;+ target.setAttribute("disabled", "disabled");+ if (pkgType === "plugins" && installedItem) {+ controller._setPluginEnabled(app, installedItem, enabled, () => {+ if (controller._isMountCurrent(mount)) {+ controller._refreshPackageUI(pkgType, installedItem.name, app);+ }+ });+ } else if (["icons", "themes"].includes(pkgType)) {+ controller._setAppearancePackage(pkgType as "themes" | "icons", actionItem, enabled, () => {+ if (controller._isMountCurrent(mount)) {+ controller._refreshPackageUI(pkgType, actionItem.name, app);+ }+ });+ }+ return HANDLED;+}++const applyActionResult = (event: MouseEvent, result: IBazaarActionResult) => {+ if (result.preventDefault) {+ event.preventDefault();+ }+ if (result.stopPropagation) {+ event.stopPropagation();+ }+};++const resolveClickContext = (+ controller: TBazaarController,+ app: App,+ mount: IBazaarMountSnapshot,+ target: HTMLElement,+): IBazaarClickContext => {+ const packageElement = hasClosestByAttribute(target, "data-name", null);+ let pkgType: TBazaarType | undefined;+ let pkgItem: IBazaarItem | undefined;+ let updatedItem: IUpdatedBazaarItem | undefined;+ let packageSource: TBazaarPackageSource | undefined;+ let packageName: string | undefined;+ if (packageElement) {+ packageName = packageElement.getAttribute("data-name") || undefined;+ const packageType = packageElement.getAttribute("data-package-type");+ pkgType = isBazaarPackageType(packageType) ? packageType : undefined;+ packageSource = (packageElement.getAttribute("data-package-source") ||+ packageElement.getAttribute("data-from")) as TBazaarPackageSource;+ if (packageName && pkgType && packageSource === "downloaded") {+ pkgItem = controller._data.downloaded.find((item) => item.name === packageName);+ } else if (packageName && pkgType && packageSource === "updated") {+ updatedItem = controller._getUpdatedItem(pkgType, packageName);+ pkgItem = updatedItem?.available;+ } else if (packageName && pkgType && packageSource === "bazaar") {+ pkgItem = controller._data[pkgType]?.find((item) => item.name === packageName);+ }+ }+ const packageDetail = packageName && pkgType ? controller._getPackageDetail(pkgType, packageName) : undefined;+ return {+ controller,+ app,+ mount,+ packageSource,+ packageName,+ pkgType,+ pkgItem,+ updatedItem,+ installedItem: packageDetail?.installed || updatedItem?.installed ||+ (packageSource === "downloaded" ? pkgItem : undefined),+ availableItem: packageDetail?.available || updatedItem?.available ||+ (packageSource === "bazaar" ? pkgItem : undefined),+ };+};++const handleCardClick = (context: IBazaarClickContext, eventTarget: HTMLElement) => {+ const {controller, pkgItem, pkgType, packageSource} = context;+ if (!hasClosestByClassName(eventTarget, "b3-card__actions--right") && pkgItem && !pkgItem.invalidReason &&+ pkgType && packageSource) {+ controller._renderReadme(pkgType, packageSource, pkgItem);+ }+ return HANDLED;+};++const handleLayoutTabClick = (context: IBazaarClickContext, target: HTMLElement) => {+ const {controller} = context;+ const type = target.getAttribute("data-type");+ controller.element.querySelector(".layout-tab-bar .item--focus").classList.remove("item--focus");+ target.classList.add("item--focus");+ controller.element.querySelectorAll(".config-bazaar__panel").forEach((item) => {+ if (type === item.getAttribute("data-type")) {+ item.classList.remove("fn__none");+ if (type !== "downloaded") {+ const bazaarType = getBazaarTypeByTab(type);+ if (bazaarType) {+ controller._initBazaarPanel(bazaarType, item as HTMLElement);+ }+ }+ } else {+ item.classList.add("fn__none");+ }+ });+ return HANDLED;+};++const handlePreviewClick = (target: HTMLElement) => {+ if (isMobile()) {+ const previewURL = target.dataset.previewUrl;+ if (previewURL) {+ previewImages([previewURL], previewURL);+ }+ } else {+ target.classList.toggle("item__preview--fullscreen");+ }+ return HANDLED;+};++const bindBazaarClickEvent = (+ controller: TBazaarController,+ app: App,+ mount: IBazaarMountSnapshot,+) => {+ controller.element.firstElementChild.addEventListener("click", (event: MouseEvent) => {+ if (controller._syncRatingUser()) {+ controller._refreshVisibleRatingUI();+ }+ const eventTarget = event.target as HTMLElement;+ const context = resolveClickContext(controller, app, mount, eventTarget);+ let target = eventTarget;+ while (target && !target.isEqualNode(controller.element)) {+ if (target.tagName === "A") {+ return;+ }+ const downloadedTabResult = handleDownloadedTab(context, target);+ if (downloadedTabResult.handled) {+ applyActionResult(event, downloadedTabResult);+ return;+ }+ const type = target.getAttribute("data-type");+ const handler = type && Object.prototype.hasOwnProperty.call(ACTION_HANDLERS, type) ?+ ACTION_HANDLERS[type as keyof typeof ACTION_HANDLERS] : undefined;+ const result = handler?.(context, target);+ if (result?.handled) {+ applyActionResult(event, result);+ return;+ }+ let fallbackResult: IBazaarActionResult | undefined;+ if (target.classList.contains("b3-card")) {+ fallbackResult = handleCardClick(context, eventTarget);+ } else if (target.classList.contains("item") && !target.classList.contains("item--focus")) {+ fallbackResult = handleLayoutTabClick(context, target);+ } else if (target.classList.contains("item__preview")) {+ fallbackResult = handlePreviewClick(target);+ }+ if (fallbackResult?.handled) {+ applyActionResult(event, fallbackResult);+ return;+ }+ target = target.parentElement;+ }+ });+};++const bindBazaarSearchEvents = (+ controller: TBazaarController,+ app: App,+ mount: IBazaarMountSnapshot,+) => {+ controller.element.querySelectorAll(".config-bazaar__panel .b3-text-field")+ .forEach((inputElement: HTMLInputElement) => {+ inputElement.addEventListener("keydown", (event) => {+ if (event.isComposing || event.key !== "Enter") {+ return;+ }+ const keyword = inputElement.value.trim();+ const type = (hasClosestByClassName(inputElement, "config-bazaar__panel") as HTMLElement)+ .getAttribute("data-type");+ const bazaarType = getBazaarTypeByTab(type);+ if (bazaarType) {+ const config = BAZAAR_PACKAGE_CONFIG[bazaarType];+ const request = controller._beginBazaarRequest(bazaarType, mount);+ fetchPost(config.api.bazaar, {+ ...(config.bazaarRequestUsesFrontend ? {frontend: getFrontend()} : {}),+ keyword,+ }, response => {+ controller._onBazaar(response, bazaarType, request);+ });+ } else if (type === "downloaded") {+ const activeType = inputElement.closest(".config-bazaar__title")+ ?.querySelector('.b3-button[data-type^="my"]:not(.b3-button--outline)')+ ?.getAttribute("data-type");+ const selectedType = getBazaarTypeByMyType(activeType);+ if (selectedType) {+ controller._genMyHTML(selectedType, app);+ }+ }+ event.preventDefault();+ });+ });+};++const bindBazaarSelectEvents = (controller: TBazaarController) => {+ controller.element.querySelectorAll(".b3-select").forEach((selectElement: HTMLSelectElement) => {+ selectElement.addEventListener("change", () => {+ if (selectElement.getAttribute("data-type") === "downloaded-sort") {+ const activeBtn = controller.element.querySelector("#configBazaarDownloaded")?.previousElementSibling+ ?.querySelector('.b3-button[data-type^="my"]:not(.b3-button--outline)') as HTMLElement;+ if (activeBtn?.getAttribute("data-type") === "myUpdate") {+ return;+ }+ const bazaarType = getBazaarTypeByMyType(activeBtn?.getAttribute("data-type"));+ if (!bazaarType) {+ return;+ }+ window.siyuan.storage[Constants.LOCAL_BAZAAR][BAZAAR_PACKAGE_CONFIG[bazaarType].downloadedSortKey] =+ selectElement.value;+ setStorageVal(Constants.LOCAL_BAZAAR, window.siyuan.storage[Constants.LOCAL_BAZAAR]);+ controller._reorderDownloadedCards(controller._sortDownloadedPackages(+ controller._data.downloadedDefault, selectElement.value));+ } else if (selectElement.id === "bazaarSelect") {+ controller._renderBazaarCards(+ controller.element.querySelector("#configBazaarTheme"),+ controller._data.themes,+ "themes",+ selectElement.value+ );+ } else {+ const panelElement = selectElement.parentElement.parentElement;+ const panelType = panelElement.getAttribute("data-type");+ const bazaarType = getBazaarTypeByTab(panelType);+ if (!bazaarType) {+ return;+ }+ controller._renderBazaarCards(+ panelElement.querySelector(".config-bazaar__content"),+ sortBazaarPackages(controller._data[bazaarType], selectElement.value),+ bazaarType,+ bazaarType === "themes" ?+ (controller.element.querySelector("#bazaarSelect") as HTMLSelectElement).value : undefined+ );+ window.siyuan.storage[Constants.LOCAL_BAZAAR][BAZAAR_PACKAGE_CONFIG[bazaarType].tabType] =+ selectElement.value;+ setStorageVal(Constants.LOCAL_BAZAAR, window.siyuan.storage[Constants.LOCAL_BAZAAR]);+ }+ });+ });+};++export const bindBazaarEvents = (+ controller: TBazaarController,+ app: App,+ mount: IBazaarMountSnapshot,+) => {+ bindBazaarClickEvent(controller, app, mount);+ bindBazaarSearchEvents(controller, app, mount);+ bindBazaarSelectEvents(controller);+};diff --git a/app/src/config/bazaar/html.ts b/app/src/config/bazaar/html.tsnew file mode 100644index 0000000000..fd2af6c032--- /dev/null+++ b/app/src/config/bazaar/html.ts@@ -0,0 +1,37 @@+import {BAZAAR_PACKAGE_CONFIG} from "./packageConfig";++const genSortOptionsHTML = (sortValue: string) => `<option ${sortValue === "0" ? "selected" : ""} value="0">${window.siyuan.languages.sortByUpdateTimeDesc}</option>+<option ${sortValue === "1" ? "selected" : ""} value="1">${window.siyuan.languages.sortByUpdateTimeAsc}</option>+<option ${sortValue === "2" ? "selected" : ""} value="2">${window.siyuan.languages.sortByDownloadsDesc}</option>+<option ${sortValue === "3" ? "selected" : ""} value="3">${window.siyuan.languages.sortByDownloadsAsc}</option>+<option ${sortValue === "4" ? "selected" : ""} value="4">${window.siyuan.languages.sortByRatingDesc}</option>+<option ${sortValue === "5" ? "selected" : ""} value="5">${window.siyuan.languages.sortByRatingAsc}</option>`;++const genThemeModeSelectHTML = () => `<div class="fn__space"></div>+<select id="bazaarSelect" class="b3-select">+ <option selected value="2">${window.siyuan.languages.all}</option>+ <option value="0">${window.siyuan.languages.themeLight}</option>+ <option value="1">${window.siyuan.languages.themeDark}</option>+</select>`;++export const genBazaarPackagePanelHTML = (bazaarType: TBazaarType, sortValue: string, loadingHTML: string) => {+ const config = BAZAAR_PACKAGE_CONFIG[bazaarType];+ return `<div class="config-bazaar__panel fn__none" data-type="${config.tabType}">+ <div class="fn__flex config-bazaar__title">+ <svg class="svg ft__on-surface fn__flex-center"><use xlink:href="#iconSort"></use></svg>+ <div class="fn__space"></div>+ <select class="b3-select">+ ${genSortOptionsHTML(sortValue)}+ </select>+ ${bazaarType === "themes" ? genThemeModeSelectHTML() : ""}+ <div class="fn__space"></div>+ <div class="fn__flex config-bazaar__filter-row">+ <input class="b3-text-field" placeholder="${window.siyuan.languages.enterKey} ${window.siyuan.languages.search}">+ <div class="counter counter--bg fn__flex-center ariaLabel" data-position="north" aria-label="${window.siyuan.languages.total}"></div>+ </div>+ </div>+ <div id="${config.panelID}" class="config-bazaar__content">+ ${loadingHTML}+ </div>+</div>`;+};diff --git a/app/src/config/bazaar/packageConfig.test.ts b/app/src/config/bazaar/packageConfig.test.tsnew file mode 100644index 0000000000..7ae238884f--- /dev/null+++ b/app/src/config/bazaar/packageConfig.test.ts@@ -0,0 +1,36 @@+import {describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {+ BAZAAR_PACKAGE_CONFIG,+ BAZAAR_PACKAGE_TYPES,+ getBazaarTypeByMyType,+ getBazaarTypeByTab,+ isBazaarPackageType,+} from "./packageConfig";++describe("bazaar package configuration", () => {+ it("defines explicit mappings for every package type", () => {+ assert.deepEqual(BAZAAR_PACKAGE_TYPES.map((type) => BAZAAR_PACKAGE_CONFIG[type].tabType), [+ "plugin", "theme", "icon", "template", "widget",+ ]);+ assert.deepEqual(BAZAAR_PACKAGE_TYPES.map((type) => BAZAAR_PACKAGE_CONFIG[type].myType), [+ "myPlugin", "myTheme", "myIcon", "myTemplate", "myWidget",+ ]);+ });++ it("resolves tab and downloaded tab types without string transformations", () => {+ BAZAAR_PACKAGE_TYPES.forEach((type) => {+ const config = BAZAAR_PACKAGE_CONFIG[type];+ assert.equal(getBazaarTypeByTab(config.tabType), type);+ assert.equal(getBazaarTypeByMyType(config.myType), type);+ });+ });++ it("rejects values that are not package types", () => {+ assert.equal(isBazaarPackageType("plugins"), true);+ assert.equal(isBazaarPackageType("updates"), false);+ assert.equal(getBazaarTypeByTab("downloaded"), undefined);+ assert.equal(getBazaarTypeByMyType("myUpdate"), undefined);+ assert.equal(getBazaarTypeByMyType(undefined), undefined);+ });+});diff --git a/app/src/config/bazaar/packageConfig.ts b/app/src/config/bazaar/packageConfig.tsnew file mode 100644index 0000000000..f5d80a6fd9--- /dev/null+++ b/app/src/config/bazaar/packageConfig.ts@@ -0,0 +1,117 @@+export type TBazaarTabType = "plugin" | "theme" | "icon" | "template" | "widget";++export type TBazaarMyType = "myPlugin" | "myTheme" | "myIcon" | "myTemplate" | "myWidget";++type TBazaarLanguageKey = "plugin" | "theme" | "icon" | "template" | "widget";++interface IBazaarPackageConfig {+ tabType: TBazaarTabType;+ myType: TBazaarMyType;+ languageKey: TBazaarLanguageKey;+ panelID: string;+ downloadedSortKey: "downloadedPlugin" | "downloadedTheme" | "downloadedIcon" |+ "downloadedTemplate" | "downloadedWidget";+ bazaarRequestUsesFrontend: boolean;+ api: {+ bazaar: string;+ installed: string;+ install: string;+ uninstall: string;+ };+}++export const BAZAAR_PACKAGE_TYPES = ["plugins", "themes", "icons", "templates", "widgets"] as const satisfies readonly TBazaarType[];++export const BAZAAR_PACKAGE_CONFIG = {+ plugins: {+ tabType: "plugin",+ myType: "myPlugin",+ languageKey: "plugin",+ panelID: "configBazaarPlugin",+ downloadedSortKey: "downloadedPlugin",+ bazaarRequestUsesFrontend: true,+ api: {+ bazaar: "/api/bazaar/getBazaarPlugin",+ installed: "/api/bazaar/getInstalledPlugin",+ install: "/api/bazaar/installBazaarPlugin",+ uninstall: "/api/bazaar/uninstallBazaarPlugin",+ },+ },+ themes: {+ tabType: "theme",+ myType: "myTheme",+ languageKey: "theme",+ panelID: "configBazaarTheme",+ downloadedSortKey: "downloadedTheme",+ bazaarRequestUsesFrontend: true,+ api: {+ bazaar: "/api/bazaar/getBazaarTheme",+ installed: "/api/bazaar/getInstalledTheme",+ install: "/api/bazaar/installBazaarTheme",+ uninstall: "/api/bazaar/uninstallBazaarTheme",+ },+ },+ icons: {+ tabType: "icon",+ myType: "myIcon",+ languageKey: "icon",+ panelID: "configBazaarIcon",+ downloadedSortKey: "downloadedIcon",+ bazaarRequestUsesFrontend: false,+ api: {+ bazaar: "/api/bazaar/getBazaarIcon",+ installed: "/api/bazaar/getInstalledIcon",+ install: "/api/bazaar/installBazaarIcon",+ uninstall: "/api/bazaar/uninstallBazaarIcon",+ },+ },+ templates: {+ tabType: "template",+ myType: "myTemplate",+ languageKey: "template",+ panelID: "configBazaarTemplate",+ downloadedSortKey: "downloadedTemplate",+ bazaarRequestUsesFrontend: false,+ api: {+ bazaar: "/api/bazaar/getBazaarTemplate",+ installed: "/api/bazaar/getInstalledTemplate",+ install: "/api/bazaar/installBazaarTemplate",+ uninstall: "/api/bazaar/uninstallBazaarTemplate",+ },+ },+ widgets: {+ tabType: "widget",+ myType: "myWidget",+ languageKey: "widget",+ panelID: "configBazaarWidget",+ downloadedSortKey: "downloadedWidget",+ bazaarRequestUsesFrontend: false,+ api: {+ bazaar: "/api/bazaar/getBazaarWidget",+ installed: "/api/bazaar/getInstalledWidget",+ install: "/api/bazaar/installBazaarWidget",+ uninstall: "/api/bazaar/uninstallBazaarWidget",+ },+ },+} satisfies Record<TBazaarType, IBazaarPackageConfig>;++const BAZAAR_TYPE_BY_TAB = Object.fromEntries(BAZAAR_PACKAGE_TYPES.map((type) => [+ BAZAAR_PACKAGE_CONFIG[type].tabType,+ type,+])) as Record<TBazaarTabType, TBazaarType>;++const BAZAAR_TYPE_BY_MY_TYPE = Object.fromEntries(BAZAAR_PACKAGE_TYPES.map((type) => [+ BAZAAR_PACKAGE_CONFIG[type].myType,+ type,+])) as Record<TBazaarMyType, TBazaarType>;++export const isBazaarPackageType = (value: string | null | undefined): value is TBazaarType =>+ Boolean(value && Object.prototype.hasOwnProperty.call(BAZAAR_PACKAGE_CONFIG, value));++export const getBazaarTypeByTab = (value: string | null | undefined): TBazaarType | undefined =>+ value && Object.prototype.hasOwnProperty.call(BAZAAR_TYPE_BY_TAB, value) ?+ BAZAAR_TYPE_BY_TAB[value as TBazaarTabType] : undefined;++export const getBazaarTypeByMyType = (value: string | null | undefined): TBazaarType | undefined =>+ value && Object.prototype.hasOwnProperty.call(BAZAAR_TYPE_BY_MY_TYPE, value) ?+ BAZAAR_TYPE_BY_MY_TYPE[value as TBazaarMyType] : undefined;diff --git a/app/src/config/bazaar/rating.ts b/app/src/config/bazaar/rating.tsnew file mode 100644index 0000000000..48aa5a02ac--- /dev/null+++ b/app/src/config/bazaar/rating.ts@@ -0,0 +1,701 @@+import {showMessage} from "../../dialog/message";+import {fetchPost} from "../../util/fetch";+import {Constants} from "../../constants";+import {isMobile} from "../../util/functions";+import {escapeAttr, escapeHtml} from "../../util/escape";+import {+ applyBazaarPackageRatingToItem,+ beginBazaarRatingRequest,+ beginBazaarRatingSubmission,+ getBazaarRatingErrorLanguageKey,+ getBazaarRatingMutationVersion,+ getDisplayableBazaarRating,+ isBazaarPackageRatingLoaded,+ isBazaarRatingRemovalAvailable,+ isBazaarRatingMutationVersionCurrent,+ isLatestBazaarRatingRequest,+ normalizeBazaarPackageRatingResponse,+ normalizeBazaarPackageRatingsResponse,+ normalizeBazaarPackageUserRatingsResponse,+ normalizeBazaarUserRating,+ sortBazaarPackages,+} from "../../util/bazaarPackage";+import {Dialog} from "../../dialog";+import {BAZAAR_PACKAGE_CONFIG, BAZAAR_PACKAGE_TYPES, isBazaarPackageType} from "./packageConfig";++type TBazaarController = typeof import("../bazaar").bazaar;++export const getRatingKey = (bazaarType: TBazaarType, packageName: string) => {+ return `${bazaarType}:${packageName}`;+};++export const syncRatingUser = (controller: TBazaarController) => {+ const userID = window.siyuan.user ? `${window.siyuan.config.cloudRegion}:${window.siyuan.user.userId}` : "";+ if (controller._ratingUserID !== userID) {+ controller._ratingUserID = userID;+ controller._data.userRatings.clear();+ controller._data.userRatingKeys.clear();+ controller._data.userRatingLoadingKeys.clear();+ controller._data.userRatingSubmitRequestIDs.clear();+ controller._data.userRatingBatchRequestIDs.clear();+ return true;+ }+ return false;+};++export const refreshVisibleRatingUI = (controller: TBazaarController) => {+ const keys = new Set<string>();+ controller.element?.querySelectorAll<HTMLElement>("[data-package-type][data-name]").forEach((element) => {+ const bazaarType = element.dataset.packageType;+ const packageName = element.dataset.name;+ if (isBazaarPackageType(bazaarType) && packageName) {+ keys.add(controller._getRatingKey(bazaarType, packageName));+ }+ });+ keys.forEach((key) => {+ const separator = key.indexOf(":");+ controller._refreshRatingUI(key.slice(0, separator) as TBazaarType, key.slice(separator + 1));+ });+ const sideElement = controller.element?.querySelector("#configBazaarReadme.config__view--show .item__side");+ const bazaarType = sideElement?.getAttribute("data-package-type") as TBazaarType;+ const packageName = sideElement?.getAttribute("data-name");+ const from = sideElement?.getAttribute("data-from") as "downloaded" | "updated" | "bazaar";+ if (bazaarType && packageName && from) {+ controller._loadReadmeRating(bazaarType, packageName, from);+ }+ if (window.siyuan.user) {+ if (controller._isUpdatePanelActive()) {+ controller._loadUpdatedRatings();+ } else if (controller._data.downloadedType) {+ controller._loadDownloadedUserRatings(controller._data.downloadedType, controller._data.downloadedDefault);+ }+ }+};++export const bindRatingUserChange = (controller: TBazaarController) => {+ if (controller._ratingUserChangeHandler) {+ window.removeEventListener("siyuan-login-success", controller._ratingUserChangeHandler);+ }+ const mount = controller._captureMount();+ controller._ratingUserChangeHandler = () => {+ if (!controller._isMountCurrent(mount)) {+ return;+ }+ controller._syncRatingUser();+ controller._refreshVisibleRatingUI();+ };+ window.addEventListener("siyuan-login-success", controller._ratingUserChangeHandler);+};++export const getRatingSummaryText = (rating?: IBazaarRating) => {+ const normalized = getDisplayableBazaarRating(rating);+ if (!normalized) {+ return window.siyuan.languages.bazaarNoRatings;+ }+ return window.siyuan.languages.bazaarRatingSummary+ .replace("${average}", normalized.average.toLocaleString(undefined, {+ minimumFractionDigits: 1,+ maximumFractionDigits: 1,+ }))+ .replace("${count}", normalized.count.toLocaleString());+};++export const genRatingStarsHTML = (value: number) => {+ const activePercentage = Math.max(0, Math.min(100, value / 5 * 100));+ const inactiveStars = Array.from({length: 5}, () => '<svg class="config-bazaar__rating-star config-bazaar__rating-star--outline"><use xlink:href="#iconStar"></use></svg>').join("");+ const activeStars = Array.from({length: 5}, () => '<svg class="config-bazaar__rating-star"><use xlink:href="#iconStar"></use></svg>').join("");+ return `<span class="config-bazaar__rating-stars" aria-hidden="true">+${inactiveStars}+<span class="config-bazaar__rating-stars--active" style="width: ${activePercentage}%">${activeStars}</span>+</span>`;+};++export const genCardRatingHTML = (controller: TBazaarController, item: Pick<IBazaarItem, "rating">, loaded = true) => {+ const rating = getDisplayableBazaarRating(item.rating);+ const hidden = !loaded || !rating;+ const summary = controller._getRatingSummaryText(rating);+ const average = rating?.average.toLocaleString(undefined, {+ minimumFractionDigits: 1,+ maximumFractionDigits: 1,+ });+ return `<span data-rating-card-slot data-position="north" class="ariaLabel block__icon block__icon--show block__icon--text${hidden ? " fn__none" : ""}" aria-label="${escapeAttr(summary)}">+<svg aria-hidden="true"><use xlink:href="#iconStar"></use></svg>+<span class="fn__space--small"></span>+<span>${escapeHtml(average || "")}</span>+</span>`;+};++export const genRatePackageActionHTML = (loaded: boolean, rating?: unknown) => {+ const userRating = normalizeBazaarUserRating(rating);+ const rated = userRating !== undefined && userRating > 0;+ const ariaLabel = rated ? window.siyuan.languages.bazaarYourRatingValue.replace("${rating}", userRating.toString()) :+ window.siyuan.languages.bazaarRatePackage;+ return `<span data-rating-card-slot data-position="north" data-type="rate-package"${rated ? ` data-user-rating="${userRating}"` : ""} class="ariaLabel block__icon block__icon--show${loaded ? "" : " fn__none"}" aria-label="${escapeAttr(ariaLabel)}">+<svg aria-hidden="true"><use xlink:href="#iconStar"></use></svg>+</span>`;+};++export const genRatingDistributionHTML = (rating?: IBazaarRating) => {+ const normalized = getDisplayableBazaarRating(rating);+ return [5, 4, 3, 2, 1].map((star) => {+ const count = normalized?.distribution[star - 1] || 0;+ const ratio = normalized ? Math.min(1, count / normalized.count) : 0;+ const percentage = ratio * 100;+ const percentageText = new Intl.NumberFormat(undefined, {+ style: "percent",+ maximumFractionDigits: 0,+ }).format(ratio);+ const label = window.siyuan.languages.bazaarRatingDistributionLabel+ .replace("${star}", star.toString())+ .replace("${count}", count.toLocaleString());+ return `<div class="config-bazaar__rating-row" aria-label="${escapeAttr(`${label} ${percentageText}`)}">+<span>${star}</span>+<svg class="config-bazaar__rating-star" aria-hidden="true"><use xlink:href="#iconStar"></use></svg>+<span class="config-bazaar__rating-track" aria-hidden="true"><span style="width: ${percentage}%"></span></span>+<span>${escapeHtml(percentageText)}</span>+<span>${count.toLocaleString()}</span>+</div>`;+ }).join("");+};++export const genReadmeRatingHTML = (controller: TBazaarController, bazaarType: TBazaarType, item: IBazaarItem, loaded: boolean) => {+ if (!loaded) {+ return "";+ }+ controller._syncRatingUser();+ const rating = getDisplayableBazaarRating(item.rating);+ const userRating = controller._data.userRatings.get(controller._getRatingKey(bazaarType, item.name)) || 0;+ let action = "";+ if (item.installed) {+ if (window.siyuan.user) {+ const actionText = userRating ? window.siyuan.languages.bazaarYourRatingValue.replace("${rating}", userRating.toString()) :+ window.siyuan.languages.bazaarRatePackage;+ action = `<button type="button" class="config-bazaar__rating-action" data-type="rate-package" aria-label="${escapeAttr(actionText)}">+${controller._genRatingStarsHTML(userRating)}+<span>${escapeHtml(actionText)}</span>+</button>`;+ } else {+ action = `<div class="config-bazaar__rating-tip">${window.siyuan.languages.bazaarRatingLoginTip}</div>`;+ }+ } else {+ action = `<div class="config-bazaar__rating-tip">${window.siyuan.languages.bazaarRatingInstallTip}</div>`;+ }+ const summary = rating ? controller._getRatingSummaryText(rating) : "";+ const aggregate = rating ? `<div class="config-bazaar__rating-summary" aria-label="${escapeAttr(summary)}">+ ${controller._genRatingStarsHTML(rating.average)}+ <span>${escapeHtml(summary)}</span>+</div>+<div class="config-bazaar__rating-distribution">${controller._genRatingDistributionHTML(rating)}</div>` : "";+ return `<section class="item__meta-section config-bazaar__rating-detail">+<div class="item__meta-title">${window.siyuan.languages.bazaarRating}</div>+${aggregate}+${action}+</section>`;+};++export const applyPackageRating = (controller: TBazaarController, bazaarType: TBazaarType, packageName: string, rating?: IBazaarRating, refreshUI = true) => {+ const key = controller._getRatingKey(bazaarType, packageName);+ if (rating) {+ controller._data.ratings.set(key, rating);+ } else {+ controller._data.ratings.delete(key);+ }+ const updateItem = (item?: IBazaarItem) => {+ applyBazaarPackageRatingToItem(item, packageName, rating);+ };+ controller._data[bazaarType].forEach(updateItem);+ if (controller._data.downloadedType === bazaarType) {+ controller._data.downloadedDefault.forEach(updateItem);+ controller._data.downloaded.forEach(updateItem);+ }+ controller._data.update[bazaarType].forEach((item) => {+ updateItem(item.installed);+ updateItem(item.available);+ });+ const detail = controller._getPackageDetail(bazaarType, packageName);+ updateItem(detail?.installed);+ updateItem(detail?.available);+ if (refreshUI) {+ controller._refreshRatingUI(bazaarType, packageName);+ }+};++export const applyPackageRatingResponse = (controller: TBazaarController, bazaarType: TBazaarType, packageName: string, data: {+ ratingAvailable?: unknown;+ rating?: Partial<IBazaarRating> | null;+ }, refreshUI = true) => {+ const key = controller._getRatingKey(bazaarType, packageName);+ const publicRating = normalizeBazaarPackageRatingResponse(data);+ if (publicRating.loaded) {+ controller._data.downloadedRatingKeys.add(key);+ controller._applyPackageRating(bazaarType, packageName, publicRating.rating, refreshUI);+ } else {+ controller._data.downloadedRatingKeys.delete(key);+ if (refreshUI) {+ controller._refreshRatingUI(bazaarType, packageName);+ }+ }+ return publicRating.loaded;+};++export const getRatingItem = (controller: TBazaarController, bazaarType: TBazaarType, packageName: string, from: "downloaded" | "updated" | "bazaar") => {+ const detail = controller._getPackageDetail(bazaarType, packageName);+ if (from === "downloaded") {+ return detail?.installed || (controller._data.downloadedType === bazaarType ?+ controller._data.downloaded.find((item) => item.name === packageName) : undefined);+ }+ if (from === "updated") {+ return detail?.available || controller._getUpdatedItem(bazaarType, packageName)?.available;+ }+ return detail?.available || controller._data[bazaarType].find((item) => item.name === packageName);+};++export const refreshRatingUI = (controller: TBazaarController, bazaarType: TBazaarType, packageName: string) => {+ controller._syncRatingUser();+ controller.element?.querySelectorAll(`.b3-card[data-package-type="${bazaarType}"]`).forEach((card) => {+ if (card.getAttribute("data-name") !== packageName) {+ return;+ }+ const source = card.getAttribute("data-package-source") as "downloaded" | "updated" | "bazaar";+ const item = controller._getRatingItem(bazaarType, packageName, source);+ const slot = card.querySelector<HTMLElement>("[data-rating-card-slot]");+ if (item && slot) {+ const key = controller._getRatingKey(bazaarType, packageName);+ const loaded = isBazaarPackageRatingLoaded(source, controller._data.downloadedRatingKeys.has(key),+ item.ratingAvailable);+ if (source === "bazaar") {+ const rating = loaded ? getDisplayableBazaarRating(item.rating) : undefined;+ slot.classList.toggle("fn__none", !rating);+ if (rating) {+ slot.setAttribute("aria-label", controller._getRatingSummaryText(rating));+ const averageElement = slot.lastElementChild;+ if (averageElement) {+ averageElement.textContent = rating.average.toLocaleString(undefined, {+ minimumFractionDigits: 1,+ maximumFractionDigits: 1,+ });+ }+ }+ } else {+ slot.classList.toggle("fn__none", !loaded);+ const userRating = controller._data.userRatingKeys.has(key) ?+ normalizeBazaarUserRating(controller._data.userRatings.get(key)) : undefined;+ if (userRating !== undefined && userRating > 0) {+ slot.dataset.userRating = userRating.toString();+ slot.setAttribute("aria-label", window.siyuan.languages.bazaarYourRatingValue+ .replace("${rating}", userRating.toString()));+ } else {+ slot.removeAttribute("data-user-rating");+ slot.setAttribute("aria-label", window.siyuan.languages.bazaarRatePackage);+ }+ }+ }+ });+ const sideElement = controller.element?.querySelector("#configBazaarReadme.config__view--show .item__side");+ if (sideElement?.getAttribute("data-package-type") !== bazaarType ||+ sideElement.getAttribute("data-name") !== packageName) {+ return;+ }+ const from = sideElement.getAttribute("data-from") as "downloaded" | "updated" | "bazaar";+ const item = controller._getRatingItem(bazaarType, packageName, from);+ const slot = sideElement.querySelector('[data-type="rating-detail-slot"]');+ if (item && slot) {+ const key = controller._getRatingKey(bazaarType, packageName);+ const loaded = isBazaarPackageRatingLoaded(from, controller._data.downloadedRatingKeys.has(key),+ item.ratingAvailable);+ const displayItem = from === "bazaar" ? item : {...item, rating: controller._data.ratings.get(key)};+ slot.innerHTML = controller._genReadmeRatingHTML(bazaarType, displayItem, loaded);+ }+};++export const loadDownloadedRatings = (controller: TBazaarController, bazaarType: TBazaarType, packages: IBazaarItem[]) => {+ const packageNames = packages.filter((item) => !item.invalidReason).map((item) => item.name);+ if (packageNames.length === 0) {+ return;+ }+ const requestID = (controller._data.ratingBatchRequestIDs.get(bazaarType) || 0) + 1;+ controller._data.ratingBatchRequestIDs.set(bazaarType, requestID);+ const mutationVersions = new Map(packageNames.map((packageName) => {+ const key = controller._getRatingKey(bazaarType, packageName);+ return [packageName, getBazaarRatingMutationVersion(controller._data.ratingMutationVersions, key)];+ }));+ const mount = controller._captureMount();+ fetchPost("/api/bazaar/getBazaarPackageRatings", {+ packageType: bazaarType,+ packageNames,+ }, response => {+ if (response.code !== 0 || controller._data.ratingBatchRequestIDs.get(bazaarType) !== requestID ||+ !controller._isMountCurrent(mount) || !controller.element?.isConnected) {+ return;+ }+ const ratings = normalizeBazaarPackageRatingsResponse(packageNames, response.data);+ if (!ratings) {+ return;+ }+ ratings.forEach((ratingResponse, packageName) => {+ const key = controller._getRatingKey(bazaarType, packageName);+ if (isBazaarRatingMutationVersionCurrent(controller._data.ratingMutationVersions, key,+ mutationVersions.get(packageName) || 0)) {+ controller._applyPackageRatingResponse(bazaarType, packageName, ratingResponse);+ }+ });+ });+};++export const loadDownloadedUserRatings = (controller: TBazaarController, bazaarType: TBazaarType, packages: IBazaarItem[]) => {+ controller._syncRatingUser();+ if (!window.siyuan.user) {+ return;+ }+ const requestedUserID = controller._ratingUserID;+ const packageNames = Array.from(new Set(packages.filter((item) => !item.invalidReason).map((item) => item.name)))+ .filter((packageName) => {+ const key = controller._getRatingKey(bazaarType, packageName);+ return !controller._data.userRatingKeys.has(key) &&+ !controller._data.userRatingLoadingKeys.has(`${requestedUserID}|${key}`);+ });+ if (packageNames.length === 0) {+ return;+ }+ const requestKey = `${requestedUserID}|${bazaarType}|${JSON.stringify(packageNames)}`;+ const requestID = (controller._data.userRatingBatchRequestIDs.get(requestKey) || 0) + 1;+ controller._data.userRatingBatchRequestIDs.set(requestKey, requestID);+ const loadingKeys = packageNames.map((packageName) => {+ const loadingKey = `${requestedUserID}|${controller._getRatingKey(bazaarType, packageName)}`;+ controller._data.userRatingLoadingKeys.add(loadingKey);+ return loadingKey;+ });+ const mutationVersions = new Map(packageNames.map((packageName) => {+ const key = controller._getRatingKey(bazaarType, packageName);+ return [packageName, getBazaarRatingMutationVersion(controller._data.ratingMutationVersions, key)];+ }));+ const mount = controller._captureMount();+ fetchPost("/api/bazaar/getBazaarPackageUserRatings", {+ packageType: bazaarType,+ packageNames,+ }, response => {+ controller._syncRatingUser();+ if (response.code !== 0 || requestedUserID !== controller._ratingUserID ||+ controller._data.userRatingBatchRequestIDs.get(requestKey) !== requestID ||+ !controller._isMountCurrent(mount) || !controller.element?.isConnected) {+ return;+ }+ const userRatings = normalizeBazaarPackageUserRatingsResponse(packageNames, response.data);+ if (!userRatings) {+ return;+ }+ userRatings.forEach((userRating, packageName) => {+ const key = controller._getRatingKey(bazaarType, packageName);+ if (isBazaarRatingMutationVersionCurrent(controller._data.ratingMutationVersions, key,+ mutationVersions.get(packageName) || 0)) {+ controller._data.userRatings.set(key, userRating);+ controller._data.userRatingKeys.add(key);+ controller._refreshRatingUI(bazaarType, packageName);+ }+ });+ }).finally(() => {+ loadingKeys.forEach((loadingKey) => controller._data.userRatingLoadingKeys.delete(loadingKey));+ if (controller._data.userRatingBatchRequestIDs.get(requestKey) === requestID) {+ controller._data.userRatingBatchRequestIDs.delete(requestKey);+ }+ });+};++export const loadUpdatedRatings = (controller: TBazaarController) => {+ BAZAAR_PACKAGE_TYPES.forEach((bazaarType) => {+ const items = controller._data.update[bazaarType];+ const installed = items.map((item) => item.installed);+ if (items.length && !items.every((item) => controller._data.downloadedRatingKeys.has(+ controller._getRatingKey(bazaarType, item.installed.name)))) {+ controller._loadDownloadedRatings(bazaarType, installed);+ }+ if (items.length && window.siyuan.user) {+ controller._loadDownloadedUserRatings(bazaarType, installed);+ }+ });+};++export const fetchPackageRating = (controller: TBazaarController, bazaarType: TBazaarType, packageName: string, callback?: () => void, silent = true) => {+ controller._syncRatingUser();+ const requestedUserID = controller._ratingUserID;+ const key = controller._getRatingKey(bazaarType, packageName);+ const loadingKey = `${requestedUserID}|${key}`;+ controller._data.userRatingLoadingKeys.add(loadingKey);+ const mount = controller._captureMount();+ let handled = false;+ fetchPost("/api/bazaar/getBazaarPackageRating", {+ packageType: bazaarType,+ packageName,+ }, response => {+ handled = true;+ controller._syncRatingUser();+ if (requestedUserID !== controller._ratingUserID || !controller._isMountCurrent(mount)) {+ return;+ }+ if (response.code !== 0 || !response.data) {+ if (!silent) {+ const languageKey = getBazaarRatingErrorLanguageKey(response.data);+ showMessage(languageKey ? window.siyuan.languages[languageKey] :+ response.msg || window.siyuan.languages.bazaarRatingFailed);+ }+ return;+ }+ const userRating = response.data.userRating;+ controller._data.userRatings.set(key, normalizeBazaarUserRating(userRating) || 0);+ controller._data.userRatingKeys.add(key);+ if (!controller._applyPackageRatingResponse(bazaarType, packageName, response.data)) {+ if (!silent) {+ showMessage(window.siyuan.languages.bazaarRatingFailed);+ }+ return;+ }+ callback?.();+ }).finally(() => {+ controller._data.userRatingLoadingKeys.delete(loadingKey);+ if (!handled && !silent && requestedUserID === controller._ratingUserID) {+ showMessage(window.siyuan.languages.bazaarRatingFailed);+ }+ });+};++export const loadReadmeRating = (controller: TBazaarController, bazaarType: TBazaarType, packageName: string, from: "downloaded" | "updated" | "bazaar") => {+ controller._syncRatingUser();+ const key = controller._getRatingKey(bazaarType, packageName);+ const loadingKey = `${controller._ratingUserID}|${key}`;+ if (controller._getRatingItem(bazaarType, packageName, from)?.installed && window.siyuan.user &&+ !controller._data.userRatingKeys.has(key) &&+ !controller._data.userRatingLoadingKeys.has(loadingKey)) {+ controller._fetchPackageRating(bazaarType, packageName);+ }+};++export const submitPackageRating = (controller: TBazaarController, bazaarType: TBazaarType, packageName: string, rating: number, callback: (success: boolean) => void) => {+ controller._syncRatingUser();+ const mount = controller._captureMount();+ const removing = rating === 0;+ const failureMessage = removing ? window.siyuan.languages.bazaarRemoveRatingFailed :+ window.siyuan.languages.bazaarRatingFailed;+ if (normalizeBazaarUserRating(rating) === undefined) {+ showMessage(failureMessage);+ callback(false);+ return;+ }+ const requestedUserID = controller._ratingUserID;+ const key = controller._getRatingKey(bazaarType, packageName);+ const requestKey = `${requestedUserID}|${key}`;+ if (!beginBazaarRatingSubmission(controller._data.userRatingSubmittingKeys, requestKey)) {+ showMessage(window.siyuan.languages.loading);+ callback(false);+ return;+ }+ const requestID = beginBazaarRatingRequest(controller._data.userRatingSubmitRequestIDs, requestKey);+ let handled = false;+ let settled = false;+ const isLatestRequest = () => requestedUserID === controller._ratingUserID &&+ isLatestBazaarRatingRequest(controller._data.userRatingSubmitRequestIDs, requestKey, requestID);+ const settle = (success: boolean) => {+ if (!settled) {+ settled = true;+ callback(success);+ }+ };+ fetchPost("/api/bazaar/setBazaarPackageRating", {+ packageType: bazaarType,+ packageName,+ rating,+ }, response => {+ handled = true;+ controller._syncRatingUser();+ if (!isLatestRequest()) {+ settle(false);+ return;+ }+ if (response.code !== 0 || !response.data) {+ const languageKey = getBazaarRatingErrorLanguageKey(response.data);+ showMessage(languageKey ? window.siyuan.languages[languageKey] :+ response.msg || failureMessage);+ settle(false);+ return;+ }+ const userRating = response.data.userRating;+ controller._data.userRatings.set(key, normalizeBazaarUserRating(userRating) ?? rating);+ controller._data.userRatingKeys.add(key);+ beginBazaarRatingRequest(controller._data.ratingMutationVersions, key);+ const refreshUI = controller._isMountCurrent(mount);+ controller._applyPackageRatingResponse(bazaarType, packageName, response.data, refreshUI);+ const sortValue = window.siyuan.storage[Constants.LOCAL_BAZAAR][BAZAAR_PACKAGE_CONFIG[bazaarType].tabType];+ if (refreshUI && ["4", "5"].includes(sortValue)) {+ controller._renderBazaarCards(+ controller.element.querySelector(`#${BAZAAR_PACKAGE_CONFIG[bazaarType].panelID}`),+ sortBazaarPackages(controller._data[bazaarType], sortValue),+ bazaarType,+ bazaarType === "themes" ? (controller.element.querySelector("#bazaarSelect") as HTMLSelectElement)?.value : undefined,+ );+ }+ showMessage(removing ? window.siyuan.languages.bazaarRatingRemoved :+ window.siyuan.languages.bazaarRatingSubmitted);+ settle(true);+ }).finally(() => {+ controller._data.userRatingSubmittingKeys.delete(requestKey);+ if (settled) {+ return;+ }+ controller._syncRatingUser();+ if (!handled && isLatestRequest()) {+ showMessage(failureMessage);+ }+ settle(false);+ });+};++export const openRatingDialog = (controller: TBazaarController, bazaarType: TBazaarType, packageName: string) => {+ controller._syncRatingUser();+ if (!window.siyuan.user) {+ showMessage(window.siyuan.languages.bazaarRatingLoginTip);+ return;+ }+ const key = controller._getRatingKey(bazaarType, packageName);+ const submitKey = `${controller._ratingUserID}|${key}`;+ if (controller._data.userRatingSubmittingKeys.has(submitKey)) {+ showMessage(window.siyuan.languages.loading);+ return;+ }+ if (!controller._data.userRatingKeys.has(key)) {+ const loadingKey = `${controller._ratingUserID}|${key}`;+ if (controller._data.userRatingLoadingKeys.has(loadingKey)) {+ showMessage(window.siyuan.languages.loading);+ return;+ }+ controller._fetchPackageRating(bazaarType, packageName, () => {+ controller._openRatingDialog(bazaarType, packageName);+ }, false);+ return;+ }+ const previousActiveElement = document.activeElement as HTMLElement;+ let selectedRating = controller._data.userRatings.get(key) || 0;+ const canRemoveRating = isBazaarRatingRemovalAvailable(selectedRating);+ const buttons = [1, 2, 3, 4, 5].map((rating) => {+ const label = window.siyuan.languages.bazaarRatingStarLabel.replace("${star}", rating.toString());+ return `<button type="button" role="radio" data-rating-value="${rating}" aria-checked="${selectedRating === rating}" aria-label="${escapeAttr(label)}" tabindex="${selectedRating === rating || (!selectedRating && rating === 1) ? "0" : "-1"}">+<svg class="config-bazaar__rating-star config-bazaar__rating-star--outline" aria-hidden="true"><use xlink:href="#iconStar"></use></svg>+</button>`;+ }).join("");+ const dialog = new Dialog({+ title: window.siyuan.languages.bazaarRatePackage,+ content: `<div class="b3-dialog__content">+<div class="config-bazaar__rating-picker" role="radiogroup" aria-label="${escapeAttr(window.siyuan.languages.bazaarYourRating)}">${buttons}</div>+</div>+<div class="b3-dialog__action">+${canRemoveRating ? `<button type="button" class="b3-button b3-button--remove" data-type="rating-remove">${window.siyuan.languages.bazaarRemoveRating}</button><div class="fn__space"></div>` : ""}+<button type="button" class="b3-button b3-button--cancel" data-type="rating-cancel">${window.siyuan.languages.cancel}</button>+<div class="fn__space"></div>+<button type="button" class="b3-button b3-button--text" data-type="rating-confirm"${selectedRating ? "" : " disabled"}>${window.siyuan.languages.confirm}</button>+</div>`,+ width: isMobile() ? "92vw" : "360px",+ destroyCallback: () => {+ if (previousActiveElement?.isConnected) {+ previousActiveElement.focus({preventScroll: true});+ }+ },+ });+ const picker = dialog.element.querySelector(".config-bazaar__rating-picker") as HTMLElement;+ const cancelButton = dialog.element.querySelector('[data-type="rating-cancel"]') as HTMLButtonElement;+ const confirmButton = dialog.element.querySelector('[data-type="rating-confirm"]') as HTMLButtonElement;+ const removeButton = dialog.element.querySelector('[data-type="rating-remove"]') as HTMLButtonElement | null;+ let submitting = false;+ const setSubmitting = (value: boolean) => {+ submitting = value;+ picker.querySelectorAll<HTMLButtonElement>("[data-rating-value]").forEach((button) => {+ button.disabled = value;+ });+ if (removeButton) {+ removeButton.disabled = value;+ }+ cancelButton.disabled = value;+ confirmButton.disabled = value || !selectedRating;+ };+ const highlightRating = (rating: number) => {+ picker.querySelectorAll<HTMLButtonElement>("[data-rating-value]").forEach((button) => {+ button.classList.toggle("config-bazaar__rating-picker--active", Number(button.dataset.ratingValue) <= rating);+ });+ };+ const selectRating = (rating: number, focus = false) => {+ if (submitting) {+ return;+ }+ selectedRating = rating;+ highlightRating(rating);+ picker.querySelectorAll<HTMLButtonElement>("[data-rating-value]").forEach((button) => {+ const value = Number(button.dataset.ratingValue);+ button.setAttribute("aria-checked", (value === rating).toString());+ button.tabIndex = value === rating ? 0 : -1;+ if (focus && value === rating) {+ button.focus();+ }+ });+ confirmButton.disabled = false;+ };+ if (selectedRating) {+ selectRating(selectedRating);+ }+ picker.addEventListener("click", (event) => {+ const button = (event.target as HTMLElement).closest<HTMLButtonElement>("[data-rating-value]");+ if (button) {+ selectRating(Number(button.dataset.ratingValue));+ }+ });+ picker.addEventListener("mouseover", (event) => {+ const button = (event.target as HTMLElement).closest<HTMLButtonElement>("[data-rating-value]");+ if (button) {+ highlightRating(Number(button.dataset.ratingValue));+ }+ });+ picker.addEventListener("mouseleave", () => highlightRating(selectedRating));+ picker.addEventListener("keydown", (event: KeyboardEvent) => {+ if (!["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Home", "End"].includes(event.key)) {+ return;+ }+ let next = selectedRating || Number((event.target as HTMLElement).closest<HTMLElement>("[data-rating-value]")?.dataset.ratingValue) || 1;+ if (["ArrowLeft", "ArrowUp"].includes(event.key)) {+ next = next === 1 ? 5 : next - 1;+ } else if (["ArrowRight", "ArrowDown"].includes(event.key)) {+ next = next === 5 ? 1 : next + 1;+ } else {+ next = event.key === "Home" ? 1 : 5;+ }+ selectRating(next, true);+ event.preventDefault();+ });+ cancelButton.addEventListener("click", () => {+ if (!submitting) {+ dialog.destroy();+ }+ });+ removeButton?.addEventListener("click", () => {+ if (submitting) {+ return;+ }+ setSubmitting(true);+ controller._submitPackageRating(bazaarType, packageName, 0, (success) => {+ if (success) {+ dialog.destroy();+ } else {+ setSubmitting(false);+ }+ });+ });+ confirmButton.addEventListener("click", () => {+ if (!selectedRating || submitting) {+ return;+ }+ setSubmitting(true);+ controller._submitPackageRating(bazaarType, packageName, selectedRating, (success) => {+ if (success) {+ dialog.destroy();+ } else {+ setSubmitting(false);+ }+ });+ });+ (picker.querySelector('[tabindex="0"]') as HTMLButtonElement)?.focus({preventScroll: true});+};diff --git a/app/src/plugin/index.ts b/app/src/plugin/index.tsindex a757f44a33..69d00ba2af 100644--- a/app/src/plugin/index.ts+++ b/app/src/plugin/index.ts@@ -655,3 +655,6 @@ export class Plugin {return this.protyleOptionsValue;}}++export const hasPluginSetting = (plugin: Plugin) => Boolean(plugin.setting) ||+ plugin.openSetting !== Plugin.prototype.openSetting;diff --git a/app/src/plugin/openTopBarMenu.ts b/app/src/plugin/openTopBarMenu.tsindex 0cd1340a6e..c5651f92be 100644--- a/app/src/plugin/openTopBarMenu.ts+++ b/app/src/plugin/openTopBarMenu.ts@@ -6,6 +6,7 @@ import {isBazaarAvailable} from "../util/bazaarAvailability";import {setTabPosition} from "../layout/tabUtil";/// #endifimport {Constants} from "../constants";+import {hasPluginSetting} from "./index";export const openTopBarMenu = (app: App, target?: Element) => {const menu = new Menu(Constants.MENU_BAR_PLUGIN);@@ -24,8 +25,7 @@ export const openTopBarMenu = (app: App, target?: Element) => {});let hasPlugin = false;app.plugins.forEach((plugin) => {- // @ts-ignore- const hasSetting = plugin.setting || plugin.__proto__.hasOwnProperty("openSetting");+ const hasSetting = hasPluginSetting(plugin);let hasTopBar = false;for (let i = 0; i < plugin.topBarIcons.length; i++) {const item = plugin.topBarIcons[i];diff --git a/app/src/util/bazaarPackage.test.ts b/app/src/util/bazaarPackage.test.tsindex aa708d3fb0..bcfb377a5f 100644--- a/app/src/util/bazaarPackage.test.ts+++ b/app/src/util/bazaarPackage.test.ts@@ -29,6 +29,7 @@ import {normalizeBazaarPackageUserRatingsResponse,normalizeBazaarRating,normalizeBazaarUserRating,+ sortBazaarPackages,sortBazaarPackagesByRating,} from "./bazaarPackage";@@ -528,6 +529,37 @@ describe("sortBazaarPackagesByRating", () => {});});+describe("sortBazaarPackages", () => {+ const packages = [+ {name: "first", updated: "20260102", downloads: 10},+ {name: "second", updated: "20260103", downloads: 5},+ {name: "third", updated: "20260102", downloads: 10},+ ];++ it("sorts update times in both directions and preserves ties", () => {+ assert.deepEqual(sortBazaarPackages(packages, "0").map((item) => item.name), [+ "second", "first", "third",+ ]);+ assert.deepEqual(sortBazaarPackages(packages, "1").map((item) => item.name), [+ "first", "third", "second",+ ]);+ });++ it("sorts download counts in both directions and preserves ties", () => {+ assert.deepEqual(sortBazaarPackages(packages, "2").map((item) => item.name), [+ "first", "third", "second",+ ]);+ assert.deepEqual(sortBazaarPackages(packages, "3").map((item) => item.name), [+ "second", "first", "third",+ ]);+ });++ it("does not mutate the source order", () => {+ sortBazaarPackages(packages, "0");+ assert.deepEqual(packages.map((item) => item.name), ["first", "second", "third"]);+ });+});+describe("isBazaarPackageRatingLoaded", () => {it("exposes online ratings only when both public indexes are available", () => {assert.equal(isBazaarPackageRatingLoaded("bazaar", false, true), true);diff --git a/app/src/util/bazaarPackage.ts b/app/src/util/bazaarPackage.tsindex 98868a0e22..4f7ce7c1d9 100644--- a/app/src/util/bazaarPackage.ts+++ b/app/src/util/bazaarPackage.ts@@ -301,6 +301,31 @@ export const sortBazaarPackagesByRating = <T extends {return updatedResult || a.index - b.index;}).map(({item}) => item);+export const sortBazaarPackages = <T extends {+ updated: string;+ downloads: number;+ ratingAvailable?: boolean;+ rating?: IBazaarRating;+}>(packages: T[], sortValue: string): T[] => {+ if (["4", "5"].includes(sortValue)) {+ return sortBazaarPackagesByRating(packages, sortValue === "4");+ }+ const indexed = packages.map((item, index) => ({item, index}));+ return indexed.sort((a, b) => {+ let result = 0;+ if (sortValue === "0") {+ result = b.item.updated.localeCompare(a.item.updated);+ } else if (sortValue === "1") {+ result = a.item.updated.localeCompare(b.item.updated);+ } else if (sortValue === "2") {+ result = b.item.downloads - a.item.downloads;+ } else if (sortValue === "3") {+ result = a.item.downloads - b.item.downloads;+ }+ return result || a.index - b.index;+ }).map(({item}) => item);+};+export const isBazaarPackageRatingLoaded = (source: "downloaded" | "updated" | "bazaar",asynchronouslyLoaded: boolean,