Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

web: add a simple command palette #7314

Draft
wants to merge 10 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions apps/web/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
"event-source-polyfill": "1.0.31",
"fflate": "^0.8.0",
"file-saver": "^2.0.5",
"fuzzyjs": "^5.0.1",
"hash-wasm": "4.12.0",
"hotkeys-js": "^3.8.3",
"katex": "0.16.11",
Expand Down
6 changes: 6 additions & 0 deletions apps/web/src/app.css
Original file line number Diff line number Diff line change
Expand Up @@ -249,3 +249,9 @@ textarea,
background-color: color-mix(in srgb, var(--accent) 5%, transparent);
}
}

kbd {
background: var(--background);
border-radius: 3px;
color: var(--paragraph-secondary);
}
12 changes: 11 additions & 1 deletion apps/web/src/common/key-map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { GlobalKeyboard } from "../utils/keyboard";
import { useEditorStore } from "../stores/editor-store";
import { useStore as useSearchStore } from "../stores/search-store";
import { useEditorManager } from "../components/editor/manager";
import { CommandPaletteDialog } from "../dialogs/command-palette";

const KEYMAP = [
// {
Expand Down Expand Up @@ -77,7 +78,7 @@ const KEYMAP = [

useSearchStore.setState({ isSearching: true, searchType: "notes" });
}
}
},
// {
// keys: ["alt+n"],
// description: "Go to Notes",
Expand Down Expand Up @@ -141,6 +142,15 @@ const KEYMAP = [
// themestore.get().toggleNightMode();
// },
// },
{
keys: ["ctrl+k"],
description: "Open command palette",
global: false,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be true, I think.

action: (e: KeyboardEvent) => {
e.preventDefault();
CommandPaletteDialog.show(true);
}
}
];

