Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:art: Improve marketplace browsing and package management https://github.com/siyuan-note/siyuan/issues/19058

Daniel08c1f65db2cb
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index ac9535fc2e..d29f0d340d 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,5 @@
{
+ "openStorageLocation": "فتح موقع التخزين",
"moveDocToSameLevel": "نفس المستوى",
"moveDocAsChild": "مستند فرعي",
"editMode": "تبديل الوضع",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index b20cdfdfbe..3dfb4d731e 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,5 @@
{
+ "openStorageLocation": "Speicherort öffnen",
"moveDocToSameLevel": "Gleiche Ebene",
"moveDocAsChild": "Unterdokument",
"editMode": "Modus umschalten",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index f919f46c5a..bb5374f1d2 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,5 @@
{
+ "openStorageLocation": "Open storage location",
"moveDocToSameLevel": "Same level",
"moveDocAsChild": "Child document",
"editMode": "Toggle Mode",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index 891cb65448..ebe20c9b68 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,5 @@
{
+ "openStorageLocation": "Abrir ubicación de almacenamiento",
"moveDocToSameLevel": "Mismo nivel",
"moveDocAsChild": "Subdocumento",
"editMode": "Modo de edición",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 2d6885aeaa..6ccf7c1564 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,5 @@
{
+ "openStorageLocation": "Ouvrir l’emplacement de stockage",
"moveDocToSameLevel": "Même niveau",
"moveDocAsChild": "Sous-document",
"editMode": "Mode Toggle",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index 2eb1e1eff6..4309e0536a 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,5 @@
{
+ "openStorageLocation": "פתיחת מיקום האחסון",
"moveDocToSameLevel": "אותה רמה",
"moveDocAsChild": "מסמך משנה",
"editMode": "החלף מצב",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 13c39ef02b..ce6e1270ee 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,5 @@
{
+ "openStorageLocation": "संग्रहण स्थान खोलें",
"moveDocToSameLevel": "समान स्तर",
"moveDocAsChild": "उप-दस्तावेज़",
"editMode": "मोड बदलें",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index f5a39546fb..7265e0247c 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,5 @@
{
+ "openStorageLocation": "Buka lokasi penyimpanan",
"moveDocToSameLevel": "Tingkat yang sama",
"moveDocAsChild": "Dokumen anak",
"editMode": "Alihkan Mode",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 03df91031c..6f3ac9b54b 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,5 @@
{
+ "openStorageLocation": "Apri percorso di archiviazione",
"moveDocToSameLevel": "Stesso livello",
"moveDocAsChild": "Documento secondario",
"editMode": "Cambia modalità",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index 5972515ed4..fc2e5668eb 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,5 @@
{
+ "openStorageLocation": "保存場所を開く",
"moveDocToSameLevel": "同じ階層",
"moveDocAsChild": "子文書",
"editMode": "編集モードの切り替え",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index db7a8bc8e4..a1108c0af7 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,5 @@
{
+ "openStorageLocation": "저장 위치 열기",
"moveDocToSameLevel": "같은 수준",
"moveDocAsChild": "하위 문서",
"editMode": "모드 전환",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index 84893a885c..fcb235839a 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,5 @@
{
+ "openStorageLocation": "Opslaglocatie openen",
"moveDocToSameLevel": "Hetzelfde niveau",
"moveDocAsChild": "Subdocument",
"editMode": "Modus schakelen",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index e21ab5d51e..78be044cfc 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,5 @@
{
+ "openStorageLocation": "Otwórz lokalizację przechowywania",
"moveDocToSameLevel": "Ten sam poziom",
"moveDocAsChild": "Dokument podrzędny",
"editMode": "Przełącz tryb",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index bb1c2dcd06..140e054be9 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,5 @@
{
+ "openStorageLocation": "Abrir local de armazenamento",
"moveDocToSameLevel": "Mesmo nível",
"moveDocAsChild": "Documento filho",
"editMode": "Alternar Modo",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 4cf7908b2b..4f0112791d 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,5 @@
{
+ "openStorageLocation": "Открыть расположение хранилища",
"moveDocToSameLevel": "Тот же уровень",
"moveDocAsChild": "Дочерний документ",
"editMode": "Переключить режим",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 6e25dbfeba..5f9c990905 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,5 @@
{
+ "openStorageLocation": "Otvoriť umiestnenie úložiska",
"moveDocToSameLevel": "Rovnaká úroveň",
"moveDocAsChild": "Podriadený dokument",
"editMode": "Prepnúť režim",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 4c40f44db2..b305f8116e 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,5 @@
{
+ "openStorageLocation": "เปิดตำแหน่งที่เก็บข้อมูล",
"moveDocToSameLevel": "ระดับเดียวกัน",
"moveDocAsChild": "เอกสารย่อย",
"editMode": "สลับโหมด",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index 3b548d5e5b..ee95ff07ed 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,5 @@
{
+ "openStorageLocation": "Depolama konumunu aç",
"moveDocToSameLevel": "Aynı düzey",
"moveDocAsChild": "Alt belge",
"editMode": "Düzenleme modunu değiştir",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index 2b25df9328..72daf89623 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,5 @@
{
+ "openStorageLocation": "Відкрити розташування сховища",
"moveDocToSameLevel": "Той самий рівень",
"moveDocAsChild": "Дочірній документ",
"editMode": "Перемкнути режим",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index 6c771bcef8..07e68cdf3a 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,5 @@
{
+ "openStorageLocation": "打开存储位置",
"moveDocToSameLevel": "同级文档",
"moveDocAsChild": "子文档",
"editMode": "模式切换",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index 8e8e317b2c..aac44e09c8 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,5 @@
{
+ "openStorageLocation": "開啟儲存位置",
"moveDocToSameLevel": "同級文件",
"moveDocAsChild": "子文件",
"editMode": "模式切換",
diff --git a/app/src/assets/scss/business/_config.scss b/app/src/assets/scss/business/_config.scss
index 2e8e346063..c6c476917e 100644
--- a/app/src/assets/scss/business/_config.scss
+++ b/app/src/assets/scss/business/_config.scss
@@ -409,6 +409,8 @@
&__title {
padding: 16px;
+ background-color: var(--b3-theme-background);
+ background-color: color-mix(in srgb, var(--b3-theme-background) 88%, transparent);
backdrop-filter: blur(8px);
position: sticky;
top: 0;
diff --git a/app/src/config/bazaar.ts b/app/src/config/bazaar.ts
index 1049ccac77..82a205d442 100644
--- a/app/src/config/bazaar.ts
+++ b/app/src/config/bazaar.ts
@@ -47,6 +47,10 @@ import {
refreshVisibleRatingUI,
syncRatingUser,
} from "./bazaar/rating";
+import {
+ filterBazaarPackagesByThemeMode,
+ getNextBazaarCardBatch,
+} from "./bazaar/batchRenderer";
interface IBazaarMountSnapshot {
element: HTMLElement;
@@ -54,6 +58,20 @@ interface IBazaarMountSnapshot {
requestID?: number;
}
+interface IBazaarCardRenderState {
+ container: Element;
+ panel: HTMLElement;
+ cardsElement: HTMLElement;
+ packages: IBazaarItem[];
+ bazaarType: TBazaarType;
+ cursor: number;
+ active: boolean;
+ mount: IBazaarMountSnapshot;
+ observer?: IntersectionObserver;
+ scrollHandler?: () => void;
+ frameID?: number;
+}
+
/** 集市 Tab 挂载(面板页,不走注册表渲染) */
export const mountBazaarTab = (root: HTMLElement, keywords?: string, app?: App) => {
if (isMobile()) {
@@ -113,6 +131,7 @@ export const bazaar = {
_globalPluginStateUnsubscribe: undefined as (() => void) | undefined,
_ratingUserID: "",
_ratingUserChangeHandler: undefined as (() => void) | undefined,
+ _bazaarCardRenderStates: new Map<Element, IBazaarCardRenderState>(),
_activateMount(element: HTMLElement, force = false) {
if (!force && this.element === element) {
return;
@@ -121,6 +140,9 @@ export const bazaar = {
this.element = element;
},
_invalidateMount() {
+ Array.from(this._bazaarCardRenderStates.keys()).forEach((container) => {
+ this._disposeBazaarCardRender(container);
+ });
this._mountGeneration++;
this._updateRequestID++;
this._pluginGlobalRequestID++;
@@ -380,8 +402,17 @@ export const bazaar = {
<span data-position="north" class="ariaLabel block__icon block__icon--show${isBrowser() ? " fn__none" : ""}" data-type="open" aria-label="${window.siyuan.languages.showInFolder}">
<svg><use xlink:href="#iconFolder"></use></svg>
</span>
+ ${bazaar._genOpenStorageHTML(item, bazaarType)}
</div>
</div>`;
+ },
+ _genOpenStorageHTML(item: IBazaarItem, bazaarType: TBazaarType) {
+ if (bazaarType !== "plugins" || !item.hasStorageData) {
+ return "";
+ }
+ return `<span data-position="north" class="ariaLabel block__icon block__icon--show${isBrowser() ? " fn__none" : ""}" data-type="open-storage" aria-label="${window.siyuan.languages.openStorageLocation}">
+ <svg><use xlink:href="#iconDatabase"></use></svg>
+</span>`;
},
_getDetailKey(bazaarType: TBazaarType, packageName: string) {
return `${bazaarType}:${packageName}`;
@@ -596,6 +627,7 @@ ${primaryAction ? '<div class="fn__hr"></div>' : ""}
<span data-position="north" class="ariaLabel block__icon block__icon--show${isBrowser() ? " fn__none" : ""}" data-type="open" aria-label="${window.siyuan.languages.showInFolder}">
<svg><use xlink:href="#iconFolder"></use></svg>
</span>
+ ${bazaar._genOpenStorageHTML(installed, bazaarType)}
${bazaar._genUpdateButtonHTML(available, bazaarType)}
${genRatePackageActionHTML(ratingLoaded, bazaar._data.userRatings.get(ratingKey))}
</div>
@@ -840,6 +872,7 @@ ${primaryAction ? '<div class="fn__hr"></div>' : ""}
<span data-position="north" class="ariaLabel block__icon block__icon--show${isBrowser() ? " fn__none" : ""}" data-type="open" aria-label="${window.siyuan.languages.showInFolder}">
<svg><use xlink:href="#iconFolder"></use></svg>
</span>
+ ${bazaar._genOpenStorageHTML(bazaarItem, bazaarType)}
<span data-position="north" class="ariaLabel block__icon block__icon--show${showSwitch ? "" : " fn__none"}" data-type="switch" aria-label="${window.siyuan.languages.use}">
<svg><use xlink:href="#iconSelect"></use></svg>
</span>
@@ -1270,7 +1303,12 @@ type="checkbox">
_reloadBazaarType(bazaarType: TBazaarType) {
const config = BAZAAR_PACKAGE_CONFIG[bazaarType];
const mount = bazaar._beginBazaarRequest(bazaarType);
- fetchPost(config.api.bazaar, {frontend: getFrontend()}, response => {
+ const keyword = (mount.element.querySelector(
+ `.config-bazaar__panel[data-type="${config.tabType}"] .b3-text-field`) as HTMLInputElement)?.value.trim() || "";
+ fetchPost(config.api.bazaar, {
+ ...(config.bazaarRequestUsesFrontend ? {frontend: getFrontend()} : {}),
+ keyword,
+ }, response => {
if (response.code === 0) {
bazaar._onBazaar(response, bazaarType, mount);
}
@@ -1445,6 +1483,7 @@ type="checkbox">
const panelType = panel.getAttribute("data-type");
const isActive = panelType === layoutTabType;
panel.classList.toggle("fn__none", !isActive);
+ bazaar._setBazaarPanelActive(panel, isActive);
if (isActive && from === "bazaar") {
bazaar._initBazaarPanel(bazaarType, panel as HTMLElement);
}
@@ -1657,20 +1696,127 @@ type="checkbox">
this._bindLocalPackageEvent(app, mount);
bindBazaarEvents(this, app, mount);
},
- _renderBazaarCards(container: Element, packages: IBazaarItem[], bazaarType: TBazaarType, themeModeValue?: string) {
- const htmlParts: string[] = [];
- for (const item of packages) {
- if (bazaarType === "themes" && themeModeValue && themeModeValue !== "2" && (
- (themeModeValue === "0" && item.modes?.includes("dark")) ||
- (themeModeValue === "1" && item.modes?.includes("light"))
- )) {
- continue;
+ _stopBazaarCardWatcher(state: IBazaarCardRenderState) {
+ state.observer?.disconnect();
+ state.observer = undefined;
+ if (state.scrollHandler) {
+ state.panel.removeEventListener("scroll", state.scrollHandler);
+ state.scrollHandler = undefined;
+ }
+ if (state.frameID !== undefined) {
+ window.cancelAnimationFrame(state.frameID);
+ state.frameID = undefined;
+ }
+ },
+ _disposeBazaarCardRender(container: Element) {
+ const state = this._bazaarCardRenderStates.get(container);
+ if (!state) {
+ return;
+ }
+ state.active = false;
+ this._stopBazaarCardWatcher(state);
+ this._bazaarCardRenderStates.delete(container);
+ },
+ _isBazaarCardRenderCurrent(state: IBazaarCardRenderState) {
+ return this._bazaarCardRenderStates.get(state.container) === state &&
+ this._isMountCurrent(state.mount) && state.container.isConnected && state.cardsElement.isConnected;
+ },
+ _scheduleBazaarCardBatch(state: IBazaarCardRenderState) {
+ if (state.frameID !== undefined || !state.active || !this._isBazaarCardRenderCurrent(state)) {
+ return;
+ }
+ state.frameID = window.requestAnimationFrame(() => {
+ state.frameID = undefined;
+ if (state.active && this._isBazaarCardRenderCurrent(state)) {
+ this._appendBazaarCardBatch(state);
+ }
+ });
+ },
+ _watchBazaarCardBatch(state: IBazaarCardRenderState) {
+ if (!state.active || state.cursor >= state.packages.length || !this._isBazaarCardRenderCurrent(state)) {
+ return;
+ }
+ if (typeof window.IntersectionObserver === "function") {
+ if (!state.observer) {
+ state.observer = new IntersectionObserver((entries) => {
+ if (entries.some((entry) => entry.isIntersecting)) {
+ state.observer?.disconnect();
+ this._scheduleBazaarCardBatch(state);
+ }
+ }, {
+ root: state.panel,
+ rootMargin: "640px 0px",
+ });
+ }
+ state.observer.disconnect();
+ const lastCard = state.cardsElement.lastElementChild;
+ if (lastCard) {
+ state.observer.observe(lastCard);
+ }
+ return;
+ }
+ if (!state.scrollHandler) {
+ state.scrollHandler = () => {
+ if (state.panel.scrollTop + state.panel.clientHeight + 640 >= state.panel.scrollHeight) {
+ this._scheduleBazaarCardBatch(state);
+ }
+ };
+ state.panel.addEventListener("scroll", state.scrollHandler, {passive: true});
+ }
+ if (state.panel.clientHeight > 0 &&
+ state.panel.scrollTop + state.panel.clientHeight + 640 >= state.panel.scrollHeight) {
+ this._scheduleBazaarCardBatch(state);
+ }
+ },
+ _appendBazaarCardBatch(state: IBazaarCardRenderState) {
+ if (!this._isBazaarCardRenderCurrent(state)) {
+ return;
+ }
+ const batch = getNextBazaarCardBatch(state.packages, state.cursor);
+ state.cursor = batch.nextCursor;
+ state.cardsElement.insertAdjacentHTML("beforeend", batch.packages.map((item) =>
+ this._genCardHTML(item, state.bazaarType)).join(""));
+ if (batch.complete) {
+ this._stopBazaarCardWatcher(state);
+ } else {
+ this._watchBazaarCardBatch(state);
+ }
+ },
+ _setBazaarPanelActive(panel: Element, active: boolean) {
+ this._bazaarCardRenderStates.forEach((state: IBazaarCardRenderState) => {
+ if (state.panel !== panel) {
+ return;
+ }
+ state.active = active;
+ if (active) {
+ this._watchBazaarCardBatch(state);
+ } else {
+ this._stopBazaarCardWatcher(state);
}
- htmlParts.push(bazaar._genCardHTML(item, bazaarType));
+ });
+ },
+ _renderBazaarCards(container: Element, packages: IBazaarItem[], bazaarType: TBazaarType, themeModeValue?: string) {
+ this._disposeBazaarCardRender(container);
+ const visiblePackages = filterBazaarPackagesByThemeMode(packages, bazaarType, themeModeValue);
+ container.parentElement.querySelector(".counter").textContent = visiblePackages.length.toString();
+ if (visiblePackages.length === 0) {
+ container.innerHTML = `<div class="b3-cards b3-cards--nowrap"><ul class="b3-list b3-list--background"><li class="b3-list--empty">${window.siyuan.languages.emptyContent}</li></ul></div>`;
+ return;
}
- const html = htmlParts.join("");
- container.innerHTML = `<div class="b3-cards${html ? "" : " b3-cards--nowrap"}">${html || `<ul class="b3-list b3-list--background"><li class="b3-list--empty">${window.siyuan.languages.emptyContent}</li></ul>`}</div>`;
- container.parentElement.querySelector(".counter").textContent = htmlParts.length.toString();
+ container.innerHTML = '<div class="b3-cards"></div>';
+ const panel = container.closest(".config-bazaar__panel") as HTMLElement;
+ const state: IBazaarCardRenderState = {
+ container,
+ panel,
+ cardsElement: container.firstElementChild as HTMLElement,
+ packages: visiblePackages,
+ bazaarType,
+ cursor: 0,
+ active: !panel.classList.contains("fn__none"),
+ mount: this._captureMount(),
+ };
+ this._bazaarCardRenderStates.set(container, state);
+ this._appendBazaarCardBatch(state);
},
_onBazaar(response: IWebSocketData, bazaarType: TBazaarType, mount: IBazaarMountSnapshot) {
if (!bazaar._isBazaarRequestCurrent(bazaarType, mount)) {
diff --git a/app/src/config/bazaar/batchRenderer.test.ts b/app/src/config/bazaar/batchRenderer.test.ts
new file mode 100644
index 0000000000..9c5b81235a
--- /dev/null
+++ b/app/src/config/bazaar/batchRenderer.test.ts
@@ -0,0 +1,53 @@
+import {describe, it} from "node:test";
+import * as assert from "node:assert/strict";
+import {
+ BAZAAR_CARD_BATCH_SIZE,
+ filterBazaarPackagesByThemeMode,
+ getNextBazaarCardBatch,
+} from "./batchRenderer";
+
+describe("bazaar card batch renderer", () => {
+ it("returns fixed batches without duplicates or omissions", () => {
+ const packages = Array.from({length: BAZAAR_CARD_BATCH_SIZE * 2 + 3}, (_, index) => index);
+ const first = getNextBazaarCardBatch(packages, 0);
+ const second = getNextBazaarCardBatch(packages, first.nextCursor);
+ const last = getNextBazaarCardBatch(packages, second.nextCursor);
+
+ assert.equal(first.complete, false);
+ assert.equal(second.complete, false);
+ assert.equal(last.complete, true);
+ assert.deepEqual([...first.packages, ...second.packages, ...last.packages], packages);
+ });
+
+ it("handles empty and completed package lists", () => {
+ assert.deepEqual(getNextBazaarCardBatch([], 0), {
+ packages: [],
+ nextCursor: 0,
+ complete: true,
+ });
+ assert.deepEqual(getNextBazaarCardBatch([1, 2], 2), {
+ packages: [],
+ nextCursor: 2,
+ complete: true,
+ });
+ });
+
+ it("filters themes by supported mode and keeps dual-mode themes", () => {
+ const packages = [
+ {name: "light", modes: ["light"]},
+ {name: "dark", modes: ["dark"]},
+ {name: "both", modes: ["light", "dark"]},
+ {name: "missing"},
+ ];
+
+ assert.deepEqual(filterBazaarPackagesByThemeMode(packages, "themes", "0").map((item) => item.name), [
+ "light", "both", "missing",
+ ]);
+ assert.deepEqual(filterBazaarPackagesByThemeMode(packages, "themes", "1").map((item) => item.name), [
+ "dark", "both", "missing",
+ ]);
+ assert.equal(filterBazaarPackagesByThemeMode(packages, "plugins", "0"), packages);
+ assert.equal(filterBazaarPackagesByThemeMode(packages, "themes", "2"), packages);
+ assert.equal(filterBazaarPackagesByThemeMode(packages, "themes", "unknown"), packages);
+ });
+});
diff --git a/app/src/config/bazaar/batchRenderer.ts b/app/src/config/bazaar/batchRenderer.ts
new file mode 100644
index 0000000000..31b2b69ff0
--- /dev/null
+++ b/app/src/config/bazaar/batchRenderer.ts
@@ -0,0 +1,22 @@
+export const BAZAAR_CARD_BATCH_SIZE = 24;
+
+export const filterBazaarPackagesByThemeMode = <T extends {modes?: string[]}>(
+ packages: T[],
+ bazaarType: TBazaarType,
+ themeModeValue?: string,
+) => {
+ if (bazaarType !== "themes" || !["0", "1"].includes(themeModeValue || "")) {
+ return packages;
+ }
+ const themeMode = themeModeValue === "0" ? "light" : "dark";
+ return packages.filter((item) => !item.modes?.length || item.modes.includes(themeMode));
+};
+
+export const getNextBazaarCardBatch = <T>(packages: T[], cursor: number, batchSize = BAZAAR_CARD_BATCH_SIZE) => {
+ const nextCursor = Math.min(cursor + batchSize, packages.length);
+ return {
+ packages: packages.slice(cursor, nextCursor),
+ nextCursor,
+ complete: nextCursor >= packages.length,
+ };
+};
diff --git a/app/src/config/bazaar/events.ts b/app/src/config/bazaar/events.ts
index a8a8e4e544..0df1693df6 100644
--- a/app/src/config/bazaar/events.ts
+++ b/app/src/config/bazaar/events.ts
@@ -131,6 +131,17 @@ const ACTION_HANDLERS = {
/// #endif
return HANDLED;
}) satisfies TBazaarActionHandler,
+ "open-storage": ((context) => {
+ const {installedItem, pkgItem, pkgType} = context;
+ const item = installedItem || pkgItem;
+ if (!item || pkgType !== "plugins" || !item.hasStorageData) {
+ return CONTINUE;
+ }
+ /// #if !BROWSER
+ useShell("openPath", path.join(window.siyuan.config.system.dataDir, "storage", "petal", item.name));
+ /// #endif
+ return HANDLED;
+ }) satisfies TBazaarActionHandler,
"retry-update": ((context) => {
context.controller._checkUpdate(true);
return HANDLED;
@@ -213,9 +224,13 @@ const ACTION_HANDLERS = {
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);
+ const config = BAZAAR_PACKAGE_CONFIG[pkgType];
+ const keyword = (mount.element.querySelector(
+ `.config-bazaar__panel[data-type="${config.tabType}"] .b3-text-field`) as HTMLInputElement)?.value.trim() || "";
fetchPost("/api/bazaar/updateBazaarPackage", {
packageType: pkgType,
packageName,
+ keyword,
frontend: getFrontend()
}, response => {
if (response.code !== 0) {
@@ -448,16 +463,16 @@ const handleLayoutTabClick = (context: IBazaarClickContext, target: HTMLElement)
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");
+ const isActive = type === item.getAttribute("data-type");
+ item.classList.toggle("fn__none", !isActive);
+ controller._setBazaarPanelActive(item, isActive);
+ if (isActive) {
if (type !== "downloaded") {
const bazaarType = getBazaarTypeByTab(type);
if (bazaarType) {
controller._initBazaarPanel(bazaarType, item as HTMLElement);
}
}
- } else {
- item.classList.add("fn__none");
}
});
return HANDLED;
@@ -578,9 +593,10 @@ const bindBazaarSelectEvents = (controller: TBazaarController) => {
controller._reorderDownloadedCards(controller._sortDownloadedPackages(
controller._data.downloadedDefault, selectElement.value));
} else if (selectElement.id === "bazaarSelect") {
+ const sortValue = window.siyuan.storage[Constants.LOCAL_BAZAAR][BAZAAR_PACKAGE_CONFIG.themes.tabType];
controller._renderBazaarCards(
controller.element.querySelector("#configBazaarTheme"),
- controller._data.themes,
+ sortBazaarPackages(controller._data.themes, sortValue),
"themes",
selectElement.value
);
diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.ts
index 708d72a0b2..14f0481ad3 100644
--- a/app/src/types/index.d.ts
+++ b/app/src/types/index.d.ts
@@ -1206,6 +1206,7 @@ interface IBazaarItem {
bazaarIncompatible?: boolean; // 仅插件/主题
enabled?: boolean; // 仅 plugin
userDisabledInPublish?: boolean; // 仅 plugin
+ hasStorageData?: boolean; // 仅插件
modes?: string[]; // 仅 theme
}
diff --git a/kernel/api/bazaar.go b/kernel/api/bazaar.go
index 2e67c1d395..f790b62456 100644
--- a/kernel/api/bazaar.go
+++ b/kernel/api/bazaar.go
@@ -181,11 +181,12 @@ func updateBazaarPackage(c *gin.Context) {
return
}
- var pkgType, packageName, frontend string
+ var pkgType, packageName, frontend, keyword string
if !util.ParseJsonArgs(arg, ret,
util.BindJsonArg("packageType", &pkgType, true, true),
util.BindJsonArg("packageName", &packageName, true, true),
util.BindJsonArg("frontend", &frontend, true, true),
+ util.BindJsonArg("keyword", &keyword, false, false),
) {
return
}
@@ -201,7 +202,7 @@ func updateBazaarPackage(c *gin.Context) {
}
util.PushMsg(model.Conf.Language(69), 3000)
ret.Data = map[string]any{
- "packages": model.GetBazaarPackages(pkgType, frontend, ""),
+ "packages": model.GetBazaarPackages(pkgType, frontend, keyword),
}
}
diff --git a/kernel/bazaar/package.go b/kernel/bazaar/package.go
index 62cb4d824b..bc470f1643 100644
--- a/kernel/bazaar/package.go
+++ b/kernel/bazaar/package.go
@@ -95,6 +95,7 @@ type Package struct {
IconURL string `json:"iconURL"`
Installed bool `json:"installed"`
+ HasStorageData bool `json:"hasStorageData,omitempty"`
Outdated bool `json:"outdated"`
Current bool `json:"current"`
Updated string `json:"updated"`
diff --git a/kernel/cli/cmd/serve.go b/kernel/cli/cmd/serve.go
index bf75d56f2e..f0b67b956c 100644
--- a/kernel/cli/cmd/serve.go
+++ b/kernel/cli/cmd/serve.go
@@ -74,6 +74,7 @@ var serveCmd = &cobra.Command{
sql.SetIndexAssetPath(model.Conf.Search.IndexAssetPath)
model.BootSyncData()
+ model.CleanupEmptyPluginStorageDirs()
model.InitBoxes()
model.LoadFlashcards()
util.LoadAssetsTexts()
diff --git a/kernel/harmony/kernel.go b/kernel/harmony/kernel.go
index dfb3cea598..8ac21f370c 100644
--- a/kernel/harmony/kernel.go
+++ b/kernel/harmony/kernel.go
@@ -145,6 +145,7 @@ func StartKernel(container, appDir, workspaceBaseDir, timezoneID, localIPs, lang
sql.SetIndexAssetPath(model.Conf.Search.IndexAssetPath)
model.BootSyncData()
+ model.CleanupEmptyPluginStorageDirs()
model.InitBoxes()
model.LoadFlashcards()
util.LoadAssetsTexts()
diff --git a/kernel/mobile/kernel.go b/kernel/mobile/kernel.go
index 81de596e35..ea1d56fd80 100644
--- a/kernel/mobile/kernel.go
+++ b/kernel/mobile/kernel.go
@@ -290,6 +290,7 @@ func StartKernel(container, appDir, workspaceBaseDir, timezoneID, localIPs, lang
sql.SetIndexAssetPath(model.Conf.Search.IndexAssetPath)
model.BootSyncData()
+ model.CleanupEmptyPluginStorageDirs()
model.InitBoxes()
model.LoadFlashcards()
util.LoadAssetsTexts()
diff --git a/kernel/model/bazaar.go b/kernel/model/bazaar.go
index 2eba2fb8b4..5c0e4cc9aa 100644
--- a/kernel/model/bazaar.go
+++ b/kernel/model/bazaar.go
@@ -368,6 +368,9 @@ func getInstalledPackages0(pkgType, frontend, keyword string) (installedPackages
for _, info := range installedInfos {
pkg := info.Pkg
+ if pkgType == "plugins" {
+ setPluginStorageData(pkg, info.DirName)
+ }
installPath := filepath.Join(basePath, info.DirName)
baseURLPath := installedPackageBaseURLPath(baseURLPathPrefix, info.DirName)
// 设置本地集市包的通用元数据
diff --git a/kernel/model/plugin_storage.go b/kernel/model/plugin_storage.go
new file mode 100644
index 0000000000..8d8f23483d
--- /dev/null
+++ b/kernel/model/plugin_storage.go
@@ -0,0 +1,143 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package model
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+
+ "github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/bazaar"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+type packageDirContainsFileFunc func(string) (bool, error)
+
+func pluginStoragePath(packageName string) string {
+ return filepath.Join(util.DataDir, "storage", "petal", packageName)
+}
+
+func setPluginStorageData(pkg *bazaar.Package, packageName string) {
+ containsFile, err := bazaar.PackageDirContainsFile(pluginStoragePath(packageName))
+ if err != nil {
+ if !errors.Is(err, os.ErrNotExist) {
+ logging.LogWarnf("read plugin storage directory [%s] failed: %s", pluginStoragePath(packageName), err)
+ }
+ return
+ }
+ pkg.HasStorageData = containsFile
+}
+
+// CleanupEmptyPluginStorageDirs 在插件加载前清理没有任何文件的插件存储目录。
+func CleanupEmptyPluginStorageDirs() {
+ if util.ReadOnly {
+ return
+ }
+ storageRoot := filepath.Join(util.DataDir, "storage", "petal")
+ if err := cleanupEmptyPluginStorageDirs(storageRoot, bazaar.PackageDirContainsFile); err != nil {
+ logging.LogWarnf("cleanup empty plugin storage directories [%s] failed: %s", storageRoot, err)
+ }
+}
+
+func cleanupEmptyPluginStorageDirs(storageRoot string, containsFile packageDirContainsFileFunc) error {
+ rootInfo, err := os.Lstat(storageRoot)
+ if errors.Is(err, os.ErrNotExist) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ if rootInfo.Mode()&os.ModeSymlink != 0 || !rootInfo.IsDir() {
+ return nil
+ }
+
+ entries, err := os.ReadDir(storageRoot)
+ if err != nil {
+ return err
+ }
+ var cleanupErrors []error
+ for _, entry := range entries {
+ isDir, infoErr := isRegularDirectoryEntry(entry)
+ if infoErr != nil {
+ cleanupErrors = append(cleanupErrors, fmt.Errorf("inspect plugin storage directory [%s]: %w", entry.Name(), infoErr))
+ continue
+ }
+ if !isDir || !bazaar.IsValidPackageName(entry.Name()) {
+ continue
+ }
+
+ dirPath := filepath.Join(storageRoot, entry.Name())
+ hasFile, readErr := containsFile(dirPath)
+ if readErr != nil {
+ cleanupErrors = append(cleanupErrors, fmt.Errorf("inspect plugin storage directory [%s]: %w", dirPath, readErr))
+ continue
+ }
+ if hasFile {
+ continue
+ }
+ if _, removeErr := removeEmptyDirectoryTree(dirPath); removeErr != nil {
+ cleanupErrors = append(cleanupErrors, fmt.Errorf("remove empty plugin storage directory [%s]: %w", dirPath, removeErr))
+ }
+ }
+ return errors.Join(cleanupErrors...)
+}
+
+func isRegularDirectoryEntry(entry os.DirEntry) (bool, error) {
+ if entry.Type()&os.ModeSymlink != 0 {
+ return false, nil
+ }
+ info, err := entry.Info()
+ if err != nil {
+ return false, err
+ }
+ return info.IsDir() && info.Mode()&os.ModeSymlink == 0, nil
+}
+
+func removeEmptyDirectoryTree(dirPath string) (removed bool, err error) {
+ entries, err := os.ReadDir(dirPath)
+ if errors.Is(err, os.ErrNotExist) {
+ return true, nil
+ }
+ if err != nil {
+ return false, err
+ }
+ for _, entry := range entries {
+ isDir, infoErr := isRegularDirectoryEntry(entry)
+ if infoErr != nil {
+ return false, infoErr
+ }
+ if !isDir {
+ return false, nil
+ }
+ childRemoved, removeErr := removeEmptyDirectoryTree(filepath.Join(dirPath, entry.Name()))
+ if removeErr != nil {
+ return false, removeErr
+ }
+ if !childRemoved {
+ return false, nil
+ }
+ }
+ if err = os.Remove(dirPath); errors.Is(err, os.ErrNotExist) {
+ return true, nil
+ }
+ if err != nil {
+ return false, err
+ }
+ return true, nil
+}
diff --git a/kernel/model/plugin_storage_test.go b/kernel/model/plugin_storage_test.go
new file mode 100644
index 0000000000..35e8549d4a
--- /dev/null
+++ b/kernel/model/plugin_storage_test.go
@@ -0,0 +1,204 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package model
+
+import (
+ "errors"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/bazaar"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestGetInstalledPackagesReportsPluginStorageData(t *testing.T) {
+ originalConf, originalDataDir := Conf, util.DataDir
+ Conf, util.DataDir = NewAppConf(), t.TempDir()
+ t.Cleanup(func() {
+ Conf, util.DataDir = originalConf, originalDataDir
+ })
+
+ pluginsPath := filepath.Join(util.DataDir, "plugins")
+ for _, name := range []string{"with-data", "empty-data"} {
+ pluginPath := filepath.Join(pluginsPath, name)
+ if err := os.MkdirAll(pluginPath, 0755); err != nil {
+ t.Fatal(err)
+ }
+ manifest := []byte(`{"name":"` + name + `","version":"1.0.0","minAppVersion":"0.0.1"}`)
+ if err := os.WriteFile(filepath.Join(pluginPath, "plugin.json"), manifest, 0644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ invalidPath := filepath.Join(pluginsPath, "invalid-package")
+ if err := os.MkdirAll(invalidPath, 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(invalidPath, "index.js"), nil, 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ storageRoot := filepath.Join(util.DataDir, "storage", "petal")
+ for _, name := range []string{"with-data", "empty-data", "invalid-package"} {
+ if err := os.MkdirAll(filepath.Join(storageRoot, name, "nested"), 0755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := os.WriteFile(filepath.Join(storageRoot, "with-data", "nested", "empty.json"), nil, 0644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(storageRoot, "invalid-package", "nested", "data.json"), nil, 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ packages := getInstalledPackages0("plugins", "", "")
+ got := make(map[string]*bazaar.Package, len(packages))
+ for _, pkg := range packages {
+ got[pkg.Name] = pkg
+ }
+ if len(got) != 3 {
+ t.Fatalf("expected three installed packages, got %#v", got)
+ }
+ if pkg := got["with-data"]; pkg == nil || !pkg.HasStorageData {
+ t.Fatal("expected an empty file to mark plugin storage as containing data")
+ }
+ if pkg := got["empty-data"]; pkg == nil || pkg.HasStorageData {
+ t.Fatal("expected a nested empty directory not to mark plugin storage as containing data")
+ }
+ if pkg := got["invalid-package"]; pkg == nil || !pkg.HasStorageData || pkg.InvalidReason == "" {
+ t.Fatal("expected an invalid installed plugin to retain its storage data state")
+ }
+}
+
+func TestCleanupEmptyPluginStorageDirs(t *testing.T) {
+ storageRoot := filepath.Join(t.TempDir(), "storage", "petal")
+ for _, relativePath := range []string{
+ "empty/nested/deep",
+ "nonempty/unused-empty-dir",
+ "zero-byte/nested",
+ ".unmanaged/nested",
+ } {
+ if err := os.MkdirAll(filepath.Join(storageRoot, filepath.FromSlash(relativePath)), 0755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := os.WriteFile(filepath.Join(storageRoot, "nonempty", "data.json"), []byte("data"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(storageRoot, "zero-byte", "nested", "empty.json"), nil, 0644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(storageRoot, "petals.json"), []byte("[]"), 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := cleanupEmptyPluginStorageDirs(storageRoot, bazaar.PackageDirContainsFile); err != nil {
+ t.Fatal(err)
+ }
+ assertPathMissing(t, filepath.Join(storageRoot, "empty"))
+ for _, relativePath := range []string{"nonempty", "zero-byte", ".unmanaged", "petals.json"} {
+ assertPathExists(t, filepath.Join(storageRoot, relativePath))
+ }
+}
+
+func TestCleanupEmptyPluginStorageDirsPreservesUnreadableAndActiveDirs(t *testing.T) {
+ storageRoot := filepath.Join(t.TempDir(), "storage", "petal")
+ for _, name := range []string{"unreadable", "active"} {
+ if err := os.MkdirAll(filepath.Join(storageRoot, name), 0755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ readErr := errors.New("read denied")
+ containsFile := func(dirPath string) (bool, error) {
+ switch filepath.Base(dirPath) {
+ case "unreadable":
+ return false, readErr
+ case "active":
+ if err := os.WriteFile(filepath.Join(dirPath, "late-data.json"), []byte("data"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ return false, nil
+ default:
+ return bazaar.PackageDirContainsFile(dirPath)
+ }
+ }
+
+ err := cleanupEmptyPluginStorageDirs(storageRoot, containsFile)
+ if !errors.Is(err, readErr) {
+ t.Fatalf("expected the inspection error to be returned, got %v", err)
+ }
+ assertPathExists(t, filepath.Join(storageRoot, "unreadable"))
+ assertPathExists(t, filepath.Join(storageRoot, "active", "late-data.json"))
+}
+
+func TestCleanupEmptyPluginStorageDirsPreservesSymlinks(t *testing.T) {
+ root := t.TempDir()
+ storageRoot := filepath.Join(root, "storage", "petal")
+ targetPath := filepath.Join(root, "external")
+ if err := os.MkdirAll(targetPath, 0755); err != nil {
+ t.Fatal(err)
+ }
+ linkPath := filepath.Join(storageRoot, "linked-plugin")
+ if err := os.MkdirAll(storageRoot, 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(targetPath, linkPath); err != nil {
+ t.Skipf("symbolic links are unavailable: %v", err)
+ }
+
+ if err := cleanupEmptyPluginStorageDirs(storageRoot, bazaar.PackageDirContainsFile); err != nil {
+ t.Fatal(err)
+ }
+ assertPathExists(t, linkPath)
+ assertPathExists(t, targetPath)
+}
+
+func TestCleanupEmptyPluginStorageDirsHandlesMissingRoot(t *testing.T) {
+ storageRoot := filepath.Join(t.TempDir(), "missing")
+ if err := cleanupEmptyPluginStorageDirs(storageRoot, bazaar.PackageDirContainsFile); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestCleanupEmptyPluginStorageDirsSkipsReadOnlyMode(t *testing.T) {
+ originalDataDir, originalReadOnly := util.DataDir, util.ReadOnly
+ util.DataDir, util.ReadOnly = t.TempDir(), true
+ t.Cleanup(func() {
+ util.DataDir, util.ReadOnly = originalDataDir, originalReadOnly
+ })
+
+ emptyDir := pluginStoragePath("empty-plugin")
+ if err := os.MkdirAll(filepath.Join(emptyDir, "nested"), 0755); err != nil {
+ t.Fatal(err)
+ }
+ CleanupEmptyPluginStorageDirs()
+ assertPathExists(t, emptyDir)
+}
+
+func assertPathExists(t *testing.T, path string) {
+ t.Helper()
+ if _, err := os.Lstat(path); err != nil {
+ t.Fatalf("expected path [%s] to exist: %v", path, err)
+ }
+}
+
+func assertPathMissing(t *testing.T, path string) {
+ t.Helper()
+ if _, err := os.Lstat(path); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("expected path [%s] to be missing, got %v", path, err)
+ }
+}