Skip to content

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

:sparkles: Support text styling for selected table cells https://github.com/siyuan-note/siyuan/issues/18500

Danielb23709b48e0e
diff --git a/app/src/protyle/toolbar/Font.ts b/app/src/protyle/toolbar/Font.ts
index e3cba56dfa..a75d875807 100644
--- a/app/src/protyle/toolbar/Font.ts
+++ b/app/src/protyle/toolbar/Font.ts
@@ -70,7 +70,8 @@ export const convertFontSize = (fontSize: string, unit: "px" | "em", baseFontSiz
return fontSize.endsWith("px") ? Math.round(value) + "px" : Math.round(value * base) + "px";
};
-export const appearanceMenu = (protyle: IProtyle, nodeElements?: Element[]) => {
+export const appearanceMenu = (protyle: IProtyle, nodeElements?: Element[],
+ onChange?: (type: string, color?: string) => void) => {
let colorHTML = "";
["", "var(--b3-font-color1)", "var(--b3-font-color2)", "var(--b3-font-color3)", "var(--b3-font-color4)",
"var(--b3-font-color5)", "var(--b3-font-color6)", "var(--b3-font-color7)", "var(--b3-font-color8)",
@@ -136,6 +137,9 @@ export const appearanceMenu = (protyle: IProtyle, nodeElements?: Element[]) => {
lastColorHTML += "</div>";
}
const {fontSize, baseFontSize} = getFontSizeInfo(protyle, nodeElements);
+ const applyFontStyle = (type: string, color?: string) => {
+ fontEvent(protyle, nodeElements, type, color, true, onChange);
+ };
element.innerHTML = `${lastColorHTML}
<div class="fn__hr"></div>
<div data-id="color">${window.siyuan.languages.color}</div>
@@ -200,15 +204,15 @@ export const appearanceMenu = (protyle: IProtyle, nodeElements?: Element[]) => {
const dataType = target.getAttribute("data-type");
if (target.tagName === "BUTTON") {
if (dataType === "style1") {
- fontEvent(protyle, nodeElements, dataType, target.style.backgroundColor + Constants.ZWSP + target.style.color);
+ applyFontStyle(dataType, target.style.backgroundColor + Constants.ZWSP + target.style.color);
} else if (dataType === "fontSize") {
- fontEvent(protyle, nodeElements, dataType, target.textContent.trim());
+ applyFontStyle(dataType, target.textContent.trim());
} else if (dataType === "backgroundColor") {
- fontEvent(protyle, nodeElements, dataType, target.style.backgroundColor);
+ applyFontStyle(dataType, target.style.backgroundColor);
} else if (dataType === "color") {
- fontEvent(protyle, nodeElements, dataType, target.style.color);
+ applyFontStyle(dataType, target.style.color);
} else {
- fontEvent(protyle, nodeElements, dataType);
+ applyFontStyle(dataType);
}
break;
}
@@ -226,7 +230,7 @@ export const appearanceMenu = (protyle: IProtyle, nodeElements?: Element[]) => {
fontSizePXElement.parentElement.classList.add("fn__none");
fontSizeEMElement.parentElement.classList.remove("fn__none");
- fontEvent(protyle, nodeElements, "fontSize", fontSizeEMElement.value + "em");
+ applyFontStyle("fontSize", fontSizeEMElement.value + "em");
} else {
const px = convertFontSize(fontSizeEMElement.value + "em", "px", baseFontSize);
fontSizePXElement.parentElement.setAttribute("aria-label", px);
@@ -234,14 +238,14 @@ export const appearanceMenu = (protyle: IProtyle, nodeElements?: Element[]) => {
fontSizePXElement.parentElement.classList.remove("fn__none");
fontSizeEMElement.parentElement.classList.add("fn__none");
- fontEvent(protyle, nodeElements, "fontSize", fontSizePXElement.value + "px");
+ applyFontStyle("fontSize", fontSizePXElement.value + "px");
}
});
fontSizePXElement.addEventListener("change", function () {
- fontEvent(protyle, nodeElements, "fontSize", fontSizePXElement.value + "px");
+ applyFontStyle("fontSize", fontSizePXElement.value + "px");
});
fontSizeEMElement.addEventListener("change", function () {
- fontEvent(protyle, nodeElements, "fontSize", fontSizeEMElement.value + "em");
+ applyFontStyle("fontSize", fontSizeEMElement.value + "em");
});
fontSizePXElement.addEventListener("input", function () {
fontSizePXElement.parentElement.setAttribute("aria-label", fontSizePXElement.value + "px");
@@ -253,7 +257,7 @@ export const appearanceMenu = (protyle: IProtyle, nodeElements?: Element[]) => {
};
export const fontEvent = (protyle: IProtyle, nodeElements: Element[], type?: string, color?: string,
- focusRange = true) => {
+ focusRange = true, onChange?: (type: string, color?: string) => void) => {
let localFontStyles = window.siyuan.storage[Constants.LOCAL_FONTSTYLES];
if (type) {
localFontStyles.splice(0, 0, `${type}${Constants.ZWSP}${color}`);
@@ -273,6 +277,10 @@ export const fontEvent = (protyle: IProtyle, nodeElements: Element[], type?: str
color = fontStyles.join(Constants.ZWSP);
}
}
+ if (onChange) {
+ onChange(type, color);
+ return;
+ }
if (nodeElements && nodeElements.length > 0) {
updateBatchTransaction(nodeElements, protyle, (e: HTMLElement) => {
if (type === "clear") {
diff --git a/app/src/protyle/toolbar/index.ts b/app/src/protyle/toolbar/index.ts
index 3bfa89b7c4..f6a9c804e9 100644
--- a/app/src/protyle/toolbar/index.ts
+++ b/app/src/protyle/toolbar/index.ts
@@ -12,6 +12,7 @@ import {
getSelectionOffset,
getSelectionPosition,
getUndoFocusContext,
+ IBlockRange,
selectAll
} from "../util/selection";
import {hasClosestBlock, hasClosestByAttribute, hasClosestByClassName, hasClosestByTag} from "../util/hasClosest";
@@ -227,6 +228,11 @@ export class Toolbar {
const nodeElement = hasClosestBlock(range.startContainer);
const endElement = hasClosestBlock(range.endContainer);
const isCrossBlock = !!nodeElement && !!endElement && nodeElement !== endElement;
+ const startCellElement = hasClosestByTag(range.startContainer, "TD") ||
+ hasClosestByTag(range.startContainer, "TH");
+ const endCellElement = hasClosestByTag(range.endContainer, "TD") ||
+ hasClosestByTag(range.endContainer, "TH");
+ const isCrossCell = !!startCellElement && !!endCellElement && startCellElement !== endCellElement;
if (isMobile() || !nodeElement || protyle.disabled || (!isCrossBlock && (
nodeElement.getAttribute("data-type") === "NodeCodeBlock" ||
nodeElement.classList.contains("av") ||
@@ -267,8 +273,8 @@ export class Toolbar {
this.element.querySelectorAll(".protyle-toolbar__item--current").forEach(item => {
item.classList.remove("protyle-toolbar__item--current");
});
- this.element.querySelector('[data-type="a"]')?.toggleAttribute("disabled", isCrossBlock);
- this.element.querySelector('[data-type="block-ref"]')?.toggleAttribute("disabled", isCrossBlock);
+ this.element.querySelector('[data-type="a"]')?.toggleAttribute("disabled", isCrossBlock || isCrossCell);
+ this.element.querySelector('[data-type="block-ref"]')?.toggleAttribute("disabled", isCrossBlock || isCrossCell);
const types = this.getCurrentType();
types.forEach(item => {
if (["search-mark", "a", "block-ref", "virtual-block-ref", "text", "file-annotation-ref", "inline-math",
@@ -353,7 +359,11 @@ export class Toolbar {
if (!endElement) {
return;
}
- if (nodeElement !== endElement) {
+ const startCellElement = hasClosestByTag(this.range.startContainer, "TD") ||
+ hasClosestByTag(this.range.startContainer, "TH");
+ const endCellElement = hasClosestByTag(this.range.endContainer, "TD") ||
+ hasClosestByTag(this.range.endContainer, "TH");
+ if (nodeElement !== endElement || (startCellElement && endCellElement && startCellElement !== endCellElement)) {
if (type === "a") {
return;
}
@@ -375,11 +385,64 @@ export class Toolbar {
["NodeCodeBlock", "NodeAttributeView"]).filter(item =>
!(startsAtBlockEnd && item.editableElement.contains(selectedRange.startContainer)) &&
item.range.toString().split(Constants.ZWSP).join(""));
+ const preserveStart = !ranges.some(item => item.editableElement.contains(selectedRange.startContainer));
+ const preserveEnd = !ranges.some(item => item.editableElement.contains(selectedRange.endContainer));
+
+ return this.setRangesInlineMark(protyle, ranges, type, action, textObj, {
+ focusRange,
+ preserveEnd,
+ preserveStart,
+ selectedRange,
+ });
+ }
+
+ private getTableCellRanges(cellElements: HTMLTableCellElement[]) {
+ const ranges: IBlockRange[] = [];
+ new Set(cellElements).forEach(cellElement => {
+ if (!cellElement.isConnected || cellElement.classList.contains("fn__none")) {
+ return;
+ }
+ const blockElement = hasClosestBlock(cellElement) as HTMLElement;
+ if (!blockElement || blockElement.getAttribute("data-type") !== "NodeTable") {
+ return;
+ }
+ const range = document.createRange();
+ range.selectNodeContents(cellElement);
+ if (!range.toString().split(Constants.ZWSP).join("")) {
+ return;
+ }
+ const position = getSelectionOffset(cellElement, undefined, range);
+ ranges.push({
+ blockElement,
+ editableElement: cellElement,
+ range,
+ start: position.start,
+ end: position.end,
+ });
+ });
+ return ranges;
+ }
+
+ public hasTableCellsInlineMark(cellElements: HTMLTableCellElement[], type: string) {
+ const ranges = this.getTableCellRanges(cellElements);
+ return ranges.length > 0 && ranges.every(item => this.hasInlineMark(item.editableElement, item.range, type));
+ }
+
+ public setTableCellsInlineMark(protyle: IProtyle, cellElements: HTMLTableCellElement[], type: string,
+ textObj?: ITextOption) {
+ return this.setRangesInlineMark(protyle, this.getTableCellRanges(cellElements), type, "range", textObj);
+ }
+
+ private setRangesInlineMark(protyle: IProtyle, ranges: IBlockRange[], type: string, action: "range" | "toolbar",
+ textObj?: ITextOption, options?: {
+ focusRange?: boolean,
+ preserveEnd?: boolean,
+ preserveStart?: boolean,
+ selectedRange?: Range,
+ }) {
if (ranges.length === 0) {
return;
}
- const preserveStart = !ranges.some(item => item.editableElement.contains(selectedRange.startContainer));
- const preserveEnd = !ranges.some(item => item.editableElement.contains(selectedRange.endContainer));
const actionBtn = action === "toolbar" ? this.element.querySelector(`[data-type="${type}"]`) : undefined;
const remove = type === "clear" || actionBtn?.classList.contains("protyle-toolbar__item--current") ||
@@ -425,16 +488,16 @@ export class Toolbar {
}
newNodes.push(...connectedNodes);
});
- }, getUndoFocusContext(protyle.wysiwyg.element, selectedRange, true));
- if (selectionRange) {
- if (preserveStart) {
- selectionRange.setStart(selectedRange.startContainer, selectedRange.startOffset);
+ }, options?.selectedRange ? getUndoFocusContext(protyle.wysiwyg.element, options.selectedRange, true) : undefined);
+ if (selectionRange && options?.selectedRange) {
+ if (options.preserveStart) {
+ selectionRange.setStart(options.selectedRange.startContainer, options.selectedRange.startOffset);
}
- if (preserveEnd) {
- selectionRange.setEnd(selectedRange.endContainer, selectedRange.endOffset);
+ if (options.preserveEnd) {
+ selectionRange.setEnd(options.selectedRange.endContainer, options.selectedRange.endOffset);
}
this.range = selectionRange;
- if (focusRange) {
+ if (options.focusRange) {
focusByRange(this.range);
}
}
diff --git a/app/src/protyle/toolbar/tableCell.ts b/app/src/protyle/toolbar/tableCell.ts
new file mode 100644
index 0000000000..c459fbd91f
--- /dev/null
+++ b/app/src/protyle/toolbar/tableCell.ts
@@ -0,0 +1,106 @@
+import {setPosition} from "../../util/setPosition";
+import {appearanceMenu, fontEvent} from "./Font";
+import {toolbarKeyToMenu} from "./util";
+import {matchHotKey} from "../util/hotKey";
+
+const TABLE_CELL_INLINE_TYPES = ["strong", "em", "u", "s", "mark", "sup", "sub", "kbd", "code"];
+
+const applyTableCellFontStyle = (protyle: IProtyle, cellElements: HTMLTableCellElement[], type: string,
+ color?: string) => {
+ if (type === "clear") {
+ protyle.toolbar.setTableCellsInlineMark(protyle, cellElements, "clear", {type: "text"});
+ } else {
+ protyle.toolbar.setTableCellsInlineMark(protyle, cellElements, "text", {type, color});
+ }
+};
+
+export const openTableCellAppearance = (protyle: IProtyle, cellElements: HTMLTableCellElement[],
+ onApply?: () => void) => {
+ const cells = Array.from(new Set(cellElements)).filter(item => item.isConnected);
+ if (cells.length === 0) {
+ return;
+ }
+ window.siyuan.menus.menu.remove();
+ protyle.toolbar.element.classList.add("fn__none");
+ protyle.toolbar.subElement.innerHTML = "";
+ protyle.toolbar.subElement.style.width = "";
+ protyle.toolbar.subElement.style.padding = "";
+ const fontElement = cells[0].querySelector('[data-type~="text"]') || cells[0];
+ protyle.toolbar.subElement.append(appearanceMenu(protyle, [fontElement], (type, color) => {
+ applyTableCellFontStyle(protyle, cells, type, color);
+ onApply?.();
+ }));
+ protyle.toolbar.subElement.style.zIndex = (++window.siyuan.zIndex).toString();
+ protyle.toolbar.subElement.classList.remove("fn__none");
+ protyle.toolbar.subElementCloseCB = undefined;
+ const rect = cells[0].getBoundingClientRect();
+ setPosition(protyle.toolbar.subElement, rect.left, rect.top);
+};
+
+export const getTableCellTextStyleMenus = (protyle: IProtyle, cellElements: HTMLTableCellElement[],
+ onApply?: () => void): IMenu[] => {
+ const menus: IMenu[] = toolbarKeyToMenu(TABLE_CELL_INLINE_TYPES).map(item => ({
+ icon: item.icon,
+ label: window.siyuan.languages[item.lang],
+ accelerator: item.hotkey,
+ checked: protyle.toolbar.hasTableCellsInlineMark(cellElements, item.name),
+ click: () => {
+ protyle.toolbar.setTableCellsInlineMark(protyle, cellElements, item.name);
+ onApply?.();
+ },
+ }));
+ menus.push({type: "separator"});
+ menus.push({
+ icon: "iconFont",
+ label: window.siyuan.languages.appearance,
+ accelerator: window.siyuan.config.keymap.editor.insert.appearance.custom,
+ click: () => openTableCellAppearance(protyle, cellElements, onApply),
+ });
+ menus.push({
+ icon: "iconClear",
+ label: window.siyuan.languages.clearInline,
+ accelerator: window.siyuan.config.keymap.editor.insert.clearInline.custom,
+ click: () => {
+ protyle.toolbar.setTableCellsInlineMark(protyle, cellElements, "clear");
+ onApply?.();
+ },
+ });
+ return menus;
+};
+
+export const applyTableCellStyleHotkey = (protyle: IProtyle, cellElements: HTMLTableCellElement[],
+ event: KeyboardEvent, onApply?: () => void) => {
+ if (event.repeat || cellElements.length === 0) {
+ return false;
+ }
+ if (matchHotKey(window.siyuan.config.keymap.editor.insert.lastUsed.custom, event)) {
+ fontEvent(protyle, [], undefined, undefined, false, (type, color) => {
+ applyTableCellFontStyle(protyle, cellElements, type, color);
+ onApply?.();
+ });
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ return true;
+ }
+ let handled = false;
+ protyle.options.toolbar.find((item: IMenuItem) => {
+ if (!item.hotkey || !matchHotKey(item.hotkey, event)) {
+ return false;
+ }
+ if (TABLE_CELL_INLINE_TYPES.includes(item.name) || item.name === "clear") {
+ protyle.toolbar.setTableCellsInlineMark(protyle, cellElements, item.name);
+ onApply?.();
+ } else if (item.name === "text") {
+ openTableCellAppearance(protyle, cellElements, onApply);
+ } else {
+ return false;
+ }
+ handled = true;
+ return true;
+ });
+ if (handled) {
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ }
+ return handled;
+};
diff --git a/app/src/protyle/util/tableControl.ts b/app/src/protyle/util/tableControl.ts
index f2a0c7c06f..4052ca0b7c 100644
--- a/app/src/protyle/util/tableControl.ts
+++ b/app/src/protyle/util/tableControl.ts
@@ -20,6 +20,7 @@ import {
getTableResizeCount,
isTableCellContentEmpty,
} from "./tableResize";
+import {applyTableCellStyleHotkey, getTableCellTextStyleMenus} from "../toolbar/tableCell";
type TableSelectionMode = "row" | "column" | "cell";
type TableAddControlType = "add-row" | "add-column" | "add-both";
@@ -417,6 +418,12 @@ export class TableControl {
event.stopImmediatePropagation();
this.openMenu(event.clientX, event.clientY);
}, {capture: true, signal});
+ document.addEventListener("keydown", event => {
+ if (this.selection && !this.protyle.disabled &&
+ applyTableCellStyleHotkey(this.protyle, this.getSelectedCells(), event, () => this.scheduleRender())) {
+ return;
+ }
+ }, {capture: true, signal});
document.addEventListener("keydown", event => {
if (event.key !== "Escape") {
return;
@@ -1281,6 +1288,11 @@ export class TableControl {
}
menu.append(new MenuItem({type: "separator"}).element);
}
+ menu.append(new MenuItem({
+ icon: "iconFont",
+ label: window.siyuan.languages.fontStyle,
+ submenu: getTableCellTextStyleMenus(this.protyle, this.getSelectedCells(), () => this.scheduleRender()),
+ }).element);
menu.append(new MenuItem({
icon: "iconTheme",
label: window.siyuan.languages.colorPrimary,
diff --git a/app/src/protyle/wysiwyg/index.ts b/app/src/protyle/wysiwyg/index.ts
index ed6f877d73..9dcc593d8a 100644
--- a/app/src/protyle/wysiwyg/index.ts
+++ b/app/src/protyle/wysiwyg/index.ts
@@ -110,6 +110,7 @@ import {countBlockWord, countSelectWord} from "../../layout/status";
import {showMessage} from "../../dialog/message";
import {getBacklinkHeadingMore, loadBreadcrumb} from "./renderBacklink";
import {removeSearchMark} from "../toolbar/util";
+import {getTableCellTextStyleMenus} from "../toolbar/tableCell";
import {activeBlur} from "../../mobile/util/keyboardToolbar";
import {commonClick} from "./commonClick";
import {avClick, avContextmenu, updateAVName} from "../render/av/action";
@@ -2457,6 +2458,13 @@ export class WYSIWYG {
}
}).element);
window.siyuan.menus.menu.append(new MenuItem({type: "separator"}).element);
+ window.siyuan.menus.menu.append(new MenuItem({
+ icon: "iconFont",
+ label: window.siyuan.languages.fontStyle,
+ submenu: getTableCellTextStyleMenus(protyle, selectedCellElements, () => {
+ tableSelectElement.removeAttribute("style");
+ }),
+ }).element);
window.siyuan.menus.menu.append(new MenuItem({
icon: "iconTheme",
label: window.siyuan.languages.colorPrimary,
diff --git a/app/src/protyle/wysiwyg/keydown.ts b/app/src/protyle/wysiwyg/keydown.ts
index a8dcdaa6fd..8cd3e8ca3b 100644
--- a/app/src/protyle/wysiwyg/keydown.ts
+++ b/app/src/protyle/wysiwyg/keydown.ts
@@ -43,7 +43,7 @@ import {
} from "./getBlock";
import {isIncludesHotKey, matchHotKey} from "../util/hotKey";
import {enter, softEnter} from "./enter";
-import {clearTableCell, fixTable} from "../util/table";
+import {clearTableCell, fixTable, isIncludeCell} from "../util/table";
import {
transaction,
insertEmptyBlockquote,
@@ -56,6 +56,7 @@ import {
} from "./transaction";
import {getBlockquoteContext, shouldCancelBlockquote} from "./blockquote";
import {fontEvent} from "../toolbar/Font";
+import {applyTableCellStyleHotkey} from "../toolbar/tableCell";
import {
addSubList,
insertEmptyChildList,
@@ -1694,6 +1695,29 @@ export const keydown = (protyle: IProtyle, editorElement: HTMLElement) => {
}
// toolbar action
+ const tableSelectElement = nodeType === "NodeTable" ?
+ nodeElement.querySelector(".table__select") as HTMLElement : undefined;
+ if (tableSelectElement?.clientHeight > 0) {
+ const selectedCellElements: HTMLTableCellElement[] = [];
+ const scrollLeft = nodeElement.firstElementChild.scrollLeft;
+ const scrollTop = nodeElement.querySelector("table").scrollTop;
+ nodeElement.querySelectorAll("th, td").forEach((item: HTMLTableCellElement) => {
+ if (!item.classList.contains("fn__none") && isIncludeCell({
+ tableSelectElement,
+ scrollLeft,
+ scrollTop,
+ item,
+ })) {
+ selectedCellElements.push(item);
+ }
+ });
+ if (applyTableCellStyleHotkey(protyle, selectedCellElements, event, () => {
+ tableSelectElement.removeAttribute("style");
+ })) {
+ protyle.wysiwyg.preventKeyup = true;
+ return true;
+ }
+ }
if (matchHotKey(window.siyuan.config.keymap.editor.insert.lastUsed.custom, event)) {
protyle.toolbar.range = range;
const selectElements: Element[] = Array.from(protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select"));