Address review feedback on table filtering

This commit is contained in:
Tom Moor committed 2026-11-17 20:35:03 -05:00
1 parent 99978cfe70
commit f0d15fb939
12 files changed
+289 -81

No files matched your search

+2
View File
@@ -234,6 +234,7 @@ function MobileSelect(props: MobileSelectProps) {
optionsHaveIcon,
displayValue: _displayValue,
resolvedDisplayValue,
onCloseAutoFocus,
...triggerProps
} = props;
@@ -328,6 +329,7 @@ function MobileSelect(props: MobileSelectProps) {
aria-label={label}
onAnimationStart={disablePointerEvents}
onAnimationEnd={enablePointerEvents}
onCloseAutoFocus={onCloseAutoFocus}
>
<DrawerTitle hidden={!label}>{label}</DrawerTitle>
<StyledScrollable hiddenScrollbars>
+6 -2
View File
@@ -26,7 +26,7 @@ function DrawerContent(
ref?: React.Ref<React.ComponentRef<typeof DrawerPrimitive.Content>>;
}
) {
const { ref, children, ...rest } = props;
const { ref, children, onCloseAutoFocus, ...rest } = props;
const [measureRef, bounds] = useMeasure();
return (
@@ -34,7 +34,11 @@ function DrawerContent(
<DrawerPrimitive.Overlay asChild>
<Overlay />
</DrawerPrimitive.Overlay>
<DrawerPrimitive.Content ref={ref} asChild>
<DrawerPrimitive.Content
ref={ref}
asChild
onCloseAutoFocus={onCloseAutoFocus}
>
<StyledContent
animate={
bounds.height
+26 -3
View File
@@ -169,7 +169,7 @@ export const TableFilterMenu = observer(function TableFilterMenu() {
onInteractOutside={handleInteractOutside}
onCloseAutoFocus={handleCloseAutoFocus}
>
<TableFilterForm target={open} />
<TableFilterForm key={`${open.pos}:${open.column}`} target={open} />
</PopoverContent>
</Popover>
)}
@@ -193,6 +193,7 @@ const TableFilterForm = observer(function TableFilterForm({
null
);
const focusTextOnClose = React.useRef(false);
const discardText = React.useRef(false);
// Narrow reads, so that the menu only renders when this table changes.
const table = useComputed(() => {
@@ -271,6 +272,9 @@ const TableFilterForm = observer(function TableFilterForm({
const isSameKind =
isListOperator(operator) === isListOperator(filter.operator) &&
isTextOperator(operator) === isTextOperator(filter.operator);
// Leaving a text condition drops text that is not yet applied, and a new
// text field starts without it.
discardText.current = !isSameKind && isTextOperator(filter.operator);
update({
...filter,
operator,
@@ -306,6 +310,7 @@ const TableFilterForm = observer(function TableFilterForm({
};
const handleClear = () => {
discardText.current = true;
update(undefined);
};
@@ -345,6 +350,7 @@ const TableFilterForm = observer(function TableFilterForm({
ref={textInputRef}
value={filter.values[0] ?? ""}
onChange={handleTextChange}
discard={discardText}
/>
)}
{hasValues &&
@@ -416,15 +422,22 @@ const TableFilterForm = observer(function TableFilterForm({
type FilterTextInputProps = {
/** The text of the filter. */
value: string;
/** Called with the text once the reader stops typing. */
/** Called with the text once the reader stops typing, or the field closes. */
onChange: (text: string) => void;
/** Set to true to drop text that is not yet applied when the field closes. */
discard: React.RefObject<boolean>;
ref?: React.Ref<HTMLInputElement | HTMLTextAreaElement>;
};
/** The time to wait after the last key press before the table is filtered. */
const TextFilterWait = 200;
function FilterTextInput({ value, onChange, ref }: FilterTextInputProps) {
function FilterTextInput({
value,
onChange,
discard,
ref,
}: FilterTextInputProps) {
const { t } = useTranslation();
const [text, setText] = React.useState(value);
const debouncedText = useDebouncedValue(text, TextFilterWait);
@@ -434,10 +447,20 @@ function FilterTextInput({ value, onChange, ref }: FilterTextInputProps) {
}
});
// Closing the menu removes the field before the wait ends, so the last text
// is applied then, unless it was cleared.
const handleClose = React.useEffectEvent(() => {
if (!discard.current && text !== value) {
onChange(text);
}
});
React.useEffect(() => {
handleDebouncedChange(debouncedText);
}, [debouncedText]);
React.useEffect(() => () => handleClose(), []);
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setText(event.target.value);
};
+8 -1
View File
@@ -1,8 +1,11 @@
import type { Plugin } from "prosemirror-state";
import Extension from "@shared/editor/lib/Extension";
import { TableFilterPlugin } from "@shared/editor/plugins/TableFilterPlugin";
import { TableFilterMenu } from "../components/TableFilterMenu";
/**
* Shows the menu to filter the rows of a table, in reading and editing mode.
* Filters the rows of tables, and shows the menu to change the filters, in
* reading and editing mode. Editors without this extension show every row.
*/
export default class TableFilterExtension extends Extension {
get name() {
@@ -13,5 +16,9 @@ export default class TableFilterExtension extends Extension {
return true;
}
get plugins(): Plugin[] {
return [new TableFilterPlugin()];
}
widget = () => <TableFilterMenu />;
}
+7 -2
View File
@@ -27,6 +27,7 @@ import { parseDate } from "../../utils/date";
import { isIPv4Address, parseIPv4 } from "../../utils/ip";
import { chainTransactions } from "../lib/chainTransactions";
import {
getFilteredTableRows,
openTableFilterMenu,
remapTableColumnFilters,
} from "../plugins/TableFilterPlugin";
@@ -614,8 +615,12 @@ export function deleteRows(): Command {
}
const rect = selectedRect(state);
const rows = getAllSelectedRows(state);
if (rows.length >= rect.map.height) {
// A selection across rows that a filter hides does not delete them, as the
// reader cannot see them.
const filtered = getFilteredTableRows(state, rect.tableStart - 1);
const rows = getAllSelectedRows(state).filter((row) => !filtered.has(row));
if (!rows.length || rows.length >= rect.map.height) {
return false;
}
+19 -8
View File
@@ -2737,8 +2737,12 @@ table .${EditorStyleHelper.table} > .${EditorStyleHelper.tableScrollable} > tabl
display: none;
}
// Buttons without a filter are transparent rather than hidden, so that they
// stay in the tab order and are announced by screen readers.
.${EditorStyleHelper.tableFilterButton} {
display: none;
display: block;
opacity: 0;
pointer-events: none;
position: absolute;
top: 50%;
inset-inline-end: 4px;
@@ -2757,7 +2761,7 @@ table .${EditorStyleHelper.table} > .${EditorStyleHelper.tableScrollable} > tabl
content: "";
position: absolute;
inset: 2px;
background-color: ${props.theme.text};
background-color: currentColor;
mask: url("data:image/svg+xml;base64,${btoa(
'<svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><rect x="5" y="7" width="14" height="2" rx="1"/><rect x="7.5" y="11" width="9" height="2" rx="1"/><rect x="10" y="15" width="4" height="2" rx="1"/></svg>'
)}") center / contain no-repeat;
@@ -2768,9 +2772,15 @@ table .${EditorStyleHelper.table} > .${EditorStyleHelper.tableScrollable} > tabl
background: ${props.theme.backgroundSecondary};
}
&.active::before {
background-color: ${props.theme.text};
}
&.active,
&.expanded {
display: block;
&.expanded,
&:focus-visible {
opacity: 1;
pointer-events: auto;
}
@media print {
@@ -2778,9 +2788,9 @@ table .${EditorStyleHelper.table} > .${EditorStyleHelper.tableScrollable} > tabl
}
}
th:hover > .${EditorStyleHelper.tableFilterButton},
.${EditorStyleHelper.tableFilterButton}:focus-visible {
display: block;
th:hover > .${EditorStyleHelper.tableFilterButton} {
opacity: 1;
pointer-events: auto;
}
// Without hover, readers have no column menu to filter from.
@@ -2789,7 +2799,8 @@ ${
? `
@media (hover: none) {
.${EditorStyleHelper.tableFilterButton} {
display: block;
opacity: 1;
pointer-events: auto;
}
}
`
+7 -4
View File
@@ -1,13 +1,16 @@
import type { EditorView } from "prosemirror-view";
/**
* Focus the editor if it does not have focus, for controls such as the table
* grips that stay visible while focus is elsewhere.
* Focus the editor if focus is elsewhere, for controls such as the table grips
* that stay visible while focus is elsewhere. Focus in an open menu stays
* there, as moving it would close the menu.
*
* @param view The editor view.
*/
export function focusEditor(view: EditorView): void {
if (!view.hasFocus()) {
view.focus();
const { activeElement } = view.dom.ownerDocument;
if (view.hasFocus() || activeElement?.closest("[role='menu']")) {
return;
}
view.focus();
}
+79 -8
View File
@@ -43,10 +43,26 @@ export function toFilterKey(value: string): string {
* @returns the text of the cell.
*/
export function getCellValue(cell: Node): string {
return cell
.textBetween(0, cell.content.size, " ")
.replace(/\s+/g, " ")
.trim();
const parts: string[] = [];
cell.descendants((node) => {
if (node.isText) {
parts.push(node.text ?? "");
return false;
}
// Inline atoms such as emoji can have no text content, so they are read
// from their leaf text.
const { leafText } = node.type.spec;
if (node.isInline && leafText && !node.textContent) {
parts.push(leafText(node));
return false;
}
if (node.isBlock && parts.length) {
parts.push(" ");
}
return true;
});
return parts.join("").replace(/\s+/g, " ").trim();
}
/**
@@ -166,8 +182,9 @@ export function isEqualTableFilters(a: TableFilter[], b: TableFilter[]) {
}
/**
* Whether a table can be filtered. The first row is the header, so a table
* needs another row, and cells that span rows cannot be hidden on their own.
* Whether a table can be filtered. The table needs a header row with one cell
* for each column and at least one other row, and cells that span rows cannot
* be hidden on their own.
*
* @param table the table node.
* @returns true if the table can be filtered.
@@ -179,8 +196,15 @@ export function isTableFilterable(table: Node): boolean {
for (let row = 0; row < table.childCount; row++) {
const cells = table.child(row);
for (let cell = 0; cell < cells.childCount; cell++) {
if (cells.child(cell).attrs.rowspan > 1) {
for (let index = 0; index < cells.childCount; index++) {
const cell = cells.child(index);
if (cell.attrs.rowspan > 1) {
return false;
}
if (
row === 0 &&
(cell.type.spec.tableRole !== "header_cell" || cell.attrs.colspan > 1)
) {
return false;
}
}
@@ -188,6 +212,53 @@ export function isTableFilterable(table: Node): boolean {
return true;
}
/**
* Get the text of each header cell of a table, by column.
*
* @param table the table node.
* @returns the text of the header of each column.
*/
export function getTableHeaders(table: Node): string[] {
const map = TableMap.get(table);
return Array.from({ length: map.width }, (_, column) => {
const cell = table.nodeAt(map.map[column]);
return cell ? toFilterKey(getCellValue(cell)) : "";
});
}
/**
* Create a function that finds where a column of a table went after a change
* that may have moved, added or removed columns, by matching header text.
*
* @param before the table before the change.
* @param after the table after the change.
* @returns returns the new index of a column, or undefined if it is not found.
*/
export function mapTableColumnsByHeader(
before: Node,
after: Node
): (column: number) => number | undefined {
const old = getTableHeaders(before);
const next = getTableHeaders(after);
if (old.length === next.length && old.every((key, i) => key === next[i])) {
return (column) => column;
}
return (column) => {
const key = old[column];
const matches = next.flatMap((k, i) => (k === key ? [i] : []));
if (matches.length === 1 && old.filter((k) => k === key).length === 1) {
return matches[0];
}
// A header whose text changed stays at its index, if nothing moved there.
if (column < next.length && !old.includes(next[column])) {
return column;
}
return undefined;
};
}
/**
* Get the rows of a table that the filters hide. The header row is never
* hidden. The table must be filterable.
-2
View File
@@ -44,7 +44,6 @@ import {
} from "../commands/table";
import type { MarkdownSerializerState } from "../lib/markdown/serializer";
import { FixTablesPlugin } from "../plugins/FixTablesPlugin";
import { TableFilterPlugin } from "../plugins/TableFilterPlugin";
import { TableColumnResizePlugin } from "../plugins/TableColumnResizePlugin";
import { TableLayoutPlugin } from "../plugins/TableLayoutPlugin";
import tablesRule from "../rules/tables";
@@ -181,7 +180,6 @@ export default class Table extends Node {
new TableColumnResizePlugin(),
new FixTablesPlugin(),
new TableLayoutPlugin(),
new TableFilterPlugin(),
];
}
}
+1 -1
View File
@@ -529,11 +529,11 @@ export default class TableHeader extends Node {
const colIndex = Number(
targetGripColumn.getAttribute("data-index")
);
focusEditor(view);
selectColumn(colIndex, event.metaKey || event.shiftKey)(
view.state,
view.dispatch
);
focusEditor(view);
// Setup drag tracking for potential drag operation
setupColumnDragTracking(view, targetGripColumn, colIndex);
+2 -2
View File
@@ -387,8 +387,8 @@ export default class TableRow extends Node {
if (tableGrip) {
event.preventDefault();
event.stopImmediatePropagation();
focusEditor(view);
selectTable()(view.state, view.dispatch);
focusEditor(view);
return true;
}
@@ -402,11 +402,11 @@ export default class TableRow extends Node {
const rowIndex = Number(
targetGripRow.getAttribute("data-index")
);
focusEditor(view);
selectRow(rowIndex, event.metaKey || event.shiftKey)(
view.state,
view.dispatch
);
focusEditor(view);
// Setup drag tracking for potential drag operation
setupRowDragTracking(view, targetGripRow, rowIndex);
+132 -48
View File
@@ -8,14 +8,15 @@ import { isRemoteTransaction } from "../lib/multiplayer";
import { cellWidget } from "../lib/table";
import {
getHiddenTableRows,
getTableHeaders,
isEqualTableFilters,
isTableFilterActive,
isTableFilterable,
mapTableColumnsByHeader,
parseTableFilters,
remapTableFilters,
} from "../lib/tableFilter";
import { findChildren } from "../queries/findChildren";
import { findParentNodeClosestToPos } from "../queries/findParentNode";
import { isInlineTransaction } from "../queries/isInlineTransaction";
import { hasTableRole } from "../queries/table";
import { EditorStyleHelper } from "../styles/EditorStyleHelper";
@@ -68,8 +69,8 @@ type TableFilterAction =
/** The inputs and outputs of a build of table decorations. */
interface BuildContext {
/** The position of the row that holds the selection. */
selectionRow: number | null;
/** The positions of the rows that hold the selection. */
selectionRows: ReadonlySet<number>;
/** The filters of the current reader. */
local: ReadonlyMap<number, TableFilter[]>;
/** The column whose filter menu is open. */
@@ -152,6 +153,38 @@ export function closeTableFilterMenu(tr: Transaction): Transaction {
return setAction(tr, { type: "close" });
}
/**
* Get the rows of a table that filters hide from the current reader.
*
* @param state the editor state.
* @param pos the position of the table.
* @returns the indexes of the hidden rows.
*/
export function getFilteredTableRows(
state: EditorState,
pos: number
): Set<number> {
const rows = new Set<number>();
const table = state.doc.nodeAt(pos);
const decorations = tableFilterPluginKey.getState(state)?.decorations;
if (!table || !decorations) {
return rows;
}
const filtered = decorations.find(
pos + 1,
pos + table.nodeSize - 1,
(spec) => !!spec.filtered
);
table.forEach((_row, offset, index) => {
const rowPos = pos + 1 + offset;
if (filtered.some((decoration) => decoration.from === rowPos)) {
rows.add(index);
}
});
return rows;
}
/**
* A plugin that hides the rows of tables that do not meet their filters. The
* filters saved on a table apply for everyone, and each reader can change them
@@ -164,7 +197,7 @@ export class TableFilterPlugin extends Plugin<TableFilterPluginState> {
state: {
init: (_, state) => {
const context: BuildContext = {
selectionRow: getSelectionRow(state),
selectionRows: getSelectionRows(state),
local: new Map(),
open: null,
decorations: [],
@@ -231,24 +264,48 @@ function apply(
const isRemote = isRemoteTransaction(tr, state);
const mapPos = createPositionMapper(tr, isRemote);
// Undo and remote edits can change the columns without a remap, so the
// filters of the reader no longer match their columns.
local = mapKeys(local, mapPos, (pos, next) => {
const isStructural = isRemote || !isInlineTransaction(tr, hasTableRole);
// Undo and remote edits can move columns without a remap, so the columns
// of the filters of the reader are found again by their header.
const mapColumns = (pos: number, next: number) => {
const before = tr.before.nodeAt(pos);
const after = tr.doc.nodeAt(next);
return (
action?.type === "remap" ||
return action?.type === "remap" ||
!isStructural ||
!before ||
!after ||
TableMap.get(before).width === TableMap.get(after).width
);
});
before === after
? undefined
: mapTableColumnsByHeader(before, after);
};
const openPos = open ? mapPos(open.pos) : undefined;
open = open && openPos !== undefined ? { ...open, pos: openPos } : null;
if (local.size) {
const next = new Map<number, TableFilter[]>();
local.forEach((filters, pos) => {
const mapped = mapPos(pos);
if (mapped === undefined) {
return;
}
const mapColumn = mapColumns(pos, mapped);
next.set(
mapped,
mapColumn ? remapTableFilters(filters, mapColumn) : filters
);
});
local = next;
}
if (open) {
const pos = mapPos(open.pos);
const mapColumn =
pos === undefined ? undefined : mapColumns(open.pos, pos);
const column = mapColumn ? mapColumn(open.column) : open.column;
open = pos !== undefined && column !== undefined ? { pos, column } : null;
}
changed = changed === null ? null : (mapPos(changed) ?? null);
if (isRemote || !isInlineTransaction(tr, hasTableRole)) {
if (isStructural) {
rebuildAll = true;
} else {
decorations = decorations.map(tr.mapping, tr.doc);
@@ -310,20 +367,22 @@ function apply(
}
}
// The row that holds the selection is never hidden, so that a row does not
// disappear while it is edited.
// The rows that hold the selection are never hidden, so that a row does
// not disappear while it is edited.
if (!rebuildAll && summaries.size && (tr.selectionSet || tr.docChanged)) {
const oldRow = getSelectionRow(oldState);
const newRow = getSelectionRow(state);
const mappedOldRow = oldRow === null ? null : tr.mapping.map(oldRow);
const oldRows = [...getSelectionRows(oldState)].map((row) =>
tr.mapping.map(row)
);
const newRows = getSelectionRows(state);
const changedRows = [
...oldRows.filter((row) => !newRows.has(row)),
...[...newRows].filter((row) => !oldRows.includes(row)),
];
if (mappedOldRow !== newRow) {
for (const row of [mappedOldRow, newRow]) {
const pos =
row === null ? undefined : findTable(state.doc.resolve(row))?.pos;
if (pos !== undefined && summaries.has(pos)) {
stale.add(pos);
}
for (const row of changedRows) {
const pos = findTable(state.doc.resolve(row))?.pos;
if (pos !== undefined && summaries.has(pos)) {
stale.add(pos);
}
}
}
@@ -333,7 +392,7 @@ function apply(
}
const context: BuildContext = {
selectionRow: getSelectionRow(state),
selectionRows: getSelectionRows(state),
local,
open,
decorations: [],
@@ -395,7 +454,7 @@ function buildTable(node: Node, pos: number, context: BuildContext) {
return;
}
const { selectionRow, local, open, decorations, summaries } = context;
const { selectionRows, local, open, decorations, summaries } = context;
const map = TableMap.get(node);
const tableStart = pos + 1;
const saved = parseTableFilters(node.attrs.filters);
@@ -434,7 +493,7 @@ function buildTable(node: Node, pos: number, context: BuildContext) {
if (index === 0) {
return;
}
if (hidden.has(index) && rowPos !== selectionRow) {
if (hidden.has(index) && !selectionRows.has(rowPos)) {
decorations.push(
Decoration.node(
rowPos,
@@ -600,33 +659,41 @@ function buildButton(className: string, onClick: () => void) {
return button;
}
function getSelectionRow(state: EditorState): number | null {
return (
findParentNodeClosestToPos(
state.selection.$head,
(node) => node.type.spec.tableRole === "row"
)?.pos ?? null
);
function getSelectionRows(state: EditorState): Set<number> {
const rows = new Set<number>();
const { $head } = state.selection;
for (let depth = $head.depth; depth > 0; depth--) {
if ($head.node(depth).type.spec.tableRole === "row") {
rows.add($head.before(depth));
}
}
return rows;
}
/**
* Create a function that maps the position of a table through a transaction.
* Remote transactions replace the whole document, so a table is found by its
* order in the document instead.
* headers and its order among the tables with the same headers instead.
*/
function createPositionMapper(
tr: Transaction,
isRemote: boolean
): (pos: number) => number | undefined {
if (isRemote) {
const isTable = (node: Node) => node.type.spec.tableRole === "table";
let before: number[] | undefined;
let after: number[] | undefined;
let before: TableIdentity[] | undefined;
let after: TableIdentity[] | undefined;
return (pos) => {
before ??= findChildren(tr.before, isTable).map((child) => child.pos);
after ??= findChildren(tr.doc, isTable).map((child) => child.pos);
const index = before.indexOf(pos);
return index === -1 ? undefined : after[index];
before ??= getTableIdentities(tr.before);
after ??= getTableIdentities(tr.doc);
const table = before.find((identity) => identity.pos === pos);
if (!table) {
return undefined;
}
const index = before
.filter((identity) => identity.key === table.key)
.indexOf(table);
return after.filter((identity) => identity.key === table.key)[index]?.pos;
};
}
@@ -638,10 +705,27 @@ function createPositionMapper(
};
}
interface TableIdentity {
/** The position of the table. */
pos: number;
/** The headers of the table. */
key: string;
}
function getTableIdentities(doc: Node): TableIdentity[] {
return findChildren(
doc,
(node) => node.type.spec.tableRole === "table",
true
).map(({ node, pos }) => ({
pos,
key: JSON.stringify(getTableHeaders(node)),
}));
}
function mapKeys<T>(
map: ReadonlyMap<number, T>,
mapPos: (pos: number) => number | undefined,
keep: (pos: number, next: number) => boolean = () => true
mapPos: (pos: number) => number | undefined
): ReadonlyMap<number, T> {
if (!map.size) {
return map;
@@ -650,7 +734,7 @@ function mapKeys<T>(
const next = new Map<number, T>();
map.forEach((value, pos) => {
const mapped = mapPos(pos);
if (mapped !== undefined && keep(pos, mapped)) {
if (mapped !== undefined) {
next.set(mapped, value);
}
});