polished the UI a bit. next up: saving changes (and maybe a diff ui as confirmation dialog)

This commit is contained in:
Chris Kruining 2024-10-16 16:13:12 +02:00
parent 1a963a665e
commit 7db65413be
No known key found for this signature in database
GPG key ID: EB894A3560CCCAD2
9 changed files with 323 additions and 117 deletions

View file

@ -0,0 +1,15 @@
.menu {
position: fixed;
display: grid;
grid-template-columns: max-content;
inset-inline-start: anchor(start);
inset-block-start: anchor(end);
margin: 0;
background-color: var(--surface-1);
color: var(--text-1);
border: none;
padding: var(--padding-m);
}

View file

@ -0,0 +1,84 @@
import { Accessor, Component, createContext, createEffect, createMemo, createSignal, createUniqueId, For, JSX, ParentComponent, useContext } from "solid-js";
import { CommandType } from "./index";
import css from "./contextMenu.module.css";
interface ContextMenuType {
readonly commands: Accessor<CommandType[]>;
readonly target: Accessor<HTMLElement | undefined>;
show(element: HTMLElement): void;
hide(): void;
}
const ContextMenu = createContext<ContextMenuType>()
const Root: ParentComponent<{ commands: CommandType[] }> = (props) => {
const [target, setTarget] = createSignal<HTMLElement>();
const context = {
commands: createMemo(() => props.commands),
target,
show(element: HTMLElement) {
setTarget(element);
},
hide() {
setTarget(undefined);
},
};
return <ContextMenu.Provider value={context}>
{props.children}
</ContextMenu.Provider>
};
const Menu: Component<{ children: (command: CommandType) => JSX.Element }> = (props) => {
const context = useContext(ContextMenu)!;
const [root, setRoot] = createSignal<HTMLElement>();
createEffect(() => {
const target = context.target();
const menu = root();
if (!menu) {
return;
}
if (target) {
menu.showPopover();
}
else {
menu.hidePopover();
}
});
const onToggle = (e: ToggleEvent) => {
if (e.newState === 'closed') {
context.hide();
}
};
const onCommand = (command: CommandType) => (e: PointerEvent) => {
context.hide();
command();
};
return <ul ref={setRoot} class={css.menu} style={`position-anchor: ${context.target()?.style.getPropertyValue('anchor-name')};`} popover ontoggle={onToggle}>
<For each={context.commands()}>{
command => <li onpointerdown={onCommand(command)}>{props.children(command)}</li>
}</For>
</ul>;
};
const Handle: ParentComponent = (props) => {
const context = useContext(ContextMenu)!;
return <span style={`anchor-name: --context-menu-handle-${createUniqueId()};`} oncontextmenu={(e) => {
e.preventDefault();
context.show(e.target as HTMLElement);
return false;
}}>{props.children}</span>;
};
export const Context = { Root, Menu, Handle };

View file

@ -1,33 +0,0 @@
export enum Modifier {
None = 0,
Shift = 1 << 0,
Control = 1 << 1,
Meta = 1 << 2,
Alt = 1 << 3,
}
export interface Command {
(): any;
label: string;
shortcut?: {
key: string;
modifier: Modifier;
};
}
export const createCommand = (label: string, command: () => any, shortcut?: Command['shortcut']): Command => {
return Object.defineProperties(command as Command, {
label: {
value: label,
configurable: false,
writable: false,
},
shortcut: {
value: shortcut ? { key: shortcut.key.toLowerCase(), modifier: shortcut.modifier } : undefined,
configurable: false,
writable: false,
}
});
};
export const noop = createCommand('noop', () => { });

View file

