mirror of
https://github.com/outline/outline.git
synced 2026-12-06 19:22:29 +03:00
feat: Add filtering to tables in the editor
This commit is contained in:
18 files changed
+1841
-23
No files matched your search
@@ -77,6 +77,8 @@ type Props = Omit<React.HTMLAttributes<HTMLButtonElement>, "onChange"> & {
|
||||
help?: string;
|
||||
/** Render function to override the selected value shown in the trigger. Receives the currently selected option, or undefined when none is selected. */
|
||||
displayValue?: (selectedOption: Item | undefined) => React.ReactNode;
|
||||
/** Called when the menu closes and focus would return to the trigger. Call preventDefault on the event to focus another element. */
|
||||
onCloseAutoFocus?: (event: Event) => void;
|
||||
ref?: React.Ref<HTMLButtonElement>;
|
||||
} & TriggerButtonProps;
|
||||
|
||||
@@ -91,6 +93,7 @@ export function InputSelect(props: Props) {
|
||||
short,
|
||||
help,
|
||||
displayValue,
|
||||
onCloseAutoFocus,
|
||||
...triggerProps
|
||||
} = props;
|
||||
|
||||
@@ -202,6 +205,7 @@ export function InputSelect(props: Props) {
|
||||
aria-label={label}
|
||||
onAnimationStart={disablePointerEvents}
|
||||
onAnimationEnd={enablePointerEvents}
|
||||
onCloseAutoFocus={onCloseAutoFocus}
|
||||
>
|
||||
{options.map(renderOption)}
|
||||
</InputSelectContent>
|
||||
|
||||
@@ -0,0 +1,527 @@
|
||||
import * as VisuallyHidden from "@radix-ui/react-visually-hidden";
|
||||
import { observer } from "mobx-react";
|
||||
import { TableMap } from "prosemirror-tables";
|
||||
import type { EditorView } from "prosemirror-view";
|
||||
import * as React from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import styled from "styled-components";
|
||||
import {
|
||||
getTableColumnValues,
|
||||
isListOperator,
|
||||
isTextOperator,
|
||||
parseTableFilterOperator,
|
||||
parseTableFilters,
|
||||
toFilterKey,
|
||||
} from "@shared/editor/lib/tableFilter";
|
||||
import {
|
||||
closeTableFilterMenu,
|
||||
setLocalTableFilters,
|
||||
tableFilterPluginKey,
|
||||
type TableFilterTarget,
|
||||
} from "@shared/editor/plugins/TableFilterPlugin";
|
||||
import { EditorStyleHelper } from "@shared/editor/styles/EditorStyleHelper";
|
||||
import { TableFilterOperator, type TableFilter } from "@shared/editor/types";
|
||||
import { s } from "@shared/styles";
|
||||
import ButtonSmall from "~/components/ButtonSmall";
|
||||
import Flex from "~/components/Flex";
|
||||
import Input from "~/components/Input";
|
||||
import InputSearch from "~/components/InputSearch";
|
||||
import { InputSelect, type Option } from "~/components/InputSelect";
|
||||
import Switch from "~/components/Switch";
|
||||
import Text from "~/components/Text";
|
||||
import {
|
||||
Popover,
|
||||
PopoverAnchor,
|
||||
PopoverContent,
|
||||
} from "~/components/primitives/Popover";
|
||||
import { useComputed } from "~/hooks/useComputed";
|
||||
import useDebouncedValue from "~/hooks/useDebouncedValue";
|
||||
import { useEditor } from "./EditorContext";
|
||||
|
||||
/** The number of values above which the value list can be searched. */
|
||||
const SearchThreshold = 8;
|
||||
|
||||
/** Equal padding on all sides of the menu. */
|
||||
const MenuStyle = { padding: 12 };
|
||||
|
||||
/** The most values shown at once, a search finds the others. */
|
||||
const MaxShownValues = 100;
|
||||
|
||||
/**
|
||||
* The menu to filter the rows of a table by the values in a column, and a
|
||||
* live region that tells screen reader users how many rows are shown.
|
||||
*
|
||||
* @returns the menu, if open, and the live region.
|
||||
*/
|
||||
export const TableFilterMenu = observer(function TableFilterMenu() {
|
||||
const { t } = useTranslation();
|
||||
const editor = useEditor();
|
||||
const { view } = editor;
|
||||
const open = useComputed(
|
||||
() => tableFilterPluginKey.getState(editor.editorState)?.open ?? null,
|
||||
[editor]
|
||||
);
|
||||
|
||||
const announcement = useComputed(() => {
|
||||
const pluginState = tableFilterPluginKey.getState(editor.editorState);
|
||||
if (!pluginState || pluginState.changed === null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
const summary = pluginState.summaries.get(pluginState.changed);
|
||||
if (!summary || summary.visibleRows === summary.totalRows) {
|
||||
return t("Showing all rows");
|
||||
}
|
||||
return t("Showing {{ visible }} of {{ total }} rows", {
|
||||
visible: summary.visibleRows,
|
||||
total: summary.totalRows,
|
||||
});
|
||||
}, [editor, t]);
|
||||
|
||||
const cell = open ? getHeaderCell(view, open) : null;
|
||||
const lastCell = React.useRef<HTMLElement | null>(null);
|
||||
if (cell) {
|
||||
lastCell.current = cell;
|
||||
}
|
||||
|
||||
React.useEffect(() => {
|
||||
if (open && !cell) {
|
||||
view.dispatch(closeTableFilterMenu(view.state.tr));
|
||||
}
|
||||
}, [view, open, cell]);
|
||||
|
||||
const handleOpenChange = React.useCallback(
|
||||
(value: boolean) => {
|
||||
if (!value) {
|
||||
view.dispatch(closeTableFilterMenu(view.state.tr));
|
||||
}
|
||||
},
|
||||
[view]
|
||||
);
|
||||
|
||||
// The filter button toggles the menu, so a press on it is not treated as a
|
||||
// press outside of the menu.
|
||||
const handleInteractOutside = React.useCallback((event: Event) => {
|
||||
if (
|
||||
event.target instanceof Element &&
|
||||
event.target.closest(`.${EditorStyleHelper.tableFilterButton}`)
|
||||
) {
|
||||
event.preventDefault();
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleCloseAutoFocus = React.useCallback(
|
||||
(event: Event) => {
|
||||
event.preventDefault();
|
||||
const button = lastCell.current?.querySelector(
|
||||
`.${EditorStyleHelper.tableFilterButton}`
|
||||
);
|
||||
if (
|
||||
button instanceof HTMLElement &&
|
||||
button.isConnected &&
|
||||
getComputedStyle(button).display !== "none"
|
||||
) {
|
||||
button.focus();
|
||||
} else if (view.editable) {
|
||||
view.focus();
|
||||
}
|
||||
},
|
||||
[view]
|
||||
);
|
||||
|
||||
const anchorRef = React.useMemo(() => ({ current: cell }), [cell]);
|
||||
|
||||
// The menu sits below the header cell, so the column name is only announced.
|
||||
const columnName = cell?.textContent?.trim();
|
||||
|
||||
return (
|
||||
<>
|
||||
<VisuallyHidden.Root role="status" aria-live="polite">
|
||||
{announcement}
|
||||
</VisuallyHidden.Root>
|
||||
{open && cell && (
|
||||
<Popover open onOpenChange={handleOpenChange}>
|
||||
<PopoverAnchor virtualRef={anchorRef} />
|
||||
<PopoverContent
|
||||
width={300}
|
||||
style={MenuStyle}
|
||||
align="start"
|
||||
aria-label={
|
||||
columnName
|
||||
? t("Filter {{ columnName }}", { columnName })
|
||||
: t("Filter")
|
||||
}
|
||||
onInteractOutside={handleInteractOutside}
|
||||
onCloseAutoFocus={handleCloseAutoFocus}
|
||||
>
|
||||
<TableFilterForm target={open} />
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
});
|
||||
|
||||
type FormProps = {
|
||||
/** The column to filter. */
|
||||
target: TableFilterTarget;
|
||||
};
|
||||
|
||||
const TableFilterForm = observer(function TableFilterForm({
|
||||
target,
|
||||
}: FormProps) {
|
||||
const { t } = useTranslation();
|
||||
const editor = useEditor();
|
||||
const { view } = editor;
|
||||
const [query, setQuery] = React.useState("");
|
||||
const textInputRef = React.useRef<HTMLInputElement | HTMLTextAreaElement>(
|
||||
null
|
||||
);
|
||||
const focusTextOnClose = React.useRef(false);
|
||||
|
||||
// Narrow reads, so that the menu only renders when this table changes.
|
||||
const table = useComputed(() => {
|
||||
const node = editor.editorState.doc.nodeAt(target.pos);
|
||||
return node?.type.spec.tableRole === "table" ? node : null;
|
||||
}, [editor, target.pos]);
|
||||
const local = useComputed(
|
||||
() =>
|
||||
tableFilterPluginKey.getState(editor.editorState)?.local.get(target.pos),
|
||||
[editor, target.pos]
|
||||
);
|
||||
const summary = useComputed(
|
||||
() =>
|
||||
tableFilterPluginKey
|
||||
.getState(editor.editorState)
|
||||
?.summaries.get(target.pos),
|
||||
[editor, target.pos]
|
||||
);
|
||||
|
||||
const columnValues = React.useMemo(
|
||||
() => (table ? getTableColumnValues(table, target.column) : []),
|
||||
[table, target.column]
|
||||
);
|
||||
|
||||
if (!table) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const filters = local ?? parseTableFilters(table.attrs.filters);
|
||||
const filter: TableFilter = filters.find(
|
||||
(f) => f.column === target.column
|
||||
) ?? {
|
||||
column: target.column,
|
||||
operator: TableFilterOperator.Is,
|
||||
values: [],
|
||||
};
|
||||
const selected = new Set(filter.values.map(toFilterKey));
|
||||
const found = new Set(columnValues.map((v) => toFilterKey(v.value)));
|
||||
|
||||
// Chosen values that no rows have any more are kept, so that they can be
|
||||
// removed.
|
||||
const values = [
|
||||
...columnValues,
|
||||
...filter.values
|
||||
.filter((value) => !found.has(toFilterKey(value)))
|
||||
.map((value) => ({ value, count: 0 })),
|
||||
];
|
||||
const normalizedQuery = toFilterKey(query);
|
||||
const matchingValues = normalizedQuery
|
||||
? values.filter((v) => toFilterKey(v.value).includes(normalizedQuery))
|
||||
: values;
|
||||
const visibleValues = matchingValues.slice(0, MaxShownValues);
|
||||
const hasValues = isListOperator(filter.operator);
|
||||
const hasText = isTextOperator(filter.operator);
|
||||
|
||||
const update = (next: TableFilter | undefined) => {
|
||||
const others = filters.filter((f) => f.column !== target.column);
|
||||
view.dispatch(
|
||||
setLocalTableFilters(
|
||||
view.state.tr,
|
||||
target.pos,
|
||||
next ? [...others, next] : others
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
const handleOperatorChange = (value: string) => {
|
||||
const operator = parseTableFilterOperator(value);
|
||||
if (!operator) {
|
||||
return;
|
||||
}
|
||||
|
||||
// A list of values and a text are not the same, so a change between the
|
||||
// two starts again with nothing.
|
||||
focusTextOnClose.current = isTextOperator(operator);
|
||||
const isSameKind =
|
||||
isListOperator(operator) === isListOperator(filter.operator) &&
|
||||
isTextOperator(operator) === isTextOperator(filter.operator);
|
||||
update({
|
||||
...filter,
|
||||
operator,
|
||||
values: isSameKind ? filter.values : [],
|
||||
});
|
||||
};
|
||||
|
||||
const handleValueChange = (value: string, checked: boolean) => {
|
||||
const key = toFilterKey(value);
|
||||
update({
|
||||
...filter,
|
||||
values: checked
|
||||
? [...filter.values, value]
|
||||
: filter.values.filter((v) => toFilterKey(v) !== key),
|
||||
});
|
||||
};
|
||||
|
||||
// After a text condition is chosen, the reader types the text next.
|
||||
const handleConditionCloseAutoFocus = (event: Event) => {
|
||||
if (focusTextOnClose.current && textInputRef.current) {
|
||||
event.preventDefault();
|
||||
textInputRef.current.focus();
|
||||
}
|
||||
focusTextOnClose.current = false;
|
||||
};
|
||||
|
||||
const handleTextChange = (text: string) => {
|
||||
update({ ...filter, values: text.trim() ? [text] : [] });
|
||||
};
|
||||
|
||||
const handleQueryChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setQuery(event.target.value);
|
||||
};
|
||||
|
||||
const handleClear = () => {
|
||||
update(undefined);
|
||||
};
|
||||
|
||||
const options: Option[] = [
|
||||
{ type: "item", label: t("Is"), value: TableFilterOperator.Is },
|
||||
{ type: "item", label: t("Is not"), value: TableFilterOperator.IsNot },
|
||||
{
|
||||
type: "item",
|
||||
label: t("Contains"),
|
||||
value: TableFilterOperator.Contains,
|
||||
},
|
||||
{
|
||||
type: "item",
|
||||
label: t("Does not contain"),
|
||||
value: TableFilterOperator.DoesNotContain,
|
||||
},
|
||||
{ type: "item", label: t("Is empty"), value: TableFilterOperator.IsEmpty },
|
||||
{
|
||||
type: "item",
|
||||
label: t("Is not empty"),
|
||||
value: TableFilterOperator.IsNotEmpty,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<Flex column gap={12}>
|
||||
<InputSelect
|
||||
label={t("Condition")}
|
||||
labelHidden
|
||||
options={options}
|
||||
value={filter.operator}
|
||||
onChange={handleOperatorChange}
|
||||
onCloseAutoFocus={handleConditionCloseAutoFocus}
|
||||
/>
|
||||
{hasText && (
|
||||
<FilterTextInput
|
||||
ref={textInputRef}
|
||||
value={filter.values[0] ?? ""}
|
||||
onChange={handleTextChange}
|
||||
/>
|
||||
)}
|
||||
{hasValues &&
|
||||
(values.length ? (
|
||||
<>
|
||||
{values.length > SearchThreshold && (
|
||||
<InputSearch
|
||||
value={query}
|
||||
onChange={handleQueryChange}
|
||||
placeholder={`${t("Search values")}…`}
|
||||
aria-label={t("Search values")}
|
||||
margin={0}
|
||||
/>
|
||||
)}
|
||||
<ValueList role="group" aria-label={t("Values")}>
|
||||
{visibleValues.map(({ value, count }) => (
|
||||
<ValueOption
|
||||
key={value}
|
||||
value={value}
|
||||
count={count}
|
||||
checked={selected.has(toFilterKey(value))}
|
||||
onChange={handleValueChange}
|
||||
/>
|
||||
))}
|
||||
</ValueList>
|
||||
{matchingValues.length > visibleValues.length && (
|
||||
<Text type="tertiary" size="small">
|
||||
{t(
|
||||
"Showing {{ shown }} of {{ total }} values. Search to find more.",
|
||||
{
|
||||
shown: visibleValues.length,
|
||||
total: matchingValues.length,
|
||||
}
|
||||
)}
|
||||
</Text>
|
||||
)}
|
||||
{!matchingValues.length && (
|
||||
<Text type="tertiary" size="small">
|
||||
{t("No values match your search.")}
|
||||
</Text>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<Text type="secondary" size="small">
|
||||
{t("This column has no values")}
|
||||
</Text>
|
||||
))}
|
||||
<Flex justify="space-between" align="center" gap={8}>
|
||||
<Text type="secondary" size="small">
|
||||
{summary
|
||||
? t("{{ visible }} of {{ total }} rows", {
|
||||
visible: summary.visibleRows,
|
||||
total: summary.totalRows,
|
||||
})
|
||||
: null}
|
||||
</Text>
|
||||
<ButtonSmall
|
||||
neutral
|
||||
onClick={handleClear}
|
||||
disabled={!filters.some((f) => f.column === target.column)}
|
||||
>
|
||||
{t("Clear")}
|
||||
</ButtonSmall>
|
||||
</Flex>
|
||||
</Flex>
|
||||
);
|
||||
});
|
||||
|
||||
type FilterTextInputProps = {
|
||||
/** The text of the filter. */
|
||||
value: string;
|
||||
/** Called with the text once the reader stops typing. */
|
||||
onChange: (text: string) => void;
|
||||
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) {
|
||||
const { t } = useTranslation();
|
||||
const [text, setText] = React.useState(value);
|
||||
const debouncedText = useDebouncedValue(text, TextFilterWait);
|
||||
const handleDebouncedChange = React.useEffectEvent((next: string) => {
|
||||
if (next !== value) {
|
||||
onChange(next);
|
||||
}
|
||||
});
|
||||
|
||||
React.useEffect(() => {
|
||||
handleDebouncedChange(debouncedText);
|
||||
}, [debouncedText]);
|
||||
|
||||
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setText(event.target.value);
|
||||
};
|
||||
|
||||
return (
|
||||
<Input
|
||||
value={text}
|
||||
onChange={handleChange}
|
||||
placeholder={`${t("Text")}…`}
|
||||
label={t("Text")}
|
||||
labelHidden
|
||||
margin={0}
|
||||
ref={ref}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
type ValueOptionProps = {
|
||||
/** The value. */
|
||||
value: string;
|
||||
/** The number of rows that have the value. */
|
||||
count: number;
|
||||
/** Whether the value is chosen. */
|
||||
checked: boolean;
|
||||
/** Called when the value is chosen or no longer chosen. */
|
||||
onChange: (value: string, checked: boolean) => void;
|
||||
};
|
||||
|
||||
function ValueOption({ value, count, checked, onChange }: ValueOptionProps) {
|
||||
const id = React.useId();
|
||||
const handleChange = (next: boolean) => onChange(value, next);
|
||||
|
||||
return (
|
||||
<ValueRow htmlFor={id}>
|
||||
<ValueLabel>{value}</ValueLabel>
|
||||
<Text type="tertiary" size="small">
|
||||
{count}
|
||||
</Text>
|
||||
<Switch
|
||||
id={id}
|
||||
checked={checked}
|
||||
onChange={handleChange}
|
||||
width={26}
|
||||
height={14}
|
||||
/>
|
||||
</ValueRow>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the element of the header cell of a table column.
|
||||
*
|
||||
* @param view the editor view.
|
||||
* @param target the column.
|
||||
* @returns the element, or null if the column does not exist.
|
||||
*/
|
||||
function getHeaderCell(
|
||||
view: EditorView,
|
||||
target: TableFilterTarget
|
||||
): HTMLElement | null {
|
||||
const table = view.state.doc.nodeAt(target.pos);
|
||||
if (table?.type.spec.tableRole !== "table") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const map = TableMap.get(table);
|
||||
if (target.column >= map.width) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const dom = view.nodeDOM(target.pos + 1 + map.map[target.column]);
|
||||
return dom instanceof HTMLElement ? dom : null;
|
||||
}
|
||||
|
||||
const ValueList = styled.div`
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
max-height: 240px;
|
||||
overflow-y: auto;
|
||||
margin: 0 -8px;
|
||||
`;
|
||||
|
||||
const ValueRow = styled.label`
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 4px 8px;
|
||||
border-radius: 4px;
|
||||
cursor: var(--pointer);
|
||||
|
||||
&:hover {
|
||||
background: ${s("listItemHoverBackground")};
|
||||
}
|
||||
`;
|
||||
|
||||
const ValueLabel = styled.span`
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
`;
|
||||
@@ -0,0 +1,17 @@
|
||||
import Extension from "@shared/editor/lib/Extension";
|
||||
import { TableFilterMenu } from "../components/TableFilterMenu";
|
||||
|
||||
/**
|
||||
* Shows the menu to filter the rows of a table, in reading and editing mode.
|
||||
*/
|
||||
export default class TableFilterExtension extends Extension {
|
||||
get name() {
|
||||
return "table-filter";
|
||||
}
|
||||
|
||||
get allowInReadOnly() {
|
||||
return true;
|
||||
}
|
||||
|
||||
widget = () => <TableFilterMenu />;
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import PasteHandler from "~/editor/extensions/PasteHandler";
|
||||
import PreventTab from "~/editor/extensions/PreventTab";
|
||||
import SelectionToolbarExtension from "~/editor/extensions/SelectionToolbar";
|
||||
import SmartText from "~/editor/extensions/SmartText";
|
||||
import TableFilterExtension from "~/editor/extensions/TableFilter";
|
||||
|
||||
type Nodes = AnyExtensionClass[];
|
||||
|
||||
@@ -29,6 +30,7 @@ export const withUIExtensions = (nodes: Nodes) => [
|
||||
FindAndReplaceExtension,
|
||||
HoverPreviewsExtension,
|
||||
SelectionToolbarExtension,
|
||||
TableFilterExtension,
|
||||
CommentGutterExtension,
|
||||
DiagramsExtension,
|
||||
DragHandle,
|
||||
|
||||
@@ -30,8 +30,10 @@ import type {
|
||||
} from "@shared/editor/types";
|
||||
import { ArrowLeftIcon, ArrowRightIcon } from "~/components/Icons/ArrowIcon";
|
||||
import CircleIcon from "~/components/Icons/CircleIcon";
|
||||
import { FilterIcon } from "~/components/Icons/FilterIcon";
|
||||
import CellBackgroundColorPicker from "../components/CellBackgroundColorPicker";
|
||||
import TableCell from "@shared/editor/nodes/TableCell";
|
||||
import { isTableFilterable } from "@shared/editor/lib/tableFilter";
|
||||
import { DottedCircleIcon } from "~/components/Icons/DottedCircleIcon";
|
||||
import type { EditorState } from "prosemirror-state";
|
||||
|
||||
@@ -155,6 +157,14 @@ export default function tableColMenuItems(ctx: SelectionContext): MenuItem[] {
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "openTableFilter",
|
||||
label: t("Filter"),
|
||||
icon: <FilterIcon />,
|
||||
attrs: { index },
|
||||
disabled: !isTableFilterable(tableMap.table),
|
||||
visible: !isMultipleColumns,
|
||||
},
|
||||
{
|
||||
label: t("Background"),
|
||||
icon:
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
toggleHeader,
|
||||
addColumn,
|
||||
deleteTable,
|
||||
moveTableColumn,
|
||||
mergeCells,
|
||||
removeColumn,
|
||||
removeRow,
|
||||
@@ -25,6 +26,10 @@ import { isCurrency, parseCurrency } from "../../utils/currency";
|
||||
import { parseDate } from "../../utils/date";
|
||||
import { isIPv4Address, parseIPv4 } from "../../utils/ip";
|
||||
import { chainTransactions } from "../lib/chainTransactions";
|
||||
import {
|
||||
openTableFilterMenu,
|
||||
remapTableColumnFilters,
|
||||
} from "../plugins/TableFilterPlugin";
|
||||
import {
|
||||
getAllSelectedColumns,
|
||||
canMergeCells,
|
||||
@@ -68,6 +73,26 @@ function restoreColumnSelection(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a column to a table, moving the column filters after it.
|
||||
*
|
||||
* @param tr The transaction to update.
|
||||
* @param rect The table rect.
|
||||
* @param position The index to insert the column at.
|
||||
* @returns The transaction.
|
||||
*/
|
||||
function addColumnWithFilters(
|
||||
tr: Transaction,
|
||||
rect: TableRect,
|
||||
position: number
|
||||
): Transaction {
|
||||
return remapTableColumnFilters(
|
||||
addColumn(tr, rect, position),
|
||||
rect.tableStart - 1,
|
||||
(column) => (column >= position ? column + 1 : column)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A command that places a text cursor at the start of the cell at the given row
|
||||
* and column index within the table that begins at the given position. Used
|
||||
@@ -637,6 +662,12 @@ export function deleteColumns(): Command {
|
||||
}
|
||||
removeColumn(tr, { ...rect, table, map: TableMap.get(table) }, column);
|
||||
}
|
||||
remapTableColumnFilters(tr, rect.tableStart - 1, (column) => {
|
||||
if (columns.includes(column)) {
|
||||
return undefined;
|
||||
}
|
||||
return column - columns.filter((removed) => removed < column).length;
|
||||
});
|
||||
dispatch(tr);
|
||||
}
|
||||
return true;
|
||||
@@ -700,7 +731,7 @@ export function addColumnBefore({ index }: { index?: number }): Command {
|
||||
|
||||
chainTransactions(
|
||||
headerSpecialCase ? toggleHeader("column") : undefined,
|
||||
(s, d) => !!d?.(addColumn(s.tr, rect, position)),
|
||||
(s, d) => !!d?.(addColumnWithFilters(s.tr, rect, position)),
|
||||
headerSpecialCase ? toggleHeader("column") : undefined,
|
||||
setCursorInCell(rect.tableStart, 0, position)
|
||||
)(state, dispatch);
|
||||
@@ -755,7 +786,7 @@ export function addColumnAfter({ index }: { index?: number }): Command {
|
||||
const position = index !== undefined ? index + 1 : rect.right;
|
||||
|
||||
chainTransactions(
|
||||
(s, d) => !!d?.(addColumn(s.tr, rect, position)),
|
||||
(s, d) => !!d?.(addColumnWithFilters(s.tr, rect, position)),
|
||||
setCursorInCell(rect.tableStart, 0, position)
|
||||
)(state, dispatch);
|
||||
|
||||
@@ -927,6 +958,77 @@ export function setTableAttr(attrs: { layout: TableLayout | null }): Command {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A command that moves a column of the table, keeping the column filters on
|
||||
* the columns they apply to.
|
||||
*
|
||||
* @param from The index of the column to move.
|
||||
* @param to The index to move the column to.
|
||||
* @returns The command
|
||||
*/
|
||||
export function moveColumn({
|
||||
from,
|
||||
to,
|
||||
}: {
|
||||
from: number;
|
||||
to: number;
|
||||
}): Command {
|
||||
return (state, dispatch) => {
|
||||
if (!isInTable(state)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const rect = selectedRect(state);
|
||||
const order = Array.from({ length: rect.map.width }, (_, index) => index);
|
||||
order.splice(to, 0, ...order.splice(from, 1));
|
||||
|
||||
return moveTableColumn({ from, to })(
|
||||
state,
|
||||
dispatch
|
||||
? (tr) =>
|
||||
dispatch(
|
||||
remapTableColumnFilters(tr, rect.tableStart - 1, (column) =>
|
||||
order.indexOf(column)
|
||||
)
|
||||
)
|
||||
: undefined
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A command that opens the filter menu for a column of the table.
|
||||
*
|
||||
* @param index The index of the column.
|
||||
* @returns The command
|
||||
*/
|
||||
export function openTableFilter({ index }: { index: number }): Command {
|
||||
return (state, dispatch) => {
|
||||
if (!isInTable(state)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (dispatch) {
|
||||
const rect = selectedRect(state);
|
||||
if (index < 0 || index >= rect.map.width) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Collapse the column selection so that its toolbar closes.
|
||||
const $cell = state.doc.resolve(
|
||||
rect.tableStart + rect.map.map[index] + 1
|
||||
);
|
||||
dispatch(
|
||||
openTableFilterMenu(state.tr.setSelection(TextSelection.near($cell)), {
|
||||
pos: rect.tableStart - 1,
|
||||
column: index,
|
||||
})
|
||||
);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Select a row in the table.
|
||||
*
|
||||
|
||||
@@ -2359,6 +2359,16 @@ table {
|
||||
border-bottom-right-radius: ${EditorStyleHelper.blockRadius};
|
||||
}
|
||||
|
||||
// When filters hide the last row, the last visible row rounds the corners.
|
||||
tr:not(.${EditorStyleHelper.tableRowFiltered}):not(:has(~ tr:not(.${EditorStyleHelper.tableRowFiltered}))) {
|
||||
> [data-first-column] {
|
||||
border-bottom-left-radius: ${EditorStyleHelper.blockRadius};
|
||||
}
|
||||
> [data-last-column] {
|
||||
border-bottom-right-radius: ${EditorStyleHelper.blockRadius};
|
||||
}
|
||||
}
|
||||
|
||||
td .component-embed {
|
||||
padding: 4px 0;
|
||||
}
|
||||
@@ -2723,6 +2733,114 @@ table .${EditorStyleHelper.table} > .${EditorStyleHelper.tableScrollable} > tabl
|
||||
animation: none;
|
||||
}
|
||||
|
||||
.${EditorStyleHelper.tableRowFiltered} {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.${EditorStyleHelper.tableFilterButton} {
|
||||
display: none;
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
inset-inline-end: 4px;
|
||||
translate: 0 -50%;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: 4px;
|
||||
background: none;
|
||||
color: inherit;
|
||||
cursor: var(--pointer);
|
||||
z-index: 1;
|
||||
|
||||
&::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 2px;
|
||||
background-color: ${props.theme.text};
|
||||
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;
|
||||
}
|
||||
|
||||
&:hover,
|
||||
&:focus-visible {
|
||||
color: ${props.theme.text};
|
||||
background: ${props.theme.backgroundSecondary};
|
||||
}
|
||||
|
||||
&.active {
|
||||
display: block;
|
||||
}
|
||||
|
||||
@media print {
|
||||
display: none !important;
|
||||
}
|
||||
}
|
||||
|
||||
${
|
||||
props.readOnly
|
||||
? `
|
||||
th:hover > .${EditorStyleHelper.tableFilterButton},
|
||||
.${EditorStyleHelper.tableFilterButton}:focus-visible {
|
||||
display: block;
|
||||
}
|
||||
|
||||
@media (hover: none) {
|
||||
.${EditorStyleHelper.tableFilterButton} {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
`
|
||||
: ""
|
||||
}
|
||||
|
||||
th:has(> .${EditorStyleHelper.tableFilterButton}.active) {
|
||||
padding-inline-end: 28px;
|
||||
}
|
||||
|
||||
.${EditorStyleHelper.tableFilterBar} {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 4px 8px;
|
||||
margin-top: 4px;
|
||||
font-size: 14px;
|
||||
color: ${props.theme.textTertiary};
|
||||
user-select: none;
|
||||
|
||||
button {
|
||||
padding: 0 4px;
|
||||
border: 0;
|
||||
border-radius: 4px;
|
||||
background: none;
|
||||
font: inherit;
|
||||
color: ${props.theme.textSecondary};
|
||||
cursor: var(--pointer);
|
||||
|
||||
&:hover,
|
||||
&:focus-visible {
|
||||
color: ${props.theme.text};
|
||||
background: ${props.theme.backgroundSecondary};
|
||||
}
|
||||
}
|
||||
|
||||
${
|
||||
props.readOnly
|
||||
? `
|
||||
&.inactive,
|
||||
.save {
|
||||
display: none;
|
||||
}
|
||||
`
|
||||
: ""
|
||||
}
|
||||
|
||||
@media print {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
.${EditorStyleHelper.tableStickyHeader} {
|
||||
> .${EditorStyleHelper.tableScrollable} > table > tbody > tr:first-child {
|
||||
position: relative;
|
||||
|
||||
@@ -3,11 +3,12 @@ import { TableMap, type MutableAttrs } from "prosemirror-tables";
|
||||
import { Decoration, type EditorView } from "prosemirror-view";
|
||||
import { isBrowser } from "../../utils/browser";
|
||||
import { isNearWhite, toHexColor, validateColorHex } from "../../utils/color";
|
||||
import type { TableLayout, NodeAttrMark } from "../types";
|
||||
import type { TableFilter, TableLayout, NodeAttrMark } from "../types";
|
||||
import { readableColor } from "polished";
|
||||
|
||||
export interface TableAttrs {
|
||||
layout: TableLayout | null;
|
||||
filters: TableFilter[] | null;
|
||||
}
|
||||
|
||||
export interface CellAttrs {
|
||||
@@ -387,6 +388,18 @@ export function cellWidget(
|
||||
return Decoration.widget(cellPos + 1, toDOM, { ...spec, side: -1 });
|
||||
}
|
||||
|
||||
/**
|
||||
* Focus the editor if it does not have focus, for controls such as the table
|
||||
* grips that stay visible while focus is elsewhere.
|
||||
*
|
||||
* @param view The editor view.
|
||||
*/
|
||||
export function focusEditor(view: EditorView): void {
|
||||
if (!view.hasFocus()) {
|
||||
view.focus();
|
||||
}
|
||||
}
|
||||
|
||||
const spanTrackers = new WeakMap<globalThis.Node, () => void>();
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,316 @@
|
||||
import type { Node } from "prosemirror-model";
|
||||
import { TableMap } from "prosemirror-tables";
|
||||
import { TableFilterOperator, type TableFilter } from "../types";
|
||||
|
||||
/** A distinct value found in a table column. */
|
||||
export interface TableColumnValue {
|
||||
/** The text of the value, as first found in the column. */
|
||||
value: string;
|
||||
/** The number of rows that have the value. */
|
||||
count: number;
|
||||
}
|
||||
|
||||
const operators = Object.values(TableFilterOperator);
|
||||
|
||||
/**
|
||||
* Get the filter operator for a value.
|
||||
*
|
||||
* @param value the value to read.
|
||||
* @returns the operator, or undefined if the value is not an operator.
|
||||
*/
|
||||
export function parseTableFilterOperator(
|
||||
value: unknown
|
||||
): TableFilterOperator | undefined {
|
||||
return operators.find((operator) => operator === value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a value so that values that differ only by case or whitespace are
|
||||
* the same.
|
||||
*
|
||||
* @param value the value.
|
||||
* @returns the normalized value.
|
||||
*/
|
||||
export function toFilterKey(value: string): string {
|
||||
return value.replace(/\s+/g, " ").trim().toLocaleLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the text of a table cell, with whitespace collapsed, for use as a filter
|
||||
* value.
|
||||
*
|
||||
* @param cell the table cell node.
|
||||
* @returns the text of the cell.
|
||||
*/
|
||||
export function getCellValue(cell: Node): string {
|
||||
return cell
|
||||
.textBetween(0, cell.content.size, " ")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the filters stored on a table node. Invalid entries are left out, and
|
||||
* each column keeps only its first filter.
|
||||
*
|
||||
* @param value the stored value.
|
||||
* @returns the valid filters.
|
||||
*/
|
||||
export function parseTableFilters(value: unknown): TableFilter[] {
|
||||
if (!Array.isArray(value)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const filters: TableFilter[] = [];
|
||||
const columns = new Set<number>();
|
||||
|
||||
for (const item of value) {
|
||||
if (
|
||||
typeof item !== "object" ||
|
||||
item === null ||
|
||||
!("column" in item) ||
|
||||
!("operator" in item)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const { column } = item;
|
||||
const operator = parseTableFilterOperator(item.operator);
|
||||
if (
|
||||
typeof column !== "number" ||
|
||||
!Number.isInteger(column) ||
|
||||
column < 0 ||
|
||||
columns.has(column) ||
|
||||
!operator
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const values: unknown[] =
|
||||
"values" in item && Array.isArray(item.values) ? item.values : [];
|
||||
|
||||
columns.add(column);
|
||||
filters.push({
|
||||
column,
|
||||
operator,
|
||||
values: values.filter((v): v is string => typeof v === "string"),
|
||||
});
|
||||
}
|
||||
|
||||
return filters;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a filter hides any rows. A filter that compares with values does
|
||||
* nothing until a value is chosen.
|
||||
*
|
||||
* @param filter the filter.
|
||||
* @returns true if the filter is active.
|
||||
*/
|
||||
export function isTableFilterActive(filter: TableFilter): boolean {
|
||||
if (isTextOperator(filter.operator)) {
|
||||
return !!filter.values[0]?.trim();
|
||||
}
|
||||
if (isListOperator(filter.operator)) {
|
||||
return filter.values.length > 0;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an operator compares cells with a list of chosen values.
|
||||
*
|
||||
* @param operator the operator.
|
||||
* @returns true for the "is" and "is not" operators.
|
||||
*/
|
||||
export function isListOperator(operator: TableFilterOperator): boolean {
|
||||
return (
|
||||
operator === TableFilterOperator.Is ||
|
||||
operator === TableFilterOperator.IsNot
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an operator compares cells with a text that the reader types.
|
||||
*
|
||||
* @param operator the operator.
|
||||
* @returns true for the "contains" and "does not contain" operators.
|
||||
*/
|
||||
export function isTextOperator(operator: TableFilterOperator): boolean {
|
||||
return (
|
||||
operator === TableFilterOperator.Contains ||
|
||||
operator === TableFilterOperator.DoesNotContain
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether two lists of filters have the same effect.
|
||||
*
|
||||
* @param a the first list of filters.
|
||||
* @param b the second list of filters.
|
||||
* @returns true if the filters are equal.
|
||||
*/
|
||||
export function isEqualTableFilters(a: TableFilter[], b: TableFilter[]) {
|
||||
const serialize = (filters: TableFilter[]) =>
|
||||
JSON.stringify(
|
||||
filters
|
||||
.filter(isTableFilterActive)
|
||||
.map((filter) => ({
|
||||
...filter,
|
||||
values: filter.values.map(toFilterKey).sort(),
|
||||
}))
|
||||
.sort((x, y) => x.column - y.column)
|
||||
);
|
||||
|
||||
return serialize(a) === serialize(b);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* @param table the table node.
|
||||
* @returns true if the table can be filtered.
|
||||
*/
|
||||
export function isTableFilterable(table: Node): boolean {
|
||||
if (table.childCount < 2) {
|
||||
return false;
|
||||
}
|
||||
|
||||
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) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the rows of a table that the filters hide. The header row is never
|
||||
* hidden. The table must be filterable.
|
||||
*
|
||||
* @param table the table node.
|
||||
* @param filters the filters to apply.
|
||||
* @returns the indexes of the hidden rows.
|
||||
*/
|
||||
export function getHiddenTableRows(
|
||||
table: Node,
|
||||
filters: TableFilter[]
|
||||
): number[] {
|
||||
const map = TableMap.get(table);
|
||||
const matchers = filters
|
||||
.filter(
|
||||
(filter) => isTableFilterActive(filter) && filter.column < map.width
|
||||
)
|
||||
.map((filter) => ({
|
||||
column: filter.column,
|
||||
matches: createMatcher(filter),
|
||||
}));
|
||||
if (!matchers.length) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const hidden: number[] = [];
|
||||
for (let row = 1; row < map.height; row++) {
|
||||
const visible = matchers.every(({ column, matches }) => {
|
||||
const cell = table.nodeAt(map.map[row * map.width + column]);
|
||||
return matches(cell ? getCellValue(cell) : "");
|
||||
});
|
||||
if (!visible) {
|
||||
hidden.push(row);
|
||||
}
|
||||
}
|
||||
return hidden;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the distinct values in a column of a table, below the header row. Values
|
||||
* that differ only by case are counted as one.
|
||||
*
|
||||
* @param table the table node.
|
||||
* @param column the index of the column.
|
||||
* @returns the values, sorted alphabetically.
|
||||
*/
|
||||
export function getTableColumnValues(
|
||||
table: Node,
|
||||
column: number
|
||||
): TableColumnValue[] {
|
||||
const map = TableMap.get(table);
|
||||
if (column < 0 || column >= map.width) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const values = new Map<string, TableColumnValue>();
|
||||
for (let row = 1; row < map.height; row++) {
|
||||
const cell = table.nodeAt(map.map[row * map.width + column]);
|
||||
const value = cell ? getCellValue(cell) : "";
|
||||
if (!value) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const key = toFilterKey(value);
|
||||
const existing = values.get(key);
|
||||
if (existing) {
|
||||
existing.count++;
|
||||
} else {
|
||||
values.set(key, { value, count: 1 });
|
||||
}
|
||||
}
|
||||
|
||||
return [...values.values()].sort((a, b) =>
|
||||
a.value.localeCompare(b.value, undefined, { numeric: true })
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Change the columns that filters apply to, for example after a column is
|
||||
* moved. Filters on a column that is removed are left out.
|
||||
*
|
||||
* @param filters the filters.
|
||||
* @param mapColumn returns the new index of a column, or undefined if removed.
|
||||
* @returns the changed filters.
|
||||
*/
|
||||
export function remapTableFilters(
|
||||
filters: TableFilter[],
|
||||
mapColumn: (column: number) => number | undefined
|
||||
): TableFilter[] {
|
||||
return filters.flatMap((filter) => {
|
||||
const column = mapColumn(filter.column);
|
||||
return column === undefined ? [] : [{ ...filter, column }];
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a function that checks whether a cell value meets a filter.
|
||||
*
|
||||
* @param filter the filter.
|
||||
* @returns a function that takes the text of a cell, as returned by
|
||||
* getCellValue, and returns true if it meets the filter.
|
||||
*/
|
||||
function createMatcher(filter: TableFilter): (value: string) => boolean {
|
||||
switch (filter.operator) {
|
||||
case TableFilterOperator.Is:
|
||||
case TableFilterOperator.IsNot: {
|
||||
const keys = new Set(filter.values.map(toFilterKey));
|
||||
const is = filter.operator === TableFilterOperator.Is;
|
||||
|
||||
// Cell values have whitespace collapsed, so only the case differs.
|
||||
return (value) => keys.has(value.toLocaleLowerCase()) === is;
|
||||
}
|
||||
case TableFilterOperator.Contains:
|
||||
case TableFilterOperator.DoesNotContain: {
|
||||
const key = toFilterKey(filter.values[0] ?? "");
|
||||
const contains = filter.operator === TableFilterOperator.Contains;
|
||||
return (value) => value.toLocaleLowerCase().includes(key) === contains;
|
||||
}
|
||||
case TableFilterOperator.IsEmpty:
|
||||
return (value) => value === "";
|
||||
case TableFilterOperator.IsNotEmpty:
|
||||
return (value) => value !== "";
|
||||
default:
|
||||
return () => true;
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
columnResizing,
|
||||
deleteTable,
|
||||
goToNextCell,
|
||||
moveTableColumn,
|
||||
moveTableRow,
|
||||
tableEditing,
|
||||
toggleHeader,
|
||||
@@ -24,6 +23,8 @@ import {
|
||||
distributeColumns,
|
||||
sortTable,
|
||||
setTableAttr,
|
||||
moveColumn,
|
||||
openTableFilter,
|
||||
deleteColSelection,
|
||||
deleteColumns,
|
||||
deleteRows,
|
||||
@@ -43,16 +44,18 @@ 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";
|
||||
import { EditorStyleHelper } from "../styles/EditorStyleHelper";
|
||||
import type { TableLayout } from "../types";
|
||||
import type { TableFilter, TableLayout } from "../types";
|
||||
import Node from "./Node";
|
||||
import { TableView } from "./TableView";
|
||||
|
||||
export type TableAttrs = {
|
||||
layout: TableLayout | null;
|
||||
filters: TableFilter[] | null;
|
||||
};
|
||||
|
||||
export default class Table extends Node {
|
||||
@@ -71,6 +74,11 @@ export default class Table extends Node {
|
||||
layout: {
|
||||
default: null,
|
||||
},
|
||||
// Filters that hide rows for everyone, readers can change them for
|
||||
// themselves without changing the document.
|
||||
filters: {
|
||||
default: null,
|
||||
},
|
||||
},
|
||||
toDOM() {
|
||||
// Note: This is overridden by TableView
|
||||
@@ -100,7 +108,8 @@ export default class Table extends Node {
|
||||
addRowBefore,
|
||||
addRowAfter,
|
||||
moveTableRow,
|
||||
moveTableColumn,
|
||||
moveTableColumn: moveColumn,
|
||||
openTableFilter,
|
||||
deleteRow: () => deleteRows(),
|
||||
deleteTable: () => deleteTable,
|
||||
exportTable,
|
||||
@@ -172,6 +181,7 @@ export default class Table extends Node {
|
||||
new TableColumnResizePlugin(),
|
||||
new FixTablesPlugin(),
|
||||
new TableLayoutPlugin(),
|
||||
new TableFilterPlugin(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -16,13 +16,12 @@ import {
|
||||
isValidCellMarks,
|
||||
setCellAttrs,
|
||||
} from "../lib/table";
|
||||
import { hasTableRole } from "../queries/table";
|
||||
import Node from "./Node";
|
||||
import { presetColors, rgbaToHex } from "@shared/utils/color";
|
||||
import { parseToRgb, transparentize } from "polished";
|
||||
import type { RgbaColor } from "polished/lib/types/color";
|
||||
|
||||
const isTableNode = (node: ProsemirrorNode) => !!node.type.spec.tableRole;
|
||||
|
||||
export default class TableCell extends Node {
|
||||
/** The default opacity of the table cell background */
|
||||
static opacity = 0.7;
|
||||
@@ -159,7 +158,7 @@ export default class TableCell extends Node {
|
||||
// reflect the shape of the change, so they always rebuild.
|
||||
if (
|
||||
!isRemoteTransaction(tr, newState) &&
|
||||
isInlineTransaction(tr, isTableNode)
|
||||
isInlineTransaction(tr, hasTableRole)
|
||||
) {
|
||||
return pluginState.map(tr.mapping, tr.doc);
|
||||
}
|
||||
|
||||
@@ -1,19 +1,15 @@
|
||||
import type Token from "markdown-it/lib/token.mjs";
|
||||
import type { Node as ProsemirrorNode, NodeSpec } from "prosemirror-model";
|
||||
import type { NodeSpec } from "prosemirror-model";
|
||||
import type { EditorState } from "prosemirror-state";
|
||||
import { Plugin, PluginKey } from "prosemirror-state";
|
||||
import type { EditorView } from "prosemirror-view";
|
||||
import { DecorationSet, Decoration } from "prosemirror-view";
|
||||
import {
|
||||
isInTable,
|
||||
moveTableColumn,
|
||||
selectedRect,
|
||||
TableMap,
|
||||
} from "prosemirror-tables";
|
||||
import { addColumnBefore, selectColumn } from "../commands/table";
|
||||
import { isInTable, selectedRect, TableMap } from "prosemirror-tables";
|
||||
import { addColumnBefore, moveColumn, selectColumn } from "../commands/table";
|
||||
import { isMobile } from "../../utils/browser";
|
||||
import { isRemoteTransaction } from "../lib/multiplayer";
|
||||
import {
|
||||
focusEditor,
|
||||
cellWidget,
|
||||
getCellAttrs,
|
||||
getCellSpan,
|
||||
@@ -29,6 +25,7 @@ import { isInlineTransaction } from "../queries/isInlineTransaction";
|
||||
import {
|
||||
getCellsInColumn,
|
||||
getCellsInRow,
|
||||
hasTableRole,
|
||||
hasTableSelectionChanged,
|
||||
isColumnSelected,
|
||||
isTableSelected,
|
||||
@@ -157,7 +154,7 @@ function setupColumnDragTracking(
|
||||
currentToIndex < currentCols.length;
|
||||
|
||||
if (inBounds) {
|
||||
const moved = moveTableColumn({ from: fromIndex, to: currentToIndex })(
|
||||
const moved = moveColumn({ from: fromIndex, to: currentToIndex })(
|
||||
view.state,
|
||||
view.dispatch
|
||||
);
|
||||
@@ -221,8 +218,6 @@ function createColumnDragDecorations(state: EditorState): DecorationSet {
|
||||
return DecorationSet.create(state.doc, decorations);
|
||||
}
|
||||
|
||||
const isTableNode = (node: ProsemirrorNode) => !!node.type.spec.tableRole;
|
||||
|
||||
export default class TableHeader extends Node {
|
||||
get name() {
|
||||
return "th";
|
||||
@@ -457,7 +452,7 @@ export default class TableHeader extends Node {
|
||||
// reflect the shape of the change, so they always rebuild.
|
||||
if (
|
||||
!isRemoteTransaction(tr, newState) &&
|
||||
isInlineTransaction(tr, isTableNode)
|
||||
isInlineTransaction(tr, hasTableRole)
|
||||
) {
|
||||
return pluginState.map(tr.mapping, tr.doc);
|
||||
}
|
||||
@@ -493,7 +488,7 @@ export default class TableHeader extends Node {
|
||||
(pluginState === DecorationSet.empty && isInTable(newState)) ||
|
||||
(tr.docChanged &&
|
||||
(isRemoteTransaction(tr, newState) ||
|
||||
!isInlineTransaction(tr, isTableNode)))
|
||||
!isInlineTransaction(tr, hasTableRole)))
|
||||
) {
|
||||
return createColumnDecorations(newState);
|
||||
}
|
||||
@@ -534,6 +529,7 @@ 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
|
||||
|
||||
@@ -4,6 +4,7 @@ import { isInTable, moveTableRow, selectedRect } from "prosemirror-tables";
|
||||
import Node from "./Node";
|
||||
import { cn } from "../styles/utils";
|
||||
import {
|
||||
focusEditor,
|
||||
cellWidget,
|
||||
getCellSpan,
|
||||
setSpanPosition,
|
||||
@@ -386,6 +387,7 @@ export default class TableRow extends Node {
|
||||
if (tableGrip) {
|
||||
event.preventDefault();
|
||||
event.stopImmediatePropagation();
|
||||
focusEditor(view);
|
||||
selectTable()(view.state, view.dispatch);
|
||||
return true;
|
||||
}
|
||||
@@ -400,6 +402,7 @@ 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
|
||||
|
||||
@@ -0,0 +1,652 @@
|
||||
import { t } from "i18next";
|
||||
import type { Node } from "prosemirror-model";
|
||||
import type { EditorState, Transaction } from "prosemirror-state";
|
||||
import { Plugin, PluginKey } from "prosemirror-state";
|
||||
import { findTable, TableMap } from "prosemirror-tables";
|
||||
import { Decoration, DecorationSet } from "prosemirror-view";
|
||||
import { isRemoteTransaction } from "../lib/multiplayer";
|
||||
import { cellWidget } from "../lib/table";
|
||||
import {
|
||||
getHiddenTableRows,
|
||||
isEqualTableFilters,
|
||||
isTableFilterActive,
|
||||
isTableFilterable,
|
||||
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";
|
||||
import { cn } from "../styles/utils";
|
||||
import type { TableFilter } from "../types";
|
||||
|
||||
/** A summary of the filters on a table that has filters. */
|
||||
interface TableFilterSummary {
|
||||
/** The filters in effect for the current reader. */
|
||||
filters: TableFilter[];
|
||||
/** Whether the current reader changed the filters from the saved filters. */
|
||||
isModified: boolean;
|
||||
/** The number of rows shown, not including the header row. */
|
||||
visibleRows: number;
|
||||
/** The number of rows, not including the header row. */
|
||||
totalRows: number;
|
||||
}
|
||||
|
||||
/** A column of a table. */
|
||||
export interface TableFilterTarget {
|
||||
/** The position of the table. */
|
||||
pos: number;
|
||||
/** The index of the column. */
|
||||
column: number;
|
||||
}
|
||||
|
||||
/** The state of the table filter plugin. */
|
||||
interface TableFilterPluginState {
|
||||
/** Filters set by the current reader, by table position. */
|
||||
local: ReadonlyMap<number, TableFilter[]>;
|
||||
/** Summaries of the tables that have filters, by table position. */
|
||||
summaries: ReadonlyMap<number, TableFilterSummary>;
|
||||
/** The column whose filter menu is open. */
|
||||
open: TableFilterTarget | null;
|
||||
/** The position of the table whose filters the reader changed last. */
|
||||
changed: number | null;
|
||||
/** The decorations that hide rows and show filter controls. */
|
||||
decorations: DecorationSet;
|
||||
}
|
||||
|
||||
type TableFilterAction =
|
||||
| { type: "set"; pos: number; filters?: TableFilter[] }
|
||||
| {
|
||||
type: "remap";
|
||||
pos: number;
|
||||
mapColumn: (column: number) => number | undefined;
|
||||
}
|
||||
| { type: "open"; target: TableFilterTarget }
|
||||
| { type: "close" };
|
||||
|
||||
/** The key of the table filter plugin. */
|
||||
export const tableFilterPluginKey = new PluginKey<TableFilterPluginState>(
|
||||
"table-filter"
|
||||
);
|
||||
|
||||
/**
|
||||
* Set the filters of a table for the current reader only. The document does
|
||||
* not change.
|
||||
*
|
||||
* @param tr the transaction.
|
||||
* @param pos the position of the table.
|
||||
* @param filters the filters.
|
||||
* @returns the transaction.
|
||||
*/
|
||||
export function setLocalTableFilters(
|
||||
tr: Transaction,
|
||||
pos: number,
|
||||
filters: TableFilter[]
|
||||
): Transaction {
|
||||
return setAction(tr, { type: "set", pos, filters });
|
||||
}
|
||||
|
||||
/**
|
||||
* Change the columns that the filters of a table apply to, in the saved
|
||||
* filters and in the filters of the current reader. Use this in a transaction
|
||||
* that inserts, removes or moves columns.
|
||||
*
|
||||
* @param tr the transaction.
|
||||
* @param pos the position of the table, after the transaction.
|
||||
* @param mapColumn returns the new index of a column, or undefined if removed.
|
||||
* @returns the transaction.
|
||||
*/
|
||||
export function remapTableColumnFilters(
|
||||
tr: Transaction,
|
||||
pos: number,
|
||||
mapColumn: (column: number) => number | undefined
|
||||
): Transaction {
|
||||
const table = tr.doc.nodeAt(pos);
|
||||
if (table?.type.spec.tableRole === "table" && table.attrs.filters) {
|
||||
const filters = remapTableFilters(
|
||||
parseTableFilters(table.attrs.filters),
|
||||
mapColumn
|
||||
);
|
||||
tr.setNodeAttribute(pos, "filters", filters.length ? filters : null);
|
||||
}
|
||||
return tr.setMeta(tableFilterPluginKey, { type: "remap", pos, mapColumn });
|
||||
}
|
||||
|
||||
/**
|
||||
* Open the filter menu for a column of a table.
|
||||
*
|
||||
* @param tr the transaction.
|
||||
* @param target the column.
|
||||
* @returns the transaction.
|
||||
*/
|
||||
export function openTableFilterMenu(
|
||||
tr: Transaction,
|
||||
target: TableFilterTarget
|
||||
): Transaction {
|
||||
return setAction(tr, { type: "open", target });
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the open table filter menu.
|
||||
*
|
||||
* @param tr the transaction.
|
||||
* @returns the transaction.
|
||||
*/
|
||||
export function closeTableFilterMenu(tr: Transaction): Transaction {
|
||||
return setAction(tr, { type: "close" });
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* for themselves without changing the document.
|
||||
*/
|
||||
export class TableFilterPlugin extends Plugin<TableFilterPluginState> {
|
||||
constructor() {
|
||||
super({
|
||||
key: tableFilterPluginKey,
|
||||
state: {
|
||||
init: (_, state) => {
|
||||
const local = new Map<number, TableFilter[]>();
|
||||
const decorations: Decoration[] = [];
|
||||
const summaries = new Map<number, TableFilterSummary>();
|
||||
buildTables(
|
||||
state.doc,
|
||||
0,
|
||||
getSelectionRow(state),
|
||||
local,
|
||||
decorations,
|
||||
summaries
|
||||
);
|
||||
|
||||
return {
|
||||
local,
|
||||
summaries,
|
||||
open: null,
|
||||
changed: null,
|
||||
decorations: DecorationSet.create(state.doc, decorations),
|
||||
};
|
||||
},
|
||||
apply,
|
||||
},
|
||||
props: {
|
||||
decorations(state) {
|
||||
return this.getState(state)?.decorations;
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function setAction(tr: Transaction, action: TableFilterAction) {
|
||||
return tr
|
||||
.setMeta(tableFilterPluginKey, action)
|
||||
.setMeta("addToHistory", false);
|
||||
}
|
||||
|
||||
function saveTableFilters(state: EditorState, pos: number) {
|
||||
const summary = tableFilterPluginKey.getState(state)?.summaries.get(pos);
|
||||
if (!summary) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const filters = summary.filters.filter(isTableFilterActive);
|
||||
return state.tr
|
||||
.setNodeAttribute(pos, "filters", filters.length ? filters : null)
|
||||
.setMeta(tableFilterPluginKey, { type: "set", pos });
|
||||
}
|
||||
|
||||
function apply(
|
||||
tr: Transaction,
|
||||
prev: TableFilterPluginState,
|
||||
oldState: EditorState,
|
||||
state: EditorState
|
||||
): TableFilterPluginState {
|
||||
const action: TableFilterAction | undefined =
|
||||
tr.getMeta(tableFilterPluginKey);
|
||||
if (!action && !tr.docChanged && !tr.selectionSet) {
|
||||
return prev;
|
||||
}
|
||||
|
||||
let { local, summaries, open, changed, decorations } = prev;
|
||||
let rebuildAll = false;
|
||||
|
||||
// The positions of the tables to build again.
|
||||
const stale = new Set<number>();
|
||||
|
||||
if (tr.docChanged) {
|
||||
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 before = tr.before.nodeAt(pos);
|
||||
const after = tr.doc.nodeAt(next);
|
||||
return (
|
||||
action?.type === "remap" ||
|
||||
!before ||
|
||||
!after ||
|
||||
TableMap.get(before).width === TableMap.get(after).width
|
||||
);
|
||||
});
|
||||
|
||||
const openPos = open ? mapPos(open.pos) : undefined;
|
||||
open = open && openPos !== undefined ? { ...open, pos: openPos } : null;
|
||||
changed = changed === null ? null : (mapPos(changed) ?? null);
|
||||
|
||||
if (isRemote || !isInlineTransaction(tr, hasTableRole)) {
|
||||
rebuildAll = true;
|
||||
} else {
|
||||
decorations = decorations.map(tr.mapping, tr.doc);
|
||||
summaries = mapKeys(summaries, mapPos);
|
||||
|
||||
// Edits to the text of a filtered table can change which rows match.
|
||||
prev.summaries.forEach((_, pos) => {
|
||||
const next = mapPos(pos);
|
||||
if (
|
||||
next !== undefined &&
|
||||
tr.before.nodeAt(pos) !== tr.doc.nodeAt(next)
|
||||
) {
|
||||
stale.add(next);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (action) {
|
||||
switch (action.type) {
|
||||
case "set": {
|
||||
const next = new Map(local);
|
||||
if (action.filters) {
|
||||
next.set(action.pos, action.filters);
|
||||
} else {
|
||||
next.delete(action.pos);
|
||||
}
|
||||
local = next;
|
||||
changed = action.pos;
|
||||
stale.add(action.pos);
|
||||
break;
|
||||
}
|
||||
case "remap": {
|
||||
const filters = local.get(action.pos);
|
||||
if (filters) {
|
||||
local = new Map(local).set(
|
||||
action.pos,
|
||||
remapTableFilters(filters, action.mapColumn)
|
||||
);
|
||||
}
|
||||
if (open?.pos === action.pos) {
|
||||
const column = action.mapColumn(open.column);
|
||||
open = column === undefined ? null : { ...open, column };
|
||||
}
|
||||
stale.add(action.pos);
|
||||
break;
|
||||
}
|
||||
case "open":
|
||||
open = action.target;
|
||||
break;
|
||||
case "close":
|
||||
open = null;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// The row that holds the selection is 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);
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!rebuildAll && !stale.size) {
|
||||
return { local, summaries, open, changed, decorations };
|
||||
}
|
||||
|
||||
const selectionRow = getSelectionRow(state);
|
||||
const found: Decoration[] = [];
|
||||
|
||||
if (rebuildAll || stale.size > 1) {
|
||||
const nextSummaries = new Map<number, TableFilterSummary>();
|
||||
buildTables(state.doc, 0, selectionRow, local, found, nextSummaries);
|
||||
return {
|
||||
local,
|
||||
summaries: nextSummaries,
|
||||
open,
|
||||
changed,
|
||||
decorations: DecorationSet.create(state.doc, found),
|
||||
};
|
||||
}
|
||||
|
||||
// Build a single table, and the tables inside it, in place of their old
|
||||
// decorations.
|
||||
const [pos] = stale;
|
||||
const table = state.doc.nodeAt(pos);
|
||||
if (table?.type.spec.tableRole === "table") {
|
||||
const end = pos + table.nodeSize;
|
||||
const nextSummaries = new Map(summaries);
|
||||
nextSummaries.forEach((_, key) => {
|
||||
if (key >= pos && key < end) {
|
||||
nextSummaries.delete(key);
|
||||
}
|
||||
});
|
||||
buildTable(table, pos, selectionRow, local, found, nextSummaries);
|
||||
buildTables(table, pos + 1, selectionRow, local, found, nextSummaries);
|
||||
decorations = decorations
|
||||
.remove(decorations.find(pos + 1, end))
|
||||
.add(state.doc, found);
|
||||
summaries = nextSummaries;
|
||||
}
|
||||
|
||||
return { local, summaries, open, changed, decorations };
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the decorations and summaries of the tables inside a node.
|
||||
*
|
||||
* @param node the node to search.
|
||||
* @param start the position of the start of the node content.
|
||||
* @param selectionRow the position of the row that holds the selection.
|
||||
* @param local the filters of the current reader.
|
||||
* @param decorations the list to add decorations to.
|
||||
* @param summaries the map to add summaries to.
|
||||
*/
|
||||
function buildTables(
|
||||
node: Node,
|
||||
start: number,
|
||||
selectionRow: number | null,
|
||||
local: ReadonlyMap<number, TableFilter[]>,
|
||||
decorations: Decoration[],
|
||||
summaries: Map<number, TableFilterSummary>
|
||||
) {
|
||||
node.descendants((child, offset) => {
|
||||
if (child.type.spec.tableRole === "table") {
|
||||
buildTable(
|
||||
child,
|
||||
start + offset,
|
||||
selectionRow,
|
||||
local,
|
||||
decorations,
|
||||
summaries
|
||||
);
|
||||
return true;
|
||||
}
|
||||
return child.isBlock && !child.isTextblock;
|
||||
});
|
||||
}
|
||||
|
||||
function buildTable(
|
||||
node: Node,
|
||||
pos: number,
|
||||
selectionRow: number | null,
|
||||
local: ReadonlyMap<number, TableFilter[]>,
|
||||
decorations: Decoration[],
|
||||
summaries: Map<number, TableFilterSummary>
|
||||
) {
|
||||
if (!isTableFilterable(node)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const map = TableMap.get(node);
|
||||
const tableStart = pos + 1;
|
||||
const saved = parseTableFilters(node.attrs.filters);
|
||||
const localFilters = local.get(pos);
|
||||
const filters = (localFilters ?? saved).filter(
|
||||
(filter) => filter.column < map.width
|
||||
);
|
||||
const activeColumns = new Set(
|
||||
filters.filter(isTableFilterActive).map((filter) => filter.column)
|
||||
);
|
||||
|
||||
// A cell that spans several columns holds the button of the first one.
|
||||
for (let column = 0; column < map.width; column++) {
|
||||
if (column > 0 && map.map[column - 1] === map.map[column]) {
|
||||
continue;
|
||||
}
|
||||
decorations.push(
|
||||
buildFilterButton(
|
||||
tableStart + map.map[column],
|
||||
column,
|
||||
activeColumns.has(column)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (!saved.length && !localFilters) {
|
||||
return;
|
||||
}
|
||||
|
||||
const hidden = new Set(getHiddenTableRows(node, filters));
|
||||
let visibleRows = 0;
|
||||
|
||||
node.forEach((row, offset, index) => {
|
||||
const rowPos = tableStart + offset;
|
||||
if (index === 0) {
|
||||
return;
|
||||
}
|
||||
if (hidden.has(index) && rowPos !== selectionRow) {
|
||||
decorations.push(
|
||||
Decoration.node(
|
||||
rowPos,
|
||||
rowPos + row.nodeSize,
|
||||
{ class: EditorStyleHelper.tableRowFiltered },
|
||||
{ filtered: true }
|
||||
)
|
||||
);
|
||||
return;
|
||||
}
|
||||
visibleRows++;
|
||||
});
|
||||
|
||||
const summary: TableFilterSummary = {
|
||||
filters,
|
||||
isModified:
|
||||
localFilters !== undefined && !isEqualTableFilters(localFilters, saved),
|
||||
visibleRows,
|
||||
totalRows: map.height - 1,
|
||||
};
|
||||
summaries.set(pos, summary);
|
||||
|
||||
if (activeColumns.size > 0 || summary.isModified) {
|
||||
decorations.push(
|
||||
buildFilterBar(pos + node.nodeSize, summary, activeColumns.size)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function buildFilterButton(cellPos: number, column: number, active: boolean) {
|
||||
const className = cn(EditorStyleHelper.tableFilterButton, { active });
|
||||
|
||||
return cellWidget(
|
||||
cellPos,
|
||||
(view, getPos) => {
|
||||
const button = buildButton(className, () => {
|
||||
const widgetPos = getPos();
|
||||
const pos =
|
||||
widgetPos === undefined
|
||||
? undefined
|
||||
: findTable(view.state.doc.resolve(widgetPos))?.pos;
|
||||
if (pos === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { open } = tableFilterPluginKey.getState(view.state) ?? {};
|
||||
view.dispatch(
|
||||
open?.pos === pos && open.column === column
|
||||
? closeTableFilterMenu(view.state.tr)
|
||||
: openTableFilterMenu(view.state.tr, { pos, column })
|
||||
);
|
||||
});
|
||||
button.setAttribute("aria-haspopup", "dialog");
|
||||
button.setAttribute(
|
||||
"aria-label",
|
||||
active ? t("Change column filter") : t("Filter column")
|
||||
);
|
||||
return button;
|
||||
},
|
||||
{
|
||||
key: cn(className, column),
|
||||
ignoreSelection: true,
|
||||
stopEvent: () => true,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
function buildFilterBar(
|
||||
pos: number,
|
||||
summary: TableFilterSummary,
|
||||
activeCount: number
|
||||
) {
|
||||
const { visibleRows, totalRows, isModified } = summary;
|
||||
|
||||
return Decoration.widget(
|
||||
pos,
|
||||
(view, getPos) => {
|
||||
const getTablePos = () => {
|
||||
const widgetPos = getPos();
|
||||
const table =
|
||||
widgetPos === undefined
|
||||
? undefined
|
||||
: view.state.doc.resolve(widgetPos).nodeBefore;
|
||||
return widgetPos !== undefined && table
|
||||
? widgetPos - table.nodeSize
|
||||
: undefined;
|
||||
};
|
||||
|
||||
const bar = document.createElement("div");
|
||||
bar.className = cn(EditorStyleHelper.tableFilterBar, {
|
||||
inactive: activeCount === 0,
|
||||
});
|
||||
|
||||
const label = document.createElement("span");
|
||||
label.textContent = activeCount
|
||||
? `${t("{{ count }} filter applied", { count: activeCount })} · ${t(
|
||||
"{{ visible }} of {{ total }} rows",
|
||||
{ visible: visibleRows, total: totalRows }
|
||||
)}`
|
||||
: t("Filters cleared for you");
|
||||
bar.appendChild(label);
|
||||
|
||||
if (activeCount) {
|
||||
const clear = buildButton("clear", () => {
|
||||
const tablePos = getTablePos();
|
||||
if (tablePos !== undefined) {
|
||||
view.dispatch(setLocalTableFilters(view.state.tr, tablePos, []));
|
||||
}
|
||||
});
|
||||
clear.textContent = t("Clear");
|
||||
bar.appendChild(clear);
|
||||
}
|
||||
|
||||
if (isModified) {
|
||||
const save = buildButton("save", () => {
|
||||
const tablePos = getTablePos();
|
||||
const tr =
|
||||
view.editable && tablePos !== undefined
|
||||
? saveTableFilters(view.state, tablePos)
|
||||
: undefined;
|
||||
if (tr) {
|
||||
view.dispatch(tr);
|
||||
}
|
||||
});
|
||||
save.textContent = t("Save for everyone");
|
||||
bar.appendChild(save);
|
||||
}
|
||||
|
||||
return bar;
|
||||
},
|
||||
{
|
||||
side: -1,
|
||||
key: `table-filter-bar-${activeCount}-${visibleRows}-${totalRows}-${isModified}`,
|
||||
ignoreSelection: true,
|
||||
stopEvent: () => true,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a button that does not take the focus from the editor on press.
|
||||
*/
|
||||
function buildButton(className: string, onClick: () => void) {
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.className = className;
|
||||
button.addEventListener("mousedown", (event) => {
|
||||
event.preventDefault();
|
||||
});
|
||||
button.addEventListener("click", (event) => {
|
||||
event.preventDefault();
|
||||
onClick();
|
||||
});
|
||||
return button;
|
||||
}
|
||||
|
||||
function getSelectionRow(state: EditorState): number | null {
|
||||
return (
|
||||
findParentNodeClosestToPos(
|
||||
state.selection.$head,
|
||||
(node) => node.type.spec.tableRole === "row"
|
||||
)?.pos ?? null
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
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;
|
||||
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];
|
||||
};
|
||||
}
|
||||
|
||||
return (pos) => {
|
||||
const mapped = tr.mapping.map(pos, 1);
|
||||
return tr.doc.nodeAt(mapped)?.type.spec.tableRole === "table"
|
||||
? mapped
|
||||
: undefined;
|
||||
};
|
||||
}
|
||||
|
||||
function mapKeys<T>(
|
||||
map: ReadonlyMap<number, T>,
|
||||
mapPos: (pos: number) => number | undefined,
|
||||
keep: (pos: number, next: number) => boolean = () => true
|
||||
): ReadonlyMap<number, T> {
|
||||
if (!map.size) {
|
||||
return map;
|
||||
}
|
||||
|
||||
const next = new Map<number, T>();
|
||||
map.forEach((value, pos) => {
|
||||
const mapped = mapPos(pos);
|
||||
if (mapped !== undefined && keep(pos, mapped)) {
|
||||
next.set(mapped, value);
|
||||
}
|
||||
});
|
||||
return next;
|
||||
}
|
||||
@@ -15,6 +15,16 @@ import type { NodeAttrMark, NodeAttrMarkName } from "../types";
|
||||
import type { Node } from "prosemirror-model";
|
||||
import type { Selection } from "prosemirror-state";
|
||||
|
||||
/**
|
||||
* Whether a node is part of a table: the table, a row or a cell.
|
||||
*
|
||||
* @param node the node.
|
||||
* @returns true if the node has a table role.
|
||||
*/
|
||||
export function hasTableRole(node: Node): boolean {
|
||||
return !!node.type.spec.tableRole;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the current selection is a column selection.
|
||||
* @param state The editor state.
|
||||
|
||||
@@ -197,6 +197,15 @@ export class EditorStyleHelper {
|
||||
/** Drag indicator on bottom side of cell */
|
||||
static readonly tableDragIndicatorBottom = "table-drag-indicator-bottom";
|
||||
|
||||
/** Table row hidden by a filter */
|
||||
static readonly tableRowFiltered = "table-row-filtered";
|
||||
|
||||
/** Button in a header cell that opens the column filter */
|
||||
static readonly tableFilterButton = "table-filter-button";
|
||||
|
||||
/** Bar below a filtered table with the filter summary */
|
||||
static readonly tableFilterBar = "table-filter-bar";
|
||||
|
||||
// Drag and drop
|
||||
|
||||
/** Line that shows where dragged content will be dropped */
|
||||
|
||||
@@ -25,6 +25,35 @@ export enum TableLayout {
|
||||
fullWidth = "full-width",
|
||||
}
|
||||
|
||||
/** How a table filter compares the cells of a column. */
|
||||
export enum TableFilterOperator {
|
||||
/** The cell matches one of the values. */
|
||||
Is = "is",
|
||||
/** The cell matches none of the values. */
|
||||
IsNot = "isNot",
|
||||
/** The cell has no text. */
|
||||
IsEmpty = "isEmpty",
|
||||
/** The cell has text. */
|
||||
IsNotEmpty = "isNotEmpty",
|
||||
/** The cell includes the text. */
|
||||
Contains = "contains",
|
||||
/** The cell does not include the text. */
|
||||
DoesNotContain = "doesNotContain",
|
||||
}
|
||||
|
||||
/** A condition on one column that rows of a table must meet to be shown. */
|
||||
export interface TableFilter {
|
||||
/** The index of the column. */
|
||||
column: number;
|
||||
/** How the cells of the column are compared. */
|
||||
operator: TableFilterOperator;
|
||||
/**
|
||||
* The values to compare cells with. The "is" and "is not" operators use all
|
||||
* of them, and the "contains" and "does not contain" operators use the first.
|
||||
*/
|
||||
values: string[];
|
||||
}
|
||||
|
||||
/** How a selection toolbar menu is presented. */
|
||||
export enum MenuType {
|
||||
/** A horizontal strip of buttons; nested options open behind a trigger. */
|
||||
|
||||
@@ -6,6 +6,7 @@ import type { Plugin } from "prosemirror-state";
|
||||
import ExtensionManager from "../editor/lib/ExtensionManager";
|
||||
import { populateEmojiData } from "../editor/lib/emoji";
|
||||
import { richExtensions } from "../editor/nodes";
|
||||
import type { TableFilter } from "../editor/types";
|
||||
|
||||
// Match the server, which loads emoji data before it builds the parser.
|
||||
populateEmojiData(data as EmojiMartData);
|
||||
@@ -145,7 +146,7 @@ export function tr(cells: ReturnType<typeof td | typeof th>[]) {
|
||||
*/
|
||||
export function table(
|
||||
rows: ReturnType<typeof tr>[],
|
||||
attrs?: { layout?: string | null }
|
||||
attrs?: { layout?: string | null; filters?: TableFilter[] | null }
|
||||
) {
|
||||
return schema.nodes.table.create(attrs ?? null, rows);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user