made a start on data grid implementation

This commit is contained in:
Chris Kruining 2024-10-03 15:33:25 +02:00
parent a543259fe4
commit 70c15c4094
12 changed files with 1083 additions and 210 deletions

View file

@ -30,6 +30,9 @@ body {
block-size: 100%;
overflow: clip;
display: grid;
grid: auto 1fr / 100%;
background-color: var(--surface-1);
margin: 0;
@ -59,114 +62,82 @@ body {
padding: .75em;
margin-block-end: -1em;
background-color: inherit;
color: inherit;
border-radius: .25em;
& > svg {
inline-size: 100%;
block-size: 100%;
}
}
& > div {
display: contents;
display: contents;
}
.menu-item {
padding: .5em 1em;
padding: .5em 1em;
background-color: inherit;
color: var(--text);
border: none;
cursor: pointer;
background-color: inherit;
color: var(--text);
border: none;
cursor: pointer;
text-align: start;
text-align: start;
&:hover {
background-color: var(--surface-2);
}
}
.menu-child {
position: fixed;
inset-inline-start: anchor(self-start);
inset-block-start: anchor(end);
grid-auto-flow: row;
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;
}
& > .menu-item {
background-color: var(--surface-2);
&:hover {
background-color: var(--surface-2);
}
}
.menu-child {
position: fixed;
inset-inline-start: anchor(self-start);
inset-block-start: anchor(end);
grid-auto-flow: row;
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;
}
& > .menu-item {
background-color: var(--surface-2);
&:hover {
background-color: var(--surface-3);
}
background-color: var(--surface-3);
}
}
}
:popover-open + .menu-item {
background-color: var(--surface-2);
}
}
& > main {
block-size: 100%;
padding: 1em;
padding-block-start: 1.5em;
overflow: clip auto;
& details {
& > summary::marker {
content: url('data:image/svg+xml;charset=UTF-8,<svg color="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 1024 1024" width="1em" height="1em" xmlns="http://www.w3.org/2000/svg"><path d="M880 298.4H521L403.7 186.2a8.15 8.15 0 0 0-5.5-2.2H144c-17.7 0-32 14.3-32 32v592c0 17.7 14.3 32 32 32h736c17.7 0 32-14.3 32-32V330.4c0-17.7-14.3-32-32-32z"></path></svg>');
}
&[open] > summary::marker {
content: url('data:image/svg+xml;charset=UTF-8,<svg color="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 1024 1024" width="1em" height="1em" xmlns="http://www.w3.org/2000/svg"><path d="M928 444H820V330.4c0-17.7-14.3-32-32-32H473L355.7 186.2a8.15 8.15 0 0 0-5.5-2.2H96c-17.7 0-32 14.3-32 32v592c0 17.7 14.3 32 32 32h698c13 0 24.8-7.9 29.7-20l134-332c1.5-3.8 2.3-7.9 2.3-12 0-17.7-14.3-32-32-32zm-180 0H238c-13 0-24.8 7.9-29.7 20L136 643.2V256h188.5l119.6 114.4H748V444z"></path></svg>');
}
& span {
cursor: pointer;
}
}
}
}
a {
margin-right: 1rem;
color: var(--primary);
}
h1 {
color: #335d92;
color: var(--primary);
text-transform: uppercase;
font-size: 4rem;
font-weight: 100;
line-height: 1.1;
margin: 4rem auto;
max-width: 14rem;
}
p {
max-width: 14rem;
margin: 2rem auto;
line-height: 1.35;
}
@media (min-width: 480px) {
h1 {
max-width: none;
}
p {
max-width: none;
}
}
}

View file

