An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Unfold flashcards through editor transactions https://github.com/siyuan-note/siyuan/issues/18362
Daniel26764544846a
diff --git a/app/src/card/flashcardMode.test.ts b/app/src/card/flashcardMode.test.tsindex 939224780a..fb0f005bb5 100644--- a/app/src/card/flashcardMode.test.ts+++ b/app/src/card/flashcardMode.test.ts@@ -1,6 +1,13 @@import {describe, it} from "node:test";import * as assert from "node:assert/strict";-import {hideFlashcardAnswer, prepareCalloutFlashcard, showFlashcardAnswer} from "./flashcardMode";+import {+ beginFlashcardLoad,+ createFlashcardRevealState,+ hideFlashcardAnswer,+ prepareCalloutFlashcard,+ revealFlashcardAfterUnfold,+ showFlashcardAnswer+} from "./flashcardMode";const createClassElement = () => {const classes = new Set<string>();@@ -15,15 +22,11 @@ const createClassElement = () => {describe("flashcardMode", () => {it("prepares a top-level callout with an answer", () => {- let removedAttribute = "";const calloutElement = {querySelector(selector: string) {assert.equal(selector, ":scope > .callout-content > [data-node-id]");return {};},- removeAttribute(attribute: string) {- removedAttribute = attribute;- },} as unknown as Element;const wysiwygElement = {querySelector(selector: string) {@@ -33,7 +36,6 @@ describe("flashcardMode", () => {} as unknown as Element;assert.equal(prepareCalloutFlashcard(wysiwygElement, true), true);- assert.equal(removedAttribute, "fold");});it("ignores callouts when the mode is disabled or no direct answer exists", () => {@@ -78,4 +80,82 @@ describe("flashcardMode", () => {showFlashcardAnswer(element);assert.equal(classes.size, 0);});++ it("reveals an unfolded card immediately", () => {+ const state = createFlashcardRevealState();+ const generation = beginFlashcardLoad(state);+ let revealed = 0;++ assert.equal(revealFlashcardAfterUnfold({+ state,+ generation,+ reveal: () => revealed++,+ }), true);+ assert.equal(revealed, 1);+ });++ it("waits for a folded card to finish unfolding", () => {+ const state = createFlashcardRevealState();+ const generation = beginFlashcardLoad(state);+ let done: () => void;+ let revealed = 0;++ assert.equal(revealFlashcardAfterUnfold({+ state,+ generation,+ unfold: (callback) => {+ done = callback;+ },+ reveal: () => revealed++,+ }), true);+ assert.equal(revealed, 0);++ done();+ assert.equal(revealed, 1);+ });++ it("ignores repeated reveals while unfolding", () => {+ const state = createFlashcardRevealState();+ const generation = beginFlashcardLoad(state);+ let done: () => void;+ let revealed = 0;++ revealFlashcardAfterUnfold({+ state,+ generation,+ unfold: (callback) => {+ done = callback;+ },+ reveal: () => revealed++,+ });+ assert.equal(revealFlashcardAfterUnfold({+ state,+ generation,+ reveal: () => revealed++,+ }), false);++ done();+ done();+ assert.equal(revealed, 1);+ });++ it("ignores an unfold callback after loading another card", () => {+ const state = createFlashcardRevealState();+ const generation = beginFlashcardLoad(state);+ let done: () => void;+ let revealed = 0;++ revealFlashcardAfterUnfold({+ state,+ generation,+ unfold: (callback) => {+ done = callback;+ },+ reveal: () => revealed++,+ });+ beginFlashcardLoad(state);+ done();++ assert.equal(revealed, 0);+ });});diff --git a/app/src/card/flashcardMode.ts b/app/src/card/flashcardMode.tsindex d8cdb96de5..5ddba54c1e 100644--- a/app/src/card/flashcardMode.ts+++ b/app/src/card/flashcardMode.ts@@ -1,6 +1,57 @@type FlashcardCreationConfig = Pick<Config.IFlashCard,"blockquote" | "callout" | "heading" | "list" | "mark" | "superBlock">;+export interface IFlashcardRevealState {+ generation: number,+ pendingGeneration?: number,+}++export const createFlashcardRevealState = (): IFlashcardRevealState => ({+ generation: 0,+});++export const beginFlashcardLoad = (state: IFlashcardRevealState) => {+ state.generation++;+ state.pendingGeneration = undefined;+ return state.generation;+};++export const isCurrentFlashcardLoad = (state: IFlashcardRevealState, generation: number) => {+ return state.generation === generation;+};++export const revealFlashcardAfterUnfold = (options: {+ state: IFlashcardRevealState,+ generation: number,+ unfold?: (done: () => void) => void,+ reveal: () => void,+}) => {+ if (!isCurrentFlashcardLoad(options.state, options.generation) ||+ options.state.pendingGeneration === options.generation) {+ return false;+ }+ if (!options.unfold) {+ options.reveal();+ return true;+ }++ options.state.pendingGeneration = options.generation;+ let finished = false;+ options.unfold(() => {+ if (finished) {+ return;+ }+ finished = true;+ if (options.state.pendingGeneration === options.generation) {+ options.state.pendingGeneration = undefined;+ }+ if (isCurrentFlashcardLoad(options.state, options.generation)) {+ options.reveal();+ }+ });+ return true;+};+const FLASHCARD_HIDE_CLASS_ENTRIES: Array<[keyof FlashcardCreationConfig, string]> = [["mark", "card__block--hidemark"],["list", "card__block--hideli"],@@ -33,6 +84,5 @@ export const prepareCalloutFlashcard = (wysiwygElement: Element, enabled: booleaif (!calloutElement?.querySelector(":scope > .callout-content > [data-node-id]")) {return false;}- calloutElement.removeAttribute("fold");return true;};diff --git a/app/src/card/openCard.ts b/app/src/card/openCard.tsindex a2c655cd54..a7d97c4113 100644--- a/app/src/card/openCard.ts+++ b/app/src/card/openCard.ts@@ -26,7 +26,16 @@ import {updateCardHV} from "./util";import {showMessage} from "../dialog/message";import {Menu} from "../plugin/Menu";import {transaction} from "../protyle/wysiwyg/transaction";-import {hideFlashcardAnswer, prepareCalloutFlashcard, showFlashcardAnswer} from "./flashcardMode";+import {+ beginFlashcardLoad,+ createFlashcardRevealState,+ hideFlashcardAnswer,+ isCurrentFlashcardLoad,+ prepareCalloutFlashcard,+ revealFlashcardAfterUnfold,+ showFlashcardAnswer+} from "./flashcardMode";+import {setFold} from "../protyle/util/blockFold";const genCardCount = (cardsData: ICardData, allIndex = 0) => {let newIndex = 0;@@ -156,24 +165,59 @@ export const genCardHTML = (options: {</div>`;};+const flashcardRevealStates = new WeakMap<IProtyle, ReturnType<typeof createFlashcardRevealState>>();++const getFlashcardRevealState = (protyle: IProtyle) => {+ let state = flashcardRevealStates.get(protyle);+ if (!state) {+ state = createFlashcardRevealState();+ flashcardRevealStates.set(protyle, state);+ }+ return state;+};++const showRatingActions = (actionElements: NodeListOf<Element>, currentCard: ICard) => {+ actionElements[0].classList.add("fn__none");+ actionElements[1].querySelectorAll("button.b3-button").forEach((element, btnIndex) => {+ if (btnIndex < 2) {+ return;+ }+ element.previousElementSibling.textContent = currentCard.nextDues[btnIndex - 1];+ });+ actionElements[1].classList.remove("fn__none");+};+const getEditor = (id: string, protyle: IProtyle, element: Element, currentCard: ICard) => {+ const revealState = getFlashcardRevealState(protyle);+ const generation = beginFlashcardLoad(revealState);+ const actionElements = element.querySelectorAll(".card__action");+ actionElements.forEach(item => item.classList.add("fn__none"));+ actionElements[0].querySelectorAll('button[data-type="-1"], button[data-type="-3"]').forEach(item => {+ item.removeAttribute("disabled");+ });fetchPost("/api/block/getDocInfo", {id,}, (docResponse) => {+ if (!isCurrentFlashcardLoad(revealState, generation)) {+ return;+ }protyle.wysiwyg.renderCustom(docResponse.data.ial);fetchPost("/api/filetree/getDoc", {id,mode: 0,- size: Constants.SIZE_GET_MAX,- unfold: true+ size: Constants.SIZE_GET_MAX}, (response) => {+ if (!isCurrentFlashcardLoad(revealState, generation)) {+ return;+ }onGet({updateReadonly: true,data: response,protyle,action: response.data.rootID === response.data.id ? [] : [Constants.CB_GET_ALL],afterCB: () => {- if (protyle.element.classList.contains("fn__none")) {+ if (!isCurrentFlashcardLoad(revealState, generation) ||+ protyle.element.classList.contains("fn__none")) {return;}let hasHide = false;@@ -193,7 +237,6 @@ const getEditor = (id: string, protyle: IProtyle, element: Element, currentCard:if (window.siyuan.config.flashcard.blockquote) {const blockquoteElement = protyle.wysiwyg.element.querySelector(":scope > .bq[custom-riff-decks]");if (blockquoteElement?.querySelector(":scope > [data-node-id] ~ [data-node-id]")) {- blockquoteElement.removeAttribute("fold");hasHide = true;}}@@ -216,17 +259,10 @@ const getEditor = (id: string, protyle: IProtyle, element: Element, currentCard:}}}- const actionElements = element.querySelectorAll(".card__action");if (!hasHide) {- showFlashcardAnswer(protyle.element);- actionElements[0].classList.add("fn__none");- actionElements[1].querySelectorAll("button.b3-button").forEach((element, btnIndex) => {- if (btnIndex < 2) {- return;- }- element.previousElementSibling.textContent = currentCard.nextDues[btnIndex - 1];+ revealFlashcardAnswer(protyle, () => {+ showRatingActions(actionElements, currentCard);});- actionElements[1].classList.remove("fn__none");} else {hideFlashcardAnswer(protyle.element, window.siyuan.config.flashcard);actionElements[0].classList.remove("fn__none");@@ -239,6 +275,30 @@ const getEditor = (id: string, protyle: IProtyle, element: Element, currentCard:};+const revealFlashcardAnswer = (protyle: IProtyle, callback: () => void) => {+ const revealState = getFlashcardRevealState(protyle);+ const generation = revealState.generation;+ const cardElement = protyle.wysiwyg.element.querySelector(+ `[data-node-id="${protyle.block.id}"][fold="1"]`+ );+ revealFlashcardAfterUnfold({+ state: revealState,+ generation,+ unfold: cardElement ? (done) => {+ const foldData = setFold(protyle, cardElement, true, false, true, true);+ if (!foldData.doOperations?.length) {+ done();+ return;+ }+ transaction(protyle, foldData.doOperations, foldData.undoOperations, {callback: done});+ } : undefined,+ reveal: () => {+ showFlashcardAnswer(protyle.element);+ callback();+ }+ });+};+export const bindCardEvent = async (options: {app: App,element: Element,@@ -682,6 +742,12 @@ export const bindCardEvent = async (options: {if (!type || !currentCard) {return;}+ const revealState = getFlashcardRevealState(editor.protyle);+ if (revealState.pendingGeneration === revealState.generation) {+ event.preventDefault();+ event.stopPropagation();+ return;+ }event.preventDefault();event.stopPropagation();hideElements(["toolbar", "hint", "util", "gutter"], editor.protyle);@@ -689,16 +755,16 @@ export const bindCardEvent = async (options: {if (actionElements[0].classList.contains("fn__none")) {type = "3";} else {- showFlashcardAnswer(editor.protyle.element);- actionElements[0].classList.add("fn__none");- actionElements[1].querySelectorAll("button.b3-button").forEach((element, btnIndex) => {- if (btnIndex < 2) {- return;- }- element.previousElementSibling.textContent = currentCard.nextDues[btnIndex - 1];+ revealFlashcardAnswer(editor.protyle, () => {+ showRatingActions(actionElements, currentCard);+ emitEvent(options.app, currentCard, type);});- actionElements[1].classList.remove("fn__none");- emitEvent(options.app, currentCard, type);+ const currentRevealState = getFlashcardRevealState(editor.protyle);+ if (currentRevealState.pendingGeneration === currentRevealState.generation) {+ actionElements[0].querySelectorAll("button").forEach(item => {+ item.setAttribute("disabled", "disabled");+ });+ }return;}} else if (type === "-2") { // 上一步diff --git a/kernel/api/filetree.go b/kernel/api/filetree.goindex c6ac602ecc..ef8111b6da 100644--- a/kernel/api/filetree.go+++ b/kernel/api/filetree.go@@ -1415,10 +1415,6 @@ func getDoc(c *gin.Context) {if nil != highlightArg {highlight = highlightArg.(bool)}- unfold := false- if unfoldArg := arg["unfold"]; nil != unfoldArg {- unfold = unfoldArg.(bool)- }var blockCount intvar content, parentID, parent2ID, rootID, typ string@@ -1431,10 +1427,10 @@ func getDoc(c *gin.Context) {// 加密笔记本的打开文档走 InBox 版(查加密 blocktree + content db)if notebook, ok := arg["notebook"].(string); ok && notebook != "" && model.IsEncryptedBox(notebook) {blockCount, content, parentID, parent2ID, rootID, typ, eof, scroll, boxID, docPath, isBacklinkExpand, keywords, headingNumbers, err =- model.GetDocInBox(startID, endID, id, index, query, queryTypes, querySubTypes, queryMethod, mode, size, isBacklink, originalRefBlockIDs, highlight, unfold, notebook)+ model.GetDocInBox(startID, endID, id, index, query, queryTypes, querySubTypes, queryMethod, mode, size, isBacklink, originalRefBlockIDs, highlight, notebook)} else {blockCount, content, parentID, parent2ID, rootID, typ, eof, scroll, boxID, docPath, isBacklinkExpand, keywords, headingNumbers, err =- model.GetDoc(startID, endID, id, index, query, queryTypes, querySubTypes, queryMethod, mode, size, isBacklink, originalRefBlockIDs, highlight, unfold)+ model.GetDoc(startID, endID, id, index, query, queryTypes, querySubTypes, queryMethod, mode, size, isBacklink, originalRefBlockIDs, highlight)}if errors.Is(err, model.ErrBlockNotFound) {ret.Code = 3diff --git a/kernel/model/file.go b/kernel/model/file.goindex bfa733a3b8..8db2545d55 100644--- a/kernel/model/file.go+++ b/kernel/model/file.go@@ -582,33 +582,14 @@ func ListDocTree(boxID, listPath string, sortMode int, flashcard, showHidden booreturn}-func unfoldBlockForRender(node *ast.Node) {- removeFold := func(root *ast.Node) {- ast.Walk(root, func(n *ast.Node, entering bool) ast.WalkStatus {- if entering {- n.RemoveIALAttr("fold")- n.RemoveIALAttr("heading-fold")- }- return ast.WalkContinue- })- }-- removeFold(node)- if ast.NodeHeading == node.Type {- for _, child := range treenode.HeadingChildren(node) {- removeFold(child)- }- }-}--func GetDoc(startID, endID, id string, index int, query string, queryTypes, querySubTypes map[string]bool, queryMethod, mode int, size int, isBacklink bool, originalRefBlockIDs map[string]string, highlight, unfold bool) (+func GetDoc(startID, endID, id string, index int, query string, queryTypes, querySubTypes map[string]bool, queryMethod, mode int, size int, isBacklink bool, originalRefBlockIDs map[string]string, highlight bool) (blockCount int, dom, parentID, parent2ID, rootID, typ string, eof, scroll bool, boxID, docPath string, isBacklinkExpand bool, keywords []string, headingNumbers map[string]string, err error) {- return GetDocInBox(startID, endID, id, index, query, queryTypes, querySubTypes, queryMethod, mode, size, isBacklink, originalRefBlockIDs, highlight, unfold, "")+ return GetDocInBox(startID, endID, id, index, query, queryTypes, querySubTypes, queryMethod, mode, size, isBacklink, originalRefBlockIDs, highlight, "")}// GetDocInBox 与 GetDoc 一致,但按 boxID 路由到加密 db 或全局 db。// 加密笔记本打开文档时传入 boxID,blocktree/content 查询走加密 db;boxID 为空时 fall-through 全局 db。-func GetDocInBox(startID, endID, id string, index int, query string, queryTypes, querySubTypes map[string]bool, queryMethod, mode int, size int, isBacklink bool, originalRefBlockIDs map[string]string, highlight, unfold bool, boxID string) (+func GetDocInBox(startID, endID, id string, index int, query string, queryTypes, querySubTypes map[string]bool, queryMethod, mode int, size int, isBacklink bool, originalRefBlockIDs map[string]string, highlight bool, boxID string) (blockCount int, dom, parentID, parent2ID, rootID, typ string, eof, scroll bool, boxIDOut, docPath string, isBacklinkExpand bool, keywords []string, headingNumbers map[string]string, err error) {//os.MkdirAll("pprof", 0755)//cpuProfile, _ := os.Create("pprof/GetDoc")@@ -642,9 +623,6 @@ func GetDocInBox(startID, endID, id string, index int, query string, queryTypes,return}}- if unfold {- unfoldBlockForRender(node)- }located := falseisDoc := ast.NodeDocument == node.Typediff --git a/kernel/model/file_unfold_test.go b/kernel/model/file_unfold_test.godeleted file mode 100644index 83c93f986c..0000000000--- a/kernel/model/file_unfold_test.go+++ /dev/null@@ -1,88 +0,0 @@-// SiYuan - Refactor your thinking-// 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 (- "testing"-- "github.com/88250/lute/ast"-)--func TestUnfoldHeadingForRender(t *testing.T) {- root := &ast.Node{Type: ast.NodeDocument}- heading := &ast.Node{Type: ast.NodeHeading, HeadingLevel: 2, ID: "heading"}- paragraph := &ast.Node{Type: ast.NodeParagraph, ID: "paragraph"}- list := &ast.Node{Type: ast.NodeList, ID: "list"}- listItem := &ast.Node{Type: ast.NodeListItem, ID: "list-item"}- nextHeading := &ast.Node{Type: ast.NodeHeading, HeadingLevel: 2, ID: "next-heading"}- for _, node := range []*ast.Node{heading, paragraph, list, listItem, nextHeading} {- node.SetIALAttr("fold", "1")- node.SetIALAttr("heading-fold", "1")- }- list.AppendChild(listItem)- root.AppendChild(heading)- root.AppendChild(paragraph)- root.AppendChild(list)- root.AppendChild(nextHeading)-- nodes, _ := loadNodesByMode(heading, 0, 0, 100, false, true)- if 1 != len(nodes) {- t.Fatalf("folded heading returned %d nodes, want 1", len(nodes))- }-- unfoldBlockForRender(heading)-- nodes, _ = loadNodesByMode(heading, 0, 0, 100, false, true)- if 3 != len(nodes) {- t.Fatalf("unfolded heading returned %d nodes, want 3", len(nodes))- }- for _, node := range []*ast.Node{heading, paragraph, list, listItem} {- if "" != node.IALAttr("fold") || "" != node.IALAttr("heading-fold") {- t.Fatalf("render node [%s] remains folded", node.ID)- }- }- if "1" != nextHeading.IALAttr("fold") || "1" != nextHeading.IALAttr("heading-fold") {- t.Fatal("the following heading fold state was changed")- }-}--func TestUnfoldContainerForRender(t *testing.T) {- list := &ast.Node{Type: ast.NodeList, ID: "list"}- listItem := &ast.Node{Type: ast.NodeListItem, ID: "list-item"}- childList := &ast.Node{Type: ast.NodeList, ID: "child-list"}- childItem := &ast.Node{Type: ast.NodeListItem, ID: "child-item"}- siblingItem := &ast.Node{Type: ast.NodeListItem, ID: "sibling-item"}- for _, node := range []*ast.Node{listItem, childList, childItem, siblingItem} {- node.SetIALAttr("fold", "1")- node.SetIALAttr("heading-fold", "1")- }- childList.AppendChild(childItem)- listItem.AppendChild(childList)- list.AppendChild(listItem)- list.AppendChild(siblingItem)-- unfoldBlockForRender(listItem)-- for _, node := range []*ast.Node{listItem, childList, childItem} {- if "" != node.IALAttr("fold") || "" != node.IALAttr("heading-fold") {- t.Fatalf("render node [%s] remains folded", node.ID)- }- }- if "1" != siblingItem.IALAttr("fold") || "1" != siblingItem.IALAttr("heading-fold") {- t.Fatal("the sibling list item fold state was changed")- }-}