@ -0,0 +1,53 @@
import { Component, Show } from 'solid-js';
export enum Modifier {
None = 0,
Shift = 1 << 0,
Control = 1 << 1,
Meta = 1 << 2,
Alt = 1 << 3,
}
export interface CommandType {
(): any;
label: string;
shortcut?: {
key: string;
modifier: Modifier;
};
}
export const createCommand = (label: string, command: () => any, shortcut?: CommandType['shortcut']): CommandType => {
return Object.defineProperties(command as CommandType, {
label: {
value: label,
configurable: false,
writable: false,
},
shortcut: {
value: shortcut ? { key: shortcut.key.toLowerCase(), modifier: shortcut.modifier } : undefined,
configurable: false,
writable: false,
}
});
};
export const noop = createCommand('noop', () => { });
export const Command: Component<{ command: CommandType }> = (props) => {
return <>
{props.command.label}
<Show when={props.command.shortcut}>{
shortcut => {
const shift = shortcut().modifier & Modifier.Shift ? 'Shft+' : '';
const ctrl = shortcut().modifier & Modifier.Control ? 'Ctrl+' : '';
const meta = shortcut().modifier & Modifier.Meta ? 'Meta+' : '';
const alt = shortcut().modifier & Modifier.Alt ? 'Alt+' : '';
return <sub>{ctrl}{shift}{meta}{alt}{shortcut().key}</sub>;
}
}</Show>
</>;
};
export { Context } from './contextMenu';

View file

