for the most part switched out the grid's internals for the new table component

This commit is contained in:
Chris Kruining 2024-12-11 16:24:54 +01:00
parent 6d74950495
commit d219ae1f9a
No known key found for this signature in database
GPG key ID: EB894A3560CCCAD2
8 changed files with 151 additions and 218 deletions

View file

@ -1,22 +1,16 @@
import { Accessor, Component, createContext, createEffect, createMemo, createSignal, For, ParentComponent, Show, useContext } from "solid-js";
import { createStore, produce, unwrap } from "solid-js/store";
import { SelectionProvider, useSelection, selectable } from "../selectable";
import { debounce, deepCopy, deepDiff, Mutation } from "~/utilities";
import { debounce, deepCopy, deepDiff, Mutation, splitAt } from "~/utilities";
import { DataSetRowNode, DataSetNode, SelectionMode, Table } from "~/components/table";
import css from './grid.module.css';
selectable // prevents removal of import
interface Leaf extends Record<string, string> { }
export interface Entry extends Record<string, Entry | Leaf> { }
type Rows = Map<string, Record<string, string>>;
type SelectionItem = { key: string, value: Accessor<Record<string, string>>, element: WeakRef<HTMLElement> };
export interface GridContextType {
readonly rows: Accessor<Record<string, Record<string, string>>>;
readonly rows: Accessor<Rows>;
readonly mutations: Accessor<Mutation[]>;
readonly selection: Accessor<SelectionItem[]>;
mutate(prop: string, lang: string, value: string): void;
// readonly selection: Accessor<SelectionItem[]>;
mutate(prop: string, value: string): void;
remove(props: string[]): void;
insert(prop: string): void;
addColumn(name: string): void;
@ -35,11 +29,10 @@ export interface GridApi {
const GridContext = createContext<GridContextType>();
const isLeaf = (entry: Entry | Leaf): entry is Leaf => Object.values(entry).some(v => typeof v === 'string');
const useGrid = () => useContext(GridContext)!;
export const Grid: Component<{ class?: string, columns: string[], rows: Rows, api?: (api: GridApi) => any }> = (props) => {
const [selection, setSelection] = createSignal<SelectionItem[]>([]);
const [table, setTable] = createSignal();
const [state, setState] = createStore<{ rows: Record<string, Record<string, string>>, columns: string[], snapshot: Rows, numberOfRows: number }>({
rows: {},
columns: [],
@ -53,8 +46,25 @@ export const Grid: Component<{ class?: string, columns: string[], rows: Rows, ap
return deepDiff(state.snapshot, state.rows).toArray();
});
const rows = createMemo(() => Object.fromEntries(Object.entries(state.rows).map(([key, row]) => [key, unwrap(row)] as const)));
const columns = createMemo(() => state.columns);
type Entry = { key: string, [lang: string]: string };
const groupBy = (rows: DataSetRowNode<Entry>[]) => {
const group = (nodes: DataSetRowNode<Entry>[]): DataSetNode<Entry>[] => Object
.entries(Object.groupBy(nodes, r => r.key.split('.').at(0)!) as Record<string, DataSetRowNode<Entry>[]>)
.map<DataSetNode<Entry>>(([key, nodes]) => nodes.at(0)?.key === key
? { ...nodes[0], key: nodes[0].value.key, value: { ...nodes[0].value, key: nodes[0].key } }
: ({ kind: 'group', key, groupedBy: 'key', nodes: group(nodes.map(n => ({ ...n, key: n.key.slice(key.length + 1) }))) })
);
return group(rows.map(r => ({ ...r, key: r.value.key })));
}
const rows = createMemo(() => Object.entries(state.rows).map(([key, values]) => ({ key, ...values })));
const columns = createMemo(() => [
{ id: 'key', label: 'Key', groupBy },
...state.columns.map(c => ({ id: c, label: c })),
]);
createEffect(() => {
setState('rows', Object.fromEntries(deepCopy(props.rows).entries()));
@ -72,10 +82,12 @@ export const Grid: Component<{ class?: string, columns: string[], rows: Rows, ap
const ctx: GridContextType = {
rows,
mutations,
selection,
// selection,
mutate(prop: string, lang: string, value: string) {
setState('rows', prop, lang, value);
mutate(prop: string, value: string) {
const [key, lang] = splitAt(prop, prop.lastIndexOf('.'));
setState('rows', key, lang, value);
},
remove(props: string[]) {
@ -89,11 +101,7 @@ export const Grid: Component<{ class?: string, columns: string[], rows: Rows, ap
},
insert(prop: string) {
setState('rows', produce(rows => {
rows[prop] = Object.fromEntries(state.columns.slice(1).map(lang => [lang, '']));
return rows
}))
setState('rows', prop, Object.fromEntries(state.columns.map(lang => [lang, ''])));
},
addColumn(name: string): void {
@ -107,145 +115,68 @@ export const Grid: Component<{ class?: string, columns: string[], rows: Rows, ap
};
return <GridContext.Provider value={ctx}>
<SelectionProvider selection={setSelection} multiSelect>
<Api api={props.api} />
<Api api={props.api} table={table()} />
<_Grid class={props.class} columns={columns()} rows={rows()} />
</SelectionProvider>
<Table api={setTable} class={props.class} rows={rows()} columns={columns()} groupBy="key" selectionMode={SelectionMode.Multiple}>{
Object.fromEntries(state.columns.map(c => [c, ({ key, value }: any) => {
return <TextArea key={key} value={value} oninput={(e) => ctx.mutate(key, e.data ?? '')} />;
}]))
}</Table>
</GridContext.Provider>;
};
const _Grid: Component<{ class?: string, columns: string[], rows: Record<string, Record<string, string>> }> = (props) => {
const columnCount = createMemo(() => props.columns.length - 1);
const root = createMemo<Entry>(() => Object.entries(props.rows)
.reduce((aggregate, [key, value]) => {
let obj: any = aggregate;
const parts = key.split('.');
for (const [i, part] of parts.entries()) {
if (Object.hasOwn(obj, part) === false) {
obj[part] = {};
}
if (i === (parts.length - 1)) {
obj[part] = value;
}
else {
obj = obj[part];
}
}
return aggregate;
}, {}));
return <section class={`${css.table} ${props.class}`} style={{ '--columns': columnCount() }}>
<Head headers={props.columns} />
<main class={css.main}>
<Row entry={root()} />
</main>
</section>
};
const Api: Component<{ api: undefined | ((api: GridApi) => any) }> = (props) => {
const Api: Component<{ api: undefined | ((api: GridApi) => any), table?: any }> = (props) => {
const gridContext = useGrid();
const selectionContext = useSelection<{ key: string, value: Accessor<Record<string, string>>, element: WeakRef<HTMLElement> }>();
const api: GridApi = {
selection: createMemo(() => {
const selection = selectionContext.selection();
const api = createMemo<GridApi | undefined>(() => {
const table = props.table;
return Object.fromEntries(selection.map(({ key, value }) => [key, value()] as const));
}),
rows: gridContext.rows,
mutations: gridContext.mutations,
selectAll() {
selectionContext.selectAll();
},
clear() {
selectionContext.clear();
},
remove(props: string[]) {
gridContext.remove(props);
},
insert(prop: string) {
gridContext.insert(prop);
},
if (!table) {
return;
}
addColumn(name: string): void {
gridContext.addColumn(name);
},
};
return {
selection: createMemo(() => {
const selection = props.table?.selection() ?? [];
return Object.fromEntries(selection.map(({ key, value }) => [key, value()] as const));
}),
rows: createMemo(() => props.table?.rows ?? []),
mutations: gridContext.mutations,
selectAll() {
props.table.selectAll();
},
clear() {
props.table.clear();
},
remove(props: string[]) {
gridContext.remove(props);
},
insert(prop: string) {
gridContext.insert(prop);
},
addColumn(name: string): void {
gridContext.addColumn(name);
},
};
});
createEffect(() => {
props.api?.(api);
const value = api();
if (value) {
props.api?.(value);
}
});
return null;
};
const Head: Component<{ headers: string[] }> = (props) => {
const context = useSelection();
return <header class={css.header}>
<div class={css.cell}>
<input
type="checkbox"
checked={context.selection().length > 0 && context.selection().length === context.length()}
indeterminate={context.selection().length !== 0 && context.selection().length !== context.length()}
on:input={(e: InputEvent) => e.target.checked ? context.selectAll() : context.clear()}
/>
</div>
<For each={props.headers}>{
header => <span class={css.cell}>{header}</span>
}</For>
</header>;
};
const Row: Component<{ entry: Entry, path?: string[] }> = (props) => {
const grid = useGrid();
return <For each={Object.entries(props.entry)}>{
([key, value]) => {
const values = Object.entries(value);
const path = [...(props.path ?? []), key];
const k = path.join('.');
const context = useSelection();
const isSelected = context.isSelected(k);
return <Show when={isLeaf(value)} fallback={<Group key={key} entry={value as Entry} path={path} />}>
<div class={css.row} use:selectable={{ value, key: k }}>
<div class={css.cell}>
<input type="checkbox" checked={isSelected()} on:input={() => context.select([k])} on:pointerdown={e => e.stopPropagation()} />
</div>
<div class={css.cell}>
<span style={{ '--depth': path.length - 1 }}>{key}</span>
</div>
<For each={values}>{
([lang, value]) => <div class={css.cell}>
<TextArea key={k} value={value} lang={lang} oninput={(e) => grid.mutate(k, lang, e.data ?? '')} />
</div>
}</For>
</div>
</Show>;
}
}</For>
};
const Group: Component<{ key: string, entry: Entry, path: string[] }> = (props) => {
return <details open>
<summary style={{ '--depth': props.path.length - 1 }}>{props.key}</summary>
<Row entry={props.entry} path={props.path} />
</details>;
};
const TextArea: Component<{ key: string, value: string, lang: string, oninput?: (event: InputEvent) => any }> = (props) => {
const TextArea: Component<{ key: string, value: string, oninput?: (event: InputEvent) => any }> = (props) => {
const [element, setElement] = createSignal<HTMLTextAreaElement>();
const key = createMemo(() => props.key.slice(0, props.key.lastIndexOf('.')));
const lang = createMemo(() => props.key.slice(props.key.lastIndexOf('.') + 1));
const resize = () => {
const el = element();
@ -272,9 +203,9 @@ const TextArea: Component<{ key: string, value: string, lang: string, oninput?:
return <textarea
ref={setElement}
value={props.value}
lang={props.lang}
placeholder={`${props.key} in ${props.lang}`}
name={`${props.key}:${props.lang}`}
lang={lang()}
placeholder={`${key()} in ${lang()}`}
name={`${key()}:${lang()}`}
spellcheck={true}
wrap="soft"
onkeyup={onKeyUp}