export function registerKeyMap() {
Expand Down
4 changes: 3 additions & 1 deletion apps/web/src/components/icons/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,8 @@ import {
mdiOpenInNew,
mdiTagOutline,
mdiChatQuestionOutline,
mdiNoteRemoveOutline
mdiNoteRemoveOutline,
mdiRadar
} from "@mdi/js";
import { useTheme } from "@emotion/react";
import { Theme } from "@notesnook/theme";
Expand Down Expand Up @@ -560,3 +561,4 @@ export const ClearCache = createIcon(mdiBroom);
export const OpenInNew = createIcon(mdiOpenInNew);
export const Coupon = createIcon(mdiTagOutline);
export const Support = createIcon(mdiChatQuestionOutline);
export const Radar = createIcon(mdiRadar);
277 changes: 277 additions & 0 deletions apps/web/src/dialogs/command-palette/command-palette-dialog.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,277 @@
/*
This file is part of the Notesnook project (https://notesnook.com/)

Copyright (C) 2023 Streetwriters (Private) Limited

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

import { ScrollContainer } from "@notesnook/ui";
import { Button, Flex, Text } from "@theme-ui/components";
import { Fragment, useEffect, useRef } from "react";
import { BaseDialogProps, DialogManager } from "../../common/dialog-manager";
import Dialog from "../../components/dialog";
import Field from "../../components/field";
import {
type Command,
useCommandPaletteStore,
getCommandAction,
getCommandIcon
} from "../../stores/command-palette-store";
import { Icon } from "../../components/icons";
import { toTitleCase } from "@notesnook/common";
import { match, surround } from "fuzzyjs";

type GroupedCommands = Record<
string,
(Command & { index: number; icon: Icon | undefined })[]
>;

export const CommandPaletteDialog = DialogManager.register(
function CommandPaletteDialog(props: BaseDialogProps<boolean>) {
const {
selected,
setSelected,
query,
setQuery,
commands,
search,
setCommands,
reset
} = useCommandPaletteStore();
const selectedRef = useRef<HTMLButtonElement>(null);

useEffect(() => {
selectedRef.current?.scrollIntoView({
block: "nearest"
});
}, [selected]);

useEffect(() => {
const searchWithoutDebounce =
query.startsWith(">") || query.trim().length < 1;
if (searchWithoutDebounce) {
const res = search(query);
if (res instanceof Promise) {
} else {
setCommands(res ?? []);
}
}

const timeoutId = setTimeout(async () => {
const res = search(query);
if (res instanceof Promise) {
const commands = await res;
setCommands(commands ?? []);
return;
} else {
setCommands(res ?? []);
}
}, 500);

return () => {
clearTimeout(timeoutId);
};
}, [query]);
Comment on lines +61 to +86
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't need to be in a useEffect. Just run this logic in onChange.


const grouped = commands.reduce((acc, command, index) => {
if (!acc[command.group]) {
acc[command.group] = [];
}
acc[command.group].push({
...command,
icon: getCommandIcon(command),
index
});
return acc;
}, {} as GroupedCommands);

return (
<Dialog
isOpen={true}
width={650}
onClose={() => {
reset();
props.onClose(false);
}}
noScroll
sx={{
fontFamily: "body"
}}
>
<Flex
variant="columnFill"
sx={{ mx: 3, overflow: "hidden", height: 350 }}
onKeyDown={(e) => {
if (e.key == "Enter") {
e.preventDefault();
const command = commands[selected];
if (!command) return;
const action = getCommandAction({
id: command.id,
type: command.type
});
if (action) {
action(command.id);
reset();
props.onClose(true);
}
setSelected(0);
}
if (e.key === "ArrowDown") {
e.preventDefault();
setSelected((selected + 1) % commands.length);
}
if (e.key === "ArrowUp") {
e.preventDefault();
setSelected((selected - 1 + commands.length) % commands.length);
}
}}
>
<>
<Field
autoFocus
placeholder={"Search in notes, notebooks, and tags"}
sx={{ mx: 0, my: 2 }}
value={query}
onChange={(e) => {
setSelected(0);
setQuery(e.target.value);
}}
/>
<ScrollContainer>
<Flex
sx={{
flexDirection: "column",
gap: 1,
mt: 2,
mb: 4
}}
>
{Object.entries(grouped).map(([group, commands]) => (
<Flex sx={{ flexDirection: "column", gap: 1, mx: 1 }}>
<Text variant="subBody">{toTitleCase(group)}</Text>
<Flex
sx={{
flexDirection: "column",
gap: 1
}}
>
{commands.map((command, index) => (
<Button
ref={command.index === selected ? selectedRef : null}
key={index}
onClick={() => {
const action = getCommandAction({
id: command.id,
type: command.type
});
if (action) {
action(command.id);
reset();
props.onClose(true);
}
}}
sx={{
display: "flex",
flexDirection: "row",
alignItems: "center",
gap: 2,
py: 1,
bg:
command.index === selected
? "hover"
: "transparent",
".chip": {
bg:
command.index === selected
? "color-mix(in srgb, var(--accent) 20%, transparent)"
: "var(--background-secondary)"
},
":hover:not(:disabled):not(:active)": {
bg: "hover"
}
}}
>
{command.icon && (
<command.icon
size={18}
color={
command.index === selected
? "icon-selected"
: "icon"
}
/>
)}
{["note", "notebook", "reminder", "tag"].includes(
command.type
) ? (
<Text
className="chip"
sx={{
px: 1,
borderRadius: "4px",
border: "1px solid",
borderColor: "border"
}}
>
<Highlighter text={command.title} query={query} />
</Text>
) : (
<Highlighter text={command.title} query={query} />
)}
</Button>
))}
</Flex>
</Flex>
))}
</Flex>
</ScrollContainer>
</>
</Flex>
<Flex
sx={{ flexDirection: "row", bg: "hover", justifyContent: "center" }}
>
<Text variant="subBody" sx={{ m: 0.5 }}>
<kbd>{">"}</kbd> for command mode · remove <kbd>{">"}</kbd> for
search mode · <kbd>⏎</kbd> to select · <kbd>↑</kbd>
<kbd>↓</kbd> to navigate
</Text>
</Flex>
</Dialog>
);
}
);

function Highlighter({ text, query }: { text: string; query: string }) {
const queryClean = query.startsWith(">")
? query.slice(1).trim()
: query.trim();
const result = queryClean.length > 0 ? match(queryClean, text) : false;

return (
<span
dangerouslySetInnerHTML={{
__html:
result && result.match
? surround(text, {
result: result,
Comment on lines +261 to +269
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have to use fuzzyjs's match again here to be able to use surround. Is this fine, or do you think we should refactor so that the lookup in core returns the object that surround expects?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm. I think lookup.ts should expose an API to return results with the results wrapped (the prefix/suffix could be configurable). That'll allow us to change the matcher library in the future without any other changes and also simplify all this.

prefix: "<b style='color: var(--accent-foreground)'>",
suffix: "</b>"
})
: text
}}
></span>
);
}
Loading
Loading