@ -20,20 +20,28 @@ const debounce = <T extends (...args: any[]) => void>(callback: T, delay: number
interface Leaf extends Record<string, string> { } interface Leaf extends Record<string, string> { }
export interface Entry extends Record<string, Entry | Leaf> { } export interface Entry extends Record<string, Entry | Leaf> { }
type Rows = Record<string, { [lang: string]: { original: string, value: string } }>;
export interface GridContextType { export interface GridContextType {
rows: Record<string, { [lang: string]: { original: string, value: string } }>; readonly rows: Accessor<Rows>;
selection: Accessor<object[]>; readonly selection: Accessor<object[]>;
mutate(prop: string, lang: string, value: string): void; mutate(prop: string, lang: string, value: string): void;
} }
export interface GridApi {
readonly rows: Accessor<Rows>;
selectAll(): void;
clear(): void;
}
const GridContext = createContext<GridContextType>(); const GridContext = createContext<GridContextType>();
const isLeaf = (entry: Entry | Leaf): entry is Leaf => Object.values(entry).some(v => typeof v === 'string'); const isLeaf = (entry: Entry | Leaf): entry is Leaf => Object.values(entry).some(v => typeof v === 'string');
const useGrid = () => useContext(GridContext)!; const useGrid = () => useContext(GridContext)!;
const GridProvider: ParentComponent<{ rows: Map<string, { [lang: string]: { value: string, handle: FileSystemFileHandle } }>, context?: (ctx: GridContextType) => any }> = (props) => { const GridProvider: ParentComponent<{ rows: Map<string, { [lang: string]: { value: string, handle: FileSystemFileHandle } }> }> = (props) => {
const [selection, setSelection] = createSignal<object[]>([]); const [selection, setSelection] = createSignal<object[]>([]);
const [state, setState] = createStore<{ rows: GridContextType['rows'], numberOfRows: number }>({ const [state, setState] = createStore<{ rows: Rows, numberOfRows: number }>({
rows: {}, rows: {},
numberOfRows: 0, numberOfRows: 0,
}); });
@ -46,13 +54,12 @@ const GridProvider: ParentComponent<{ rows: Map<string, { [lang: string]: { valu
setState('rows', Object.fromEntries(rows)); setState('rows', Object.fromEntries(rows));
}); });
createEffect(() => { createEffect(() => {
setState('numberOfRows', Object.keys(state.rows).length); setState('numberOfRows', Object.keys(state.rows).length);
}); });
const ctx: GridContextType = { const ctx: GridContextType = {
rows: state.rows, rows: createMemo(() => state.rows),
selection, selection,
mutate(prop: string, lang: string, value: string) { mutate(prop: string, lang: string, value: string) {
@ -62,16 +69,8 @@ const GridProvider: ParentComponent<{ rows: Map<string, { [lang: string]: { valu
}, },
}; };
createEffect(() => {
props.context?.(ctx);
});
const mutated = createMemo(() => Object.values(state.rows).filter(entry => Object.values(entry).some(lang => lang.original !== lang.value))); const mutated = createMemo(() => Object.values(state.rows).filter(entry => Object.values(entry).some(lang => lang.original !== lang.value)));
createEffect(() => {
console.log('tap', mutated());
});
return <GridContext.Provider value={ctx}> return <GridContext.Provider value={ctx}>
<SelectionProvider selection={setSelection} multiSelect> <SelectionProvider selection={setSelection} multiSelect>
{props.children} {props.children}
@ -79,7 +78,7 @@ const GridProvider: ParentComponent<{ rows: Map<string, { [lang: string]: { valu
</GridContext.Provider>; </GridContext.Provider>;
}; };
export const Grid: Component<{ class?: string, columns: string[], rows: Map<string, { [lang: string]: { value: string, handle: FileSystemFileHandle } }>, context?: (ctx: GridContextType) => any }> = (props) => { export const Grid: Component<{ class?: string, columns: string[], rows: Map<string, { [lang: string]: { value: string, handle: FileSystemFileHandle } }>, api?: (api: GridApi) => any }> = (props) => {
const columnCount = createMemo(() => props.columns.length - 1); const columnCount = createMemo(() => props.columns.length - 1);
const root = createMemo<Entry>(() => { const root = createMemo<Entry>(() => {
return props.rows return props.rows
@ -107,7 +106,9 @@ export const Grid: Component<{ class?: string, columns: string[], rows: Map<stri
}); });
return <section class={`${css.table} ${props.class}`} style={{ '--columns': columnCount() }}> return <section class={`${css.table} ${props.class}`} style={{ '--columns': columnCount() }}>
<GridProvider rows={props.rows} context={props.context}> <GridProvider rows={props.rows}>
<Api api={props.api} />
<Head headers={props.columns} /> <Head headers={props.columns} />
<main class={css.main}> <main class={css.main}>
@ -117,6 +118,27 @@ export const Grid: Component<{ class?: string, columns: string[], rows: Map<stri
</section> </section>
}; };
const Api: Component<{ api: undefined | ((api: GridApi) => any) }> = (props) => {
const gridContext = useGrid();
const selectionContext = useSelection();
const api: GridApi = {
rows: gridContext.rows,
selectAll() {
selectionContext.selectAll();
},
clear() {
selectionContext.clear();
},
};
createEffect(() => {
props.api?.(api);
});
return null;
};
const Head: Component<{ headers: string[] }> = (props) => { const Head: Component<{ headers: string[] }> = (props) => {
const context = useSelection(); const context = useSelection();

View file

@ -0,0 +1,58 @@
.item {
padding: .5em 1em;
background-color: inherit;
color: var(--text-1);
border: none;
cursor: pointer;
text-align: start;
&:hover {
background-color: var(--surface-2);
}
}
.child {
position: fixed;
inset-inline-start: anchor(self-start);
inset-block-start: anchor(end);
grid-template-columns: auto auto;
place-content: start;
gap: .5em;
padding: .5em 0;
inline-size: max-content;
background-color: var(--surface-2);
border: 1px solid var(--surface-3);
border-block-start-width: 0;
margin: unset;
&:popover-open {
display: grid;
}
& > .item {
grid-column: span 2;
display: grid;
grid-template-columns: subgrid;
align-items: center;
background-color: var(--surface-2);
&:hover {
background-color: var(--surface-3);
}
& > sub {
color: var(--text-2);
text-align: end;
}
}
}
:popover-open + .item {
background-color: var(--surface-2);
}

View file

@ -1,7 +1,8 @@
import { Accessor, Component, For, JSX, ParentComponent, Setter, Show, children, createContext, createEffect, createMemo, createSignal, createUniqueId, mergeProps, onCleanup, onMount, splitProps, useContext } from "solid-js"; import { Accessor, Component, For, JSX, Match, ParentComponent, Setter, Show, Switch, children, createContext, createEffect, createMemo, createSignal, createUniqueId, mergeProps, onCleanup, onMount, splitProps, useContext } from "solid-js";
import { Portal, isServer } from "solid-js/web"; import { Portal } from "solid-js/web";
import { createStore } from "solid-js/store"; import { createStore } from "solid-js/store";
import { Command, Modifier } from "../command"; import { CommandType, Command } from "../command";
import css from "./index.module.css";
export interface MenuContextType { export interface MenuContextType {
ref: Accessor<JSX.Element | undefined>; ref: Accessor<JSX.Element | undefined>;
@ -9,13 +10,13 @@ export interface MenuContextType {
addItems(items: (Item | ItemWithChildren)[]): void; addItems(items: (Item | ItemWithChildren)[]): void;
items: Accessor<(Item | ItemWithChildren)[]>; items: Accessor<(Item | ItemWithChildren)[]>;
commands(): Command[]; commands(): CommandType[];
}; };
export interface Item { export interface Item {
id: string; id: string;
label: string; label: string;
command: Command; command: CommandType;
} }
export interface ItemWithChildren { export interface ItemWithChildren {
@ -55,7 +56,7 @@ const useMenu = () => {
return context; return context;
} }
type ItemProps = { label: string, children: JSX.Element } | { label: string, command: Command }; type ItemProps = { label: string, children: JSX.Element } | { command: CommandType };
const Item: Component<ItemProps> = (props) => { const Item: Component<ItemProps> = (props) => {
const id = createUniqueId(); const id = createUniqueId();
@ -77,7 +78,7 @@ const Item: Component<ItemProps> = (props) => {
const Root: ParentComponent<{}> = (props) => { const Root: ParentComponent<{}> = (props) => {
const menu = useMenu(); const menu = useMenu();
const [current, setCurrent] = createSignal<HTMLElement>(); const [current, setCurrent] = createSignal<HTMLElement>();
const items = children(() => props.children).toArray() as unknown as (Item & ItemWithChildren)[]; const items = children(() => props.children).toArray() as unknown as (Item | ItemWithChildren)[];
menu.addItems(items) menu.addItems(items)
@ -91,7 +92,7 @@ const Root: ParentComponent<{}> = (props) => {
} }
}; };
const onExecute = (command?: Command) => { const onExecute = (command?: CommandType) => {
return command return command
? async () => { ? async () => {
await command?.(); await command?.();
@ -101,31 +102,20 @@ const Root: ParentComponent<{}> = (props) => {
: () => { } : () => { }
}; };
const Button: Component<{ label: string, command?: Command } & { [key: string]: any }> = (props) => { const Child: Component<{ command: CommandType }> = (props) => {
const [local, rest] = splitProps(props, ['label', 'command']); return <button class={css.item} type="button" onpointerdown={onExecute(props.command)}>
return <button class="menu-item" type="button" on:pointerdown={onExecute(local.command)} {...rest}> <Command command={props.command} />
{local.label} </button>
<Show when={local.command?.shortcut}>{
shortcut => {
const shift = shortcut().modifier & Modifier.Shift ? 'Shft+' : '';
const ctrl = shortcut().modifier & Modifier.Control ? 'Ctrl+' : '';
const meta = shortcut().modifier & Modifier.Meta ? 'Meta+' : '';
const alt = shortcut().modifier & Modifier.Alt ? 'Alt+' : '';
return <sub>{ctrl}{shift}{meta}{alt}{shortcut().key}</sub>;
}
}</Show>
</button>;
}; };
return <Portal mount={menu.ref()}> return <Portal mount={menu.ref()}>
<For each={items}>{ <For each={items}>{
item => <> item => <Show when={Object.hasOwn(item, 'children') ? item as ItemWithChildren : undefined} fallback={<Child command={item.command} />}>{
<Show when={item.children}>{ item => <>
children => <div <div
class="menu-child" class={css.child}
id={`child-${item.id}`} id={`child-${item().id}`}
style={`position-anchor: --menu-${item.id};`} style={`position-anchor: --menu-${item().id};`}
popover popover
on:toggle={(e: ToggleEvent) => { on:toggle={(e: ToggleEvent) => {
if (e.newState === 'open' && e.target !== null) { if (e.newState === 'open' && e.target !== null) {
@ -133,17 +123,21 @@ const Root: ParentComponent<{}> = (props) => {
} }
}} }}
> >
<For each={children()}> <For each={item().children}>
{(child) => <Button label={child.label} command={child.command} />} {(child) => <Child command={child.command} />}
</For> </For>
</div> </div>
}</Show>
<Button <button
label={item.label} class={css.item}
{...(item.children ? { popovertarget: `child-${item.id}`, style: `anchor-name: --menu-${item.id};` } : { command: item.command })} type="button"
/> popovertarget={`child-${item().id}`}
</> style={`anchor-name: --menu-${item().id};`}
>
{item().label}
</button>
</>
}</Show>
}</For> }</For>
</Portal> </Portal>
}; };

View file

@ -231,8 +231,6 @@ export const selectable = (element: HTMLElement, options: Accessor<{ value: obje
}); });
const onPointerDown = (e: PointerEvent) => { const onPointerDown = (e: PointerEvent) => {
e.preventDefault();
const [latest, setLatest] = internal.latest const [latest, setLatest] = internal.latest
const [modifier] = internal.modifier const [modifier] = internal.modifier

View file

@ -2,8 +2,8 @@ import { Menu } from "~/features/menu";
import { Sidebar } from "~/components/sidebar"; import { Sidebar } from "~/components/sidebar";
import { Component, createEffect, createMemo, createResource, createSignal, For, onMount, ParentProps, Show } from "solid-js"; import { Component, createEffect, createMemo, createResource, createSignal, For, onMount, ParentProps, Show } from "solid-js";
import { Grid, load, useFiles } from "~/features/file"; import { Grid, load, useFiles } from "~/features/file";
import { createCommand, Modifier, noop } from "~/features/command"; import { Command, Context, createCommand, Modifier, noop } from "~/features/command";
import { GridContextType } from "~/features/file/grid"; import { GridApi, GridContextType } from "~/features/file/grid";
import css from "./edit.module.css"; import css from "./edit.module.css";
import { emptyFolder, FolderEntry, walk as fileTreeWalk, Tree } from "~/components/filetree"; import { emptyFolder, FolderEntry, walk as fileTreeWalk, Tree } from "~/components/filetree";
@ -33,9 +33,9 @@ export default function Edit(props: ParentProps) {
const filesContext = useFiles(); const filesContext = useFiles();
const [root, { mutate, refetch }] = createResource(() => filesContext?.get('root')); const [root, { mutate, refetch }] = createResource(() => filesContext?.get('root'));
const [tree, setFiles] = createSignal<FolderEntry>(emptyFolder); const [tree, setFiles] = createSignal<FolderEntry>(emptyFolder);
const [columns, setColumns] = createSignal(['these', 'are', 'some', 'columns']); const [columns, setColumns] = createSignal([]);
const [rows, setRows] = createSignal<Map<string, { [lang: string]: { value: string, handle: FileSystemFileHandle } }>>(new Map); const [rows, setRows] = createSignal<Map<string, { [lang: string]: { value: string, handle: FileSystemFileHandle } }>>(new Map);
const [ctx, setCtx] = createSignal<GridContextType>(); const [api, setApi] = createSignal<GridApi>();
// Since the files are stored in indexedDb we need to refetch on the client in order to populate on page load // Since the files are stored in indexedDb we need to refetch on the client in order to populate on page load
onMount(() => { onMount(() => {
@ -89,7 +89,7 @@ export default function Edit(props: ParentProps) {
console.log(fileHandle, file, text); console.log(fileHandle, file, text);
}, { key: 'o', modifier: Modifier.Control }), }, { key: 'o', modifier: Modifier.Control }),
openFolder: createCommand('open', async () => { openFolder: createCommand('open folder', async () => {
const directory = await window.showDirectoryPicker({ mode: 'readwrite' }); const directory = await window.showDirectoryPicker({ mode: 'readwrite' });
filesContext.set('root', directory); filesContext.set('root', directory);
@ -98,49 +98,64 @@ export default function Edit(props: ParentProps) {
save: createCommand('save', () => { save: createCommand('save', () => {
console.log('save', rows()); console.log('save', rows());
}, { key: 's', modifier: Modifier.Control }), }, { key: 's', modifier: Modifier.Control }),
saveAs: createCommand('saveAs', () => { saveAs: createCommand('save as', (handle?: FileSystemFileHandle) => {
console.log('save as ...'); console.log('save as ...', handle);
window.showSaveFilePicker({
startIn: root(),
excludeAcceptAllOption: true,
types: [
{ accept: { 'application/json': ['.json'] }, description: 'JSON' },
{ accept: { 'application/yaml': ['.yml', '.yaml'] }, description: 'YAML' },
{ accept: { 'application/csv': ['.csv'] }, description: 'CSV' },
]
});
}, { key: 's', modifier: Modifier.Control | Modifier.Shift }), }, { key: 's', modifier: Modifier.Control | Modifier.Shift }),
edit: createCommand('edit', () => { edit: createCommand('edit', () => {
}), }),
selectAll: createCommand('selectAll', () => { selectAll: createCommand('select all', () => {
console.log(ctx(), ctx()?.selection.selectAll(true)); api()?.selectAll();
}, { key: 'a', modifier: Modifier.Control }), }, { key: 'a', modifier: Modifier.Control }),
} as const; } as const;
const mutated = createMemo(() => Object.values(ctx()?.rows ?? {}).filter(row => Object.values(row).some(lang => lang.original !== lang.value))); const mutated = createMemo(() => Object.values(api()?.rows() ?? {}).filter(row => Object.values(row).some(lang => lang.original !== lang.value)));
createEffect(() => { createEffect(() => {
console.log('KAAS', mutated()); console.log('KAAS', mutated());
}); });
return <div class={css.root}> return <div class={css.root}>
<Menu.Root> <Context.Root commands={[commands.saveAs]}>
<Menu.Item label="file"> <Context.Menu>{
<Menu.Item label="open" command={commands.open} /> command => <Command command={command} />
}</Context.Menu>
<Menu.Item label="open folder" command={commands.openFolder} /> <Menu.Root>
<Menu.Item label="file">
<Menu.Item command={commands.open} />
<Menu.Item label="save" command={commands.save} /> <Menu.Item command={commands.openFolder} />
<Menu.Item label="save all" command={commands.saveAs} /> <Menu.Item command={commands.save} />
</Menu.Item> </Menu.Item>
<Menu.Item label="edit" command={commands.edit} /> <Menu.Item command={commands.edit} />
<Menu.Item label="selection"> <Menu.Item label="selection">
<Menu.Item label="select all" command={commands.selectAll} /> <Menu.Item command={commands.selectAll} />
</Menu.Item> </Menu.Item>
<Menu.Item label="view" command={noop} /> <Menu.Item label="view" command={noop} />
</Menu.Root> </Menu.Root>
<Sidebar as="aside" class={css.sidebar}> <Sidebar as="aside" class={css.sidebar}>
<Tree entries={tree().entries}>{ <Tree entries={tree().entries}>{
file => file().name file => <Context.Handle>{file().name}</Context.Handle>
}</Tree> }</Tree>
</Sidebar> </Sidebar>
<Grid columns={columns()} rows={rows()} context={setCtx} /> <Grid columns={columns()} rows={rows()} api={setApi} />
</Context.Root>
</div> </div>
} }