@ -3,11 +3,11 @@ import { Portal, isServer } from "solid-js/web";
import { createStore } from "solid-js/store";
export interface MenuContextType {
ref: Accessor<JSX.Element|undefined>;
setRef: Setter<JSX.Element|undefined>;
ref: Accessor<JSX.Element | undefined>;
setRef: Setter<JSX.Element | undefined>;
addItems(items: (Item|ItemWithChildren)[]): void;
items: Accessor<(Item|ItemWithChildren)[]>;
addItems(items: (Item | ItemWithChildren)[]): void;
items: Accessor<(Item | ItemWithChildren)[]>;
commands(): Command[];
};
@ -41,20 +41,20 @@ export interface ItemWithChildren {
const MenuContext = createContext<MenuContextType>();
export const createCommand = (command: () => any, shortcut?: Command['shortcut']): Command => {
if(shortcut) {
if (shortcut) {
(command as Command).shortcut = { key: shortcut.key.toLowerCase(), modifier: shortcut.modifier };
}
return command;
};
export const MenuProvider: ParentComponent = (props) => {
const [ ref, setRef ] = createSignal<JSX.Element|undefined>();
const [ _items, setItems ] = createSignal<Map<string, Item&{ children?: Map<string, Item> }>>(new Map());
const [ref, setRef] = createSignal<JSX.Element | undefined>();
const [_items, setItems] = createSignal<Map<string, Item & { children?: Map<string, Item> }>>(new Map());
const [ store, setStore ] = createStore<{ items: Record<string, Item|ItemWithChildren> }>({ items: {} });
const [store, setStore] = createStore<{ items: Record<string, Item | ItemWithChildren> }>({ items: {} });
const addItems = (items: (Item|ItemWithChildren)[]) => setStore('items', values => {
const addItems = (items: (Item | ItemWithChildren)[]) => setStore('items', values => {
for (const item of items) {
values[item.id] = item;
}
@ -67,22 +67,22 @@ export const MenuProvider: ParentComponent = (props) => {
return <MenuContext.Provider value={{ ref, setRef, addItems, items, commands }}>{props.children}</MenuContext.Provider>;
}
const useMenu = () => {
const useMenu = () => {
const context = useContext(MenuContext);
if(context === undefined) {
if (context === undefined) {
throw new Error(`MenuContext is called outside of a <MenuProvider />`);
}
return context;
}
type ItemProps = { label: string, children: JSX.Element }|{ label: string, command: Command };
type ItemProps = { label: string, children: JSX.Element } | { label: string, command: Command };
const Item: Component<ItemProps> = (props) => {
const id = createUniqueId();
if(props.command) {
if (props.command) {
return mergeProps(props, { id }) as unknown as JSX.Element;
}
@ -98,8 +98,8 @@ const Item: Component<ItemProps> = (props) => {
const Root: ParentComponent<{}> = (props) => {
const menu = useMenu();
const [ current, setCurrent ] = createSignal<HTMLElement>();
const items = (isServer
const [current, setCurrent] = createSignal<HTMLElement>();
const items = (isServer
? props.children
: props.children?.map(c => c())) ?? [];
@ -108,7 +108,7 @@ const Root: ParentComponent<{}> = (props) => {
const close = () => {
const el = current();
if(el) {
if (el) {
el.hidePopover();
setCurrent(undefined);
@ -123,55 +123,51 @@ const Root: ParentComponent<{}> = (props) => {
}
};
const Button: Component<{ label: string, command: Command }|{ [key: string]: any }> = (props) => {
const [ local, rest ] = splitProps(props, ['label', 'command']);
const Button: Component<{ label: string, command: Command } | { [key: string]: any }> = (props) => {
const [local, rest] = splitProps(props, ['label', 'command']);
return <button class="menu-item" type="button" on:pointerdown={onExecute(local.command)} {...rest}>{local.label}</button>;
};
return <Portal mount={menu.ref()}>
<For each={items}>{
item => {
const [] = createSignal();
return <>
<Show when={item.children}>
<div
class="menu-child"
id={`child-${item.id}`}
style={`position-anchor: --menu-${item.id};`}
popover
on:toggle={(e: ToggleEvent) => {
if(e.newState === 'open' && e.target !== null) {
return setCurrent(e.target as HTMLElement);
}
}}
>
<For each={item.children}>
{(child) => <Button label={child.label} command={child.command} />}
</For>
</div>
</Show>
<Button
label={item.label}
on:pointerenter={(e) => {
if(!item.children) {
return;
item => <>
<Show when={item.children}>
<div
class="menu-child"
id={`child-${item.id}`}
style={`position-anchor: --menu-${item.id};`}
popover
on:toggle={(e: ToggleEvent) => {
if (e.newState === 'open' && e.target !== null) {
return setCurrent(e.target as HTMLElement);
}
const el = current();
if(!el){
return;
}
el.hidePopover();
}}
{...(item.children ? { popovertarget: `child-${item.id}`, style: `anchor-name: --menu-${item.id};`, command: item.command } : {})}
/>
</>;
}
>
<For each={item.children}>
{(child) => <Button label={child.label} command={child.command} />}
</For>
</div>
</Show>
<Button
label={item.label}
on:pointerenter={(e) => {
if (!item.children) {
return;
}
const el = current();
if (!el) {
return;
}
el.hidePopover();
}}
{...(item.children ? { popovertarget: `child-${item.id}`, style: `anchor-name: --menu-${item.id};` } : { command: item.command })}
/>
</>
}</For>
</Portal>
};
@ -179,7 +175,7 @@ const Root: ParentComponent<{}> = (props) => {
declare module "solid-js" {
namespace JSX {
interface HTMLAttributes<T> {
anchor?: string|undefined;
anchor?: string | undefined;
}
interface Directives {
@ -190,20 +186,20 @@ declare module "solid-js" {
export const asMenuRoot = (element: Element) => {
const menu = useMenu();
const c = 'menu-root';
const listener = (e: KeyboardEvent) => {
const key = e.key.toLowerCase();
const modifiers =
const modifiers =
(e.shiftKey ? 1 : 0) << 0 |
(e.ctrlKey ? 1 : 0) << 1 |
(e.metaKey ? 1 : 0) << 2 |
(e.altKey ? 1 : 0) << 3 ;
(e.altKey ? 1 : 0) << 3;
const commands = menu.commands();
const command = commands.find(c => c.shortcut?.key === key && (c.shortcut.modifier === undefined || c.shortcut.modifier === modifiers));
if(command === undefined) {
if (command === undefined) {
return;
}

7
src/global.d.ts vendored
View file

@ -1 +1,8 @@
/// <reference types="@solidjs/start/env" />
interface IterableIterator<T> {
map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): IterableIterator<U>;
filter<S extends T>(predicate: (value: T, index: number, array: T[]) => value is S, thisArg?: any): IterableIterator<S>;
toArray(): T[];
}

View file

@ -3,24 +3,26 @@ import { Show } from "solid-js";
import { BsTranslate } from "solid-icons/bs";
import { FilesProvider } from "~/features/file";
import { MenuProvider, asMenuRoot } from "~/features/menu";
import { isServer } from "solid-js/web";
import { A } from "@solidjs/router";
asMenuRoot // prevents removal of import
export default function Editor(props) {
const supported = typeof window.showDirectoryPicker === 'function';
const supported = isServer || typeof window.showDirectoryPicker === 'function';
return <MenuProvider>
<Title>Translation-Tool</Title>
<nav use:asMenuRoot>
<BsTranslate class="logo" />
<A class="logo" href="/"><BsTranslate /></A>
</nav>
<main>
<Show when={supported} fallback={<span>too bad, so sad. Your browser does not support the File Access API</span>}>
<FilesProvider>
{props.children}
</FilesProvider>
<main style="padding: 1em; block-size: 100%; overflow: clip;">
<Show when={supported} fallback={<span>too bad, so sad. Your browser does not support the File Access API</span>}>
<FilesProvider>
{props.children}
</FilesProvider>
</Show>
</main>
</MenuProvider>

View file

@ -0,0 +1,27 @@
.table {
display: grid;
overflow: auto;
grid-template-columns: 1em max-content repeat(var(--columns), auto);
gap: .5em;
block-size: 100%;
overflow: clip auto;
& > :is(header, main, footer) {
display: contents;
}
& details {
display: contents;
&::details-content {
grid-column: span calc(2 + var(--columns));
display: grid;
grid-template-columns: subgrid;
}
& > summary {
grid-column: 2 / span calc(1 + var(--columns));
}
}
}

View file

@ -0,0 +1,202 @@
import { createCommand, Menu, Modifier } from "~/features/menu";
import { Component, createEffect, createMemo, createResource, createSignal, For, onMount, Show } from "solid-js";
import { useFiles } from "~/features/file";
import "./edit.css";
interface Entry extends Record<string, Entry | string> { }
interface Leaf extends Record<string, string> { }
interface Entry2 extends Record<string, Entry2 | Leaf> { }
async function* walk(directory: FileSystemDirectoryHandle, path: string[] = []): AsyncGenerator<{ lang: string, entries: Entry }, void, never> {
for await (const handle of directory.values()) {
if (handle.kind === 'directory') {
yield* walk(handle, [...path, handle.name]);
continue;
}
if (!handle.name.endsWith('.json')) {
continue;
}
const file = await handle.getFile();
if (file.type !== 'application/json') {
continue;
}
const lang = file.name.split('.').at(0)!;
const text = await file.text();
const root: Entry = {};
let current: Entry = root;
for (const key of path) {
current[key] = {};
current = current[key];
}
Object.assign(current, JSON.parse(text));
yield { lang, entries: root };
}
};
export default function Edit(props) {
const files = useFiles();
const [root, { mutate, refetch }] = createResource(() => files.get('root'));
// Since the files are stored in indexedDb we need to refetch on the client in order to populate on page load
onMount(() => {
refetch();
});
createEffect(async () => {
const directory = root();
if (root.state === 'ready' && directory?.kind === 'directory') {
const contents = await Array.fromAsync(walk(directory));
const entries = Object.entries(
Object.groupBy(contents, e => e.lang)
).map(([lang, entries]) => ({
lang,
entries: entries!
.map(e => e.entries)
.reduce((o, e) => {
Object.assign(o, e);
return o;
}, {})
}));
const assign = (lang: string, entries: Entry) => {
return Object.entries(entries).reduce((aggregate, [key, value]) => {
const v = typeof value === 'string' ? { [lang]: value } : assign(lang, value);
Object.assign(aggregate, { [key]: v });
return aggregate;
}, {});
}
const unified = contents.reduce((aggregate, { lang, entries }) => {
Object.assign(aggregate, assign(lang, entries));
return aggregate;
}, {});
setColumns(['key', ...new Set(contents.map(c => c.lang))]);
setRows(unified);
}
});
const commands = {
open: createCommand(async () => {
const [fileHandle] = await window.showOpenFilePicker({
types: [
{
description: "JSON File(s)",
accept: {
"application/json": [".json", ".jsonp", ".jsonc"],
},
}
],
excludeAcceptAllOption: true,
multiple: true,
});
const file = await fileHandle.getFile();
const text = await file.text();
console.log(fileHandle, file, text);
}, { key: 'o', modifier: Modifier.Control }),
openFolder: createCommand(async () => {
const directory = await window.showDirectoryPicker({ mode: 'readwrite' });
files.set('root', directory);
mutate(directory);
}),
save: createCommand(() => {
console.log('save');
}, { key: 's', modifier: Modifier.Control }),
saveAll: createCommand(() => {
console.log('save all');
}, { key: 's', modifier: Modifier.Control | Modifier.Shift }),
edit: createCommand(() => {
}),
selection: createCommand(() => { }),
view: createCommand(() => { }),
} as const;
const [columns, setColumns] = createSignal([]);
const [rows, setRows] = createSignal<Entry2>({});
const Row: Component<{ entry: Entry2 }> = (props) => {
return <For each={Object.entries(props.entry)}>{
([key, value]) => {
const values = Object.values(value);
const isLeaf = values.some(v => typeof v === 'string');
return <Show when={isLeaf} fallback={<Group key={key} entry={value as Entry2} />}>
<input type="checkbox" />
<span>{key}</span>
<For each={values}>{
value => <input type="" value={value} />
}</For>
</Show>;
}
}</For>
};
const Group: Component<{ key: string, entry: Entry2 }> = (props) => {
return <details open>
<summary>{props.key}</summary>
<Row entry={props.entry} />
</details>;
};
const columnCount = createMemo(() => columns().length - 1);
return <>
<Menu.Root>
<Menu.Item label="file">
<Menu.Item label="open" command={commands.open} />
<Menu.Item label="open folder" command={commands.openFolder} />
<Menu.Item label="save" command={commands.save} />
<Menu.Item label="save all" command={commands.saveAll} />
</Menu.Item>
<Menu.Item label="edit" command={commands.edit} />
<Menu.Item label="selection" command={commands.selection} />
<Menu.Item label="view" command={commands.view} />
</Menu.Root>
<section class="table" style={{ '--columns': columnCount() }}>
<header>
<input type="checkbox" />
<For each={columns()}>{
column => <span>{column}</span>
}</For>
</header>
<main>
<Row entry={rows()} />
</main>
</section>
{/* <AgGridSolid
singleClickEdit
columnDefs={columnDefs()}
rowData={rowData()}
defaultColDef={defaultColDef} /> */}
</>
}

View file

@ -0,0 +1,45 @@
section.index {
display: grid;
grid: 100% / auto 1fr;
inline-size: 100%;
block-size: 100%;
& > aside {
overflow: clip auto;
resize: horizontal;
min-inline-size: 300px;
max-inline-size: 75vw;
block-size: 100%;
padding: 1em;
padding-block-start: 1.5em;
padding-inline-end: 1em;
& details {
& > summary::marker {
content: none;
color: var(--text) !important;
}
& span {
cursor: pointer;
}
}
& ul {
padding-inline-start: 0;
& ul {
padding-inline-start: 1.25em;
}
& span {
white-space: nowrap;
}
}
}
& > section {
padding-inline: 1em;
}
}

View file

@ -0,0 +1,174 @@
import { Component, createEffect, createMemo, createResource, createSignal, For, onMount, Show } from "solid-js";
import { useFiles } from "~/features/file";
import { createCommand, Menu, Modifier } from "~/features/menu";
import { AiFillFile, AiFillFolder, AiFillFolderOpen } from "solid-icons/ai";
import "./experimental.css";
interface FileEntry {
name: string;
kind: 'file';
meta: File;
}
interface FolderEntry {
name: string;
kind: 'folder';
entries: Entry[];
}
type Entry = FileEntry | FolderEntry;
async function* walk(directory: FileSystemDirectoryHandle, filters: RegExp[] = [], depth = 0): AsyncGenerator<Entry, void, never> {
if (depth === 10) {
return;
}
for await (const handle of directory.values()) {
if (filters.some(f => f.test(handle.name))) {
continue;
}
if (handle.kind === 'file') {
yield { name: handle.name, kind: 'file', meta: await handle.getFile() };
}
else {
yield { name: handle.name, kind: 'folder', entries: await Array.fromAsync(walk(handle, filters, depth + 1)) };
}
}
}
export default function Index() {
const files = useFiles();
const [tree, setTree] = createSignal<FolderEntry>();
const [content, setContent] = createSignal<string>('');
const [showHiddenFiles, setShowHiddenFiles] = createSignal<boolean>(false);
const filters = createMemo<RegExp[]>(() => showHiddenFiles() ? [/^node_modules$/] : [/^node_modules$/, /^\..+$/]);
const [root, { mutate, refetch }] = createResource(() => files.get('root'));
// Since the files are stored in indexedDb we need to refetch on the client in order to populate on page load
onMount(() => {
refetch();
});
createEffect(async () => {
const directory = root();
if (root.state === 'ready' && directory?.kind === 'directory') {
const entries = await Array.fromAsync(walk(directory, filters()));
setTree({ name: '', kind: 'folder', entries });
}
});
const open = async (file: File) => {
const text = await file.text();
console.log({ file, text });
return setContent(text);
};
const commands = {
open: createCommand(async () => {
const [fileHandle] = await window.showOpenFilePicker({
types: [
{
description: "JSON File(s)",
accept: {
"application/json": [".json", ".jsonp", ".jsonc"],
},
}
],
excludeAcceptAllOption: true,
multiple: true,
});
const file = await fileHandle.getFile();
const text = await file.text();
console.log(fileHandle, file, text);
}, { key: 'o', modifier: Modifier.Control }),
openFolder: createCommand(async () => {
const directory = await window.showDirectoryPicker({ mode: 'readwrite' });
const entries = await Array.fromAsync(walk(directory, filters()));
files.set('root', directory);
mutate(directory);
setTree({ name: '', kind: 'folder', entries });
}),
save: createCommand(() => {
console.log('save');
}, { key: 's', modifier: Modifier.Control }),
saveAll: createCommand(() => {
console.log('save all');
}, { key: 's', modifier: Modifier.Control | Modifier.Shift }),
edit: createCommand(() => { }),
selection: createCommand(() => { }),
view: createCommand(() => { }),
} as const;
const Tree: Component<{ entries: Entry[] }> = (props) => {
return <ul style="display: flex; flex-direction: column; list-style: none;">
<For each={props.entries}>{
(entry, index) => <li style={`order: ${(entry.kind === 'file' ? 200 : 100) + index()}`}>
<Show when={entry.kind === 'folder' ? entry : undefined}>{
folder => <Folder folder={folder()} />
}</Show>
<Show when={entry.kind === 'file' ? entry : undefined}>{
file => <span on:pointerdown={() => {
console.log(`lets open '${file().name}'`);
open(file().meta);
}}><AiFillFile /> {file().name}</span>
}</Show>
</li>
}</For>
</ul>
}
const Folder: Component<{ folder: FolderEntry }> = (props) => {
const [open, setOpen] = createSignal(false);
return <details open={open()} on:toggle={() => setOpen(o => !o)}>
<summary><Show when={open()} fallback={<AiFillFolder />}><AiFillFolderOpen /></Show> {props.folder.name}</summary>
<Tree entries={props.folder.entries} />
</details>;
};
return (
<>
<Menu.Root>
<Menu.Item label="file">
<Menu.Item label="open" command={commands.open} />
<Menu.Item label="open folder" command={commands.openFolder} />
<Menu.Item label="save" command={commands.save} />
<Menu.Item label="save all" command={commands.saveAll} />
</Menu.Item>
<Menu.Item label="edit" command={commands.edit} />
<Menu.Item label="selection" command={commands.selection} />
<Menu.Item label="view" command={commands.view} />
</Menu.Root>
<section class="index">
<aside>
<label><input type="checkbox" on:input={() => setShowHiddenFiles(v => !v)} />Show hidden files</label>
<Show when={tree()}>{
tree => <Tree entries={tree().entries} />
}</Show>
</aside>
<section>
<pre>{content()}</pre>
</section>
</section>
</>
);
}

View file

@ -1,8 +1,4 @@
section.index {
body > main {
display: grid;
grid: 100% / 20% 1fr;
& > aside {
overflow: clip auto;
}
place-content: center;
}

View file

@ -1,8 +1,9 @@
import { Component, createEffect, createMemo, createResource, createSignal, For, onMount, Show } from "solid-js";
import { useFiles } from "~/features/file";
import { createCommand, Menu, Modifier } from "~/features/menu";
import { AiFillFile } from "solid-icons/ai";
import { AiFillFile, AiFillFolder, AiFillFolderOpen } from "solid-icons/ai";
import "./index.css";
import { A } from "@solidjs/router";
interface FileEntry {
name: string;
@ -16,20 +17,20 @@ interface FolderEntry {
entries: Entry[];
}
type Entry = FileEntry|FolderEntry;
type Entry = FileEntry | FolderEntry;
async function* walk(directory: FileSystemDirectoryHandle, filters: RegExp[] = [], depth = 0): AsyncGenerator<Entry, void, never> {
if(depth === 5) {
if (depth === 10) {
return;
}
for await (const handle of directory.values()) {
if(filters.some(f => f.test(handle.name))){
if (filters.some(f => f.test(handle.name))) {
continue;
}
if(handle.kind === 'file') {
if (handle.kind === 'file') {
yield { name: handle.name, kind: 'file', meta: await handle.getFile() };
}
else {
@ -40,11 +41,11 @@ async function* walk(directory: FileSystemDirectoryHandle, filters: RegExp[] = [
export default function Index() {
const files = useFiles();
const [ tree, setTree ] = createSignal<FolderEntry>();
const [ content, setContent ] = createSignal<string>('');
const [ showHiddenFiles, setShowHiddenFiles ] = createSignal<boolean>(false);
const filters = createMemo<RegExp[]>(() => showHiddenFiles() ? [/^node_modules$/] : [ /^node_modules$/, /^\..+$/ ]);
const [ root, { mutate, refetch } ] = createResource(() => files.get('root'));
const [tree, setTree] = createSignal<FolderEntry>();
const [content, setContent] = createSignal<string>('');
const [showHiddenFiles, setShowHiddenFiles] = createSignal<boolean>(false);
const filters = createMemo<RegExp[]>(() => showHiddenFiles() ? [/^node_modules$/] : [/^node_modules$/, /^\..+$/]);
const [root, { mutate, refetch }] = createResource(() => files.get('root'));
// Since the files are stored in indexedDb we need to refetch on the client in order to populate on page load
onMount(() => {
@ -54,7 +55,7 @@ export default function Index() {
createEffect(async () => {
const directory = root();
if(root.state ==='ready' && directory?.kind === 'directory'){
if (root.state === 'ready' && directory?.kind === 'directory') {
const entries = await Array.fromAsync(walk(directory, filters()));
setTree({ name: '', kind: 'folder', entries });
@ -76,7 +77,7 @@ export default function Index() {
{
description: "JSON File(s)",
accept: {
"application/json": [ ".json", ".jsonp", ".jsonc" ],
"application/json": [".json", ".jsonp", ".jsonc"],
},
}
],
@ -87,7 +88,7 @@ export default function Index() {
const text = await file.text();
console.log(fileHandle, file, text);
}, { key: 'o', modifier: Modifier.Control}),
}, { key: 'o', modifier: Modifier.Control }),
openFolder: createCommand(async () => {
const directory = await window.showDirectoryPicker({ mode: 'readwrite' });
const entries = await Array.fromAsync(walk(directory, filters()));
@ -102,10 +103,10 @@ export default function Index() {
}, { key: 's', modifier: Modifier.Control }),
saveAll: createCommand(() => {
console.log('save all');
}, { key: 's', modifier: Modifier.Control|Modifier.Shift }),
edit: createCommand(() => {}),
selection: createCommand(() => {}),
view: createCommand(() => {}),
}, { key: 's', modifier: Modifier.Control | Modifier.Shift }),
edit: createCommand(() => { }),
selection: createCommand(() => { }),
view: createCommand(() => { }),
} as const;
const Tree: Component<{ entries: Entry[] }> = (props) => {
@ -115,58 +116,36 @@ export default function Index() {
<Show when={entry.kind === 'folder' ? entry : undefined}>{
folder => <Folder folder={folder()} />
}</Show>
<Show when={entry.kind === 'file' ? entry : undefined}>{
file => <span on:pointerdown={() => {
console.log(`lets open '${file().name}'`);
open(file().meta);
}}><AiFillFile />{file().name}</span>
}}><AiFillFile /> {file().name}</span>
}</Show>
</li>
}</For>
</ul>
}
const Folder: Component<{ folder: FolderEntry, open?: true }> = (props) => {
return <details open={props.open ?? false}>
<summary>{props.folder.name}</summary>
const Folder: Component<{ folder: FolderEntry }> = (props) => {
const [open, setOpen] = createSignal(false);
return <details open={open()} on:toggle={() => setOpen(o => !o)}>
<summary><Show when={open()} fallback={<AiFillFolder />}><AiFillFolderOpen /></Show> {props.folder.name}</summary>
<Tree entries={props.folder.entries} />
</details>;
};
return (
<>
<Menu.Root>
<Menu.Item label="file">
<Menu.Item label="open" command={commands.open} />
<h1>Hi, welcome!</h1>
<b>Lets get started</b>
<Menu.Item label="open folder" command={commands.openFolder} />
<Menu.Item label="save" command={commands.save} />
<Menu.Item label="save all" command={commands.saveAll} />
</Menu.Item>
<Menu.Item label="edit" command={commands.edit} />
<Menu.Item label="selection" command={commands.selection} />
<Menu.Item label="view" command={commands.view} />
</Menu.Root>
<section class="index">
<aside>
<label><input type="checkbox" on:input={() => setShowHiddenFiles(v => !v)} />Show hidden files</label>
<Show when={tree()}>{
tree => <Tree entries={tree().entries} />
}</Show>
</aside>
<section>
<pre>{content()}</pre>
</section>
</section>
<ul>
<li><A href="/edit">Start editing</A></li>
</ul>
</>
);
}