Add Turn into to the text toolbar, page icons from the sidebar, and steadier block handles
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
CI / desktop (ubuntu-latest) (push) Successful in 1h36m55s
CI / mobile (push) Failing after 1m47s
CI / go (Media) (push) Successful in 19m45s
CI / go (Server) (push) Failing after 26m1s
CI / go (Web-App) (push) Canceled after 0s
CI / frontend (push) Failing after 8m49s
CI / docker (push) Failing after 37m4s

Turn into: the selection toolbar starts with the block's kind ("Heading 1")
and opens the list of kinds it can become, with a tick on the current
one. In a list it turns the whole list, as the block menu did; the grip
menu no longer has it.

Page icons: an editor clicks a page's icon in the sidebar tree to pick an
emoji from groups, recent picks or a search by name (any pasted emoji
works too), or to remove it. The emoji now stands in for the page glyph
rather than sitting before the title. Strings in all five languages.

Block handles: the link and grip buttons stay on the block the cursor is
in, which is highlighted while the editor has focus, sit centred on the
block's height, and no longer vanish crossing the gap from the text.

The sidebar shows the Docwell logo above the workspace switcher.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tajniak81andClaude Opus 5.5 committed 2026-11-17 08:47:47 +01:00
1 parent c98b127f1e
commit 2a063a51be
16 files changed
+688 -60

No files matched your search

+57 -2
View File
@@ -8,6 +8,7 @@ import { DwButton, DwIcon, type IconName } from "@docwell/ui";
import { computed, nextTick, onBeforeUnmount, ref, watch } from "vue";
import { aiActions, type AiAction, type AiHost } from "./ai";
import { copyBlockLink } from "./blocklinks";
import { currentConversion, turnIntoActions, turnIntoTarget, type BlockAction } from "./blockmenu";
import { palette, type PaletteColor } from "./colors";
import { docwellExtensions, type CollabUser } from "./extensions";
import { findKey } from "./find";
@@ -174,8 +175,23 @@ onBeforeUnmount(() => editor.value?.destroy());
// The selection toolbar: formatting for editors, Comment for anyone allowed.
type Tool = { id: string; icon: IconName; label: string; active: () => boolean; run: () => void };
/** The colour or alignment choices open under the toolbar, if any. */
const panel = ref<"color" | "align" | "ai" | null>(null);
const togglePanel = (p: "color" | "align" | "ai") => (panel.value = panel.value === p ? null : p);
const panel = ref<"turn" | "color" | "align" | "ai" | null>(null);
const togglePanel = (p: "turn" | "color" | "align" | "ai") => (panel.value = panel.value === p ? null : p);
/** "Turn into" for the block the selection is in: what it is now and what it can become. Null where it has no say. */
function turnInto(e: Editor): { current: string | null; label: string; actions: BlockAction[] } | null {
const pos = turnIntoTarget(e);
if (pos < 0) return null;
const actions = turnIntoActions(e, pos, labels.value);
if (!actions.length) return null;
const current = currentConversion(e, pos);
const label = (current && labels.value.slash[current]?.label) || labels.value.blockMenu.turnInto;
return { current, label, actions };
}
function turn(a: BlockAction) {
a.run?.();
panel.value = null;
}
const alignment = (e: Editor) =>
String(e.getAttributes("paragraph").textAlign ?? e.getAttributes("heading").textAlign ?? "left");
@@ -648,6 +664,22 @@ defineExpose({ editor, openFind });
>
<div class="flex items-center gap-0.5">
<template v-if="editor.isEditable">
<button
v-if="turnInto(editor)"
type="button"
class="mr-0.5 flex h-7 max-w-36 cursor-pointer items-center gap-1 rounded-sm border-r border-line pr-1.5 pl-2 text-ui-sm font-semibold text-ink-muted hover:bg-surface-hover hover:text-ink"
:class="{ 'bg-surface-hover text-ink': panel === 'turn' }"
:aria-label="labels.blockMenu.turnInto"
:title="labels.blockMenu.turnInto"
aria-haspopup="menu"
:aria-expanded="panel === 'turn'"
data-testid="turn-into"
@mousedown.prevent
@click="togglePanel('turn')"
>
<span class="truncate">{{ turnInto(editor)!.label }}</span>
<DwIcon name="chevron-down" :size="14" class="shrink-0" />
</button>
<button
v-for="t in tools"
:key="t.id"
@@ -675,6 +707,29 @@ defineExpose({ editor, openFind });
<DwIcon name="comment" :size="16" />{{ labels.format.comment }}
</button>
</div>
<div
v-if="editor.isEditable && panel === 'turn' && turnInto(editor)"
class="flex w-48 flex-col border-t border-line px-0.5 pt-1"
role="menu"
:aria-label="labels.blockMenu.turnInto"
data-testid="turn-into-panel"
>
<button
v-for="a in turnInto(editor)!.actions"
:key="a.id"
type="button"
role="menuitemradio"
class="flex h-7 cursor-pointer items-center gap-2 rounded-sm px-2 text-left text-ui-sm text-ink hover:bg-surface-hover"
:aria-checked="turnInto(editor)!.current === a.id"
:data-testid="`turn-into-${a.id}`"
@mousedown.prevent
@click="turn(a)"
>
<DwIcon :name="a.icon" :size="16" class="shrink-0 text-ink-muted" />
<span class="flex-1 truncate">{{ a.label }}</span>
<DwIcon v-if="turnInto(editor)!.current === a.id" name="check" :size="14" class="shrink-0 text-accent" />
</button>
</div>
<div
v-if="editor.isEditable && panel === 'color'"
class="flex flex-col gap-1 border-t border-line px-1 pt-1.5 pb-0.5"
+69 -15
View File
@@ -2,8 +2,8 @@
import { Extension, type Editor } from "@tiptap/core";
import type { Node as PMNode } from "@tiptap/pm/model";
import { NodeSelection, Plugin, PluginKey } from "@tiptap/pm/state";
import type { EditorView } from "@tiptap/pm/view";
import { NodeSelection, Plugin, PluginKey, type EditorState } from "@tiptap/pm/state";
import { Decoration, DecorationSet, type EditorView } from "@tiptap/pm/view";
import { blockActions, openBlockMenu } from "./blockmenu";
import type { EditorLabels } from "./labels";
@@ -180,6 +180,17 @@ export const BlockLinks = Extension.create<BlockLinkOptions>({
new Plugin({
key: new PluginKey("blockLinks"),
view: (view) => new BlockHandle(view, editor, labels, link, onCopied),
props: {
// Marks the block the cursor is in; the stylesheet shows it only while the editor has focus.
decorations: (state) => {
const pos = currentBlock(state);
if (pos < 0) return null;
const node = state.doc.nodeAt(pos)!;
return DecorationSet.create(state.doc, [
Decoration.node(pos, pos + node.nodeSize, { class: "dw-block-current" }),
]);
},
},
}),
];
},
@@ -191,7 +202,19 @@ const linkGlyph =
const gripGlyph =
'<svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor" aria-hidden="true"><circle cx="9" cy="6" r="1.6"/><circle cx="15" cy="6" r="1.6"/><circle cx="9" cy="12" r="1.6"/><circle cx="15" cy="12" r="1.6"/><circle cx="9" cy="18" r="1.6"/><circle cx="15" cy="18" r="1.6"/></svg>';
/** The buttons that follow the pointer from block to block: copy link, and the grip. */
/** Where the top-level block holding the whole selection starts, or -1. */
function currentBlock(state: EditorState): number {
const { $from, $to } = state.selection;
if (state.selection instanceof NodeSelection && $from.depth === 0) return $from.pos;
if ($from.depth < 1 || $to.depth < 1) return -1;
const start = $from.before(1);
return start === $to.before(1) ? start : -1;
}
/**
* The buttons beside a block: copy link, and the grip. They follow the pointer
* from block to block, and otherwise stay on the block the cursor is in.
*/
class BlockHandle {
private gutter = document.createElement("div");
private linkButton = document.createElement("button");
@@ -232,12 +255,14 @@ class BlockHandle {
grip.draggable = true;
grip.addEventListener("click", this.openMenu);
grip.addEventListener("dragstart", this.dragStart);
grip.addEventListener("dragend", () => this.hide());
grip.addEventListener("dragend", () => this.rest());
if (link) g.append(b);
g.append(grip);
view.dom.addEventListener("mousemove", this.move);
view.dom.addEventListener("mouseleave", this.leave);
view.dom.addEventListener("focus", this.rest);
view.dom.addEventListener("blur", this.blur);
}
/** The element around the editor, which the buttons sit in. Hosts may move the editor after creating it. */
@@ -250,48 +275,73 @@ class BlockHandle {
return host;
}
/** Whether the pointer is over the text or the buttons. */
private hovering = false;
private hide = () => {
if (this.closeMenu) return;
this.gutter.hidden = true;
this.pos = -1;
};
/** With the pointer elsewhere: back to the block the cursor is in, if the editor has focus. */
private rest = () => {
if (this.closeMenu || this.hovering) return;
const pos = this.view.hasFocus() ? currentBlock(this.view.state) : -1;
if (pos < 0 || !this.place(pos)) this.hide();
};
private blur = (e: FocusEvent) => {
// Clicking a button moves focus onto it; the buttons stay.
if (e.relatedTarget instanceof Node && this.gutter.contains(e.relatedTarget)) return;
this.rest();
};
// Moving from the text onto the buttons keeps them.
private leave = (e: MouseEvent) => {
const to = e.relatedTarget as Node | null;
if (to && (this.gutter.contains(to) || this.view.dom.contains(to))) return;
this.hide();
this.hovering = false;
this.rest();
};
private move = (e: MouseEvent) => {
if (this.closeMenu) return;
this.hovering = true;
// The top-level block under the pointer.
let el = e.target as HTMLElement | null;
while (el && el.parentElement !== this.view.dom) el = el.parentElement;
const host = this.host;
if (!el || !host) return this.hide();
if (!el) return;
let pos: number;
try {
pos = this.view.posAtDOM(el, 0);
} catch {
return this.hide();
return;
}
const $pos = this.view.state.doc.resolve(Math.min(pos, this.view.state.doc.content.size));
const start = $pos.depth >= 1 ? $pos.before(1) : pos;
if (!this.place(start)) this.hide();
};
/** Shows the buttons beside the top-level block at `start`, centred on its height. */
private place(start: number): boolean {
const host = this.host;
const node = this.view.state.doc.nodeAt(start);
if (!node) return this.hide();
const el = node && this.view.nodeDOM(start);
if (!host || !node || !(el instanceof HTMLElement)) return false;
// Readers can only copy links that exist; only editors can add an id.
const canLink = !!this.link && linkable.includes(node.type.name) && (!!node.attrs.blockId || this.view.editable);
const canEdit = this.view.editable;
if (!canLink && !canEdit) return this.hide();
if (!canLink && !canEdit) return false;
this.linkButton.hidden = !canLink;
this.grip.hidden = !canEdit;
this.pos = start;
const box = el.getBoundingClientRect();
const hostBox = host.getBoundingClientRect();
this.gutter.style.top = `${box.top - hostBox.top + Math.min(box.height / 2, 14) - 11}px`;
this.gutter.style.top = `${box.top - hostBox.top + box.height / 2 - 11}px`;
this.gutter.hidden = false;
};
return true;
}
private openMenu = () => {
if (this.closeMenu) {
@@ -307,7 +357,7 @@ class BlockHandle {
this.closeMenu = openBlockMenu(this.grip, actions, this.labels.blockMenu.open, () => {
this.closeMenu = null;
this.grip.setAttribute("aria-expanded", "false");
this.hide();
this.rest();
});
};
@@ -330,8 +380,10 @@ class BlockHandle {
}
update() {
// Positions move as people type; the next pointer move finds the block again.
if (this.pos >= this.view.state.doc.content.size) this.hide();
if (this.closeMenu) return;
// Blocks move and grow as people type; keep the buttons on theirs.
if (!this.hovering) return this.rest();
if (this.pos < 0 || this.pos >= this.view.state.doc.content.size || !this.place(this.pos)) this.hide();
}
destroy() {
@@ -340,5 +392,7 @@ class BlockHandle {
this.gutter.remove();
this.view.dom.removeEventListener("mousemove", this.move);
this.view.dom.removeEventListener("mouseleave", this.leave);
this.view.dom.removeEventListener("focus", this.rest);
this.view.dom.removeEventListener("blur", this.blur);
}
}
+80 -35
View File
@@ -54,9 +54,87 @@ function withoutIds(json: JSONContent): JSONContent {
return out;
}
const listTypes = ["bulletList", "orderedList", "taskList"];
/**
* The actions for the top-level block at pos: turn into, move, duplicate,
* copy, delete, plus block-specific ones (line numbers, PDF pages).
* The block "Turn into" acts on for the selection: the list around the
* cursor's line, or else its own paragraph, heading, quote or code block.
* -1 when the selection spans blocks or sits somewhere else (a table cell).
*/
export function turnIntoTarget(editor: Editor): number {
const { $from, $to } = editor.state.selection;
if (!$from.parent.isTextblock) return -1;
let depth = $from.depth;
if (depth >= 3 && listTypes.includes($from.node(depth - 2).type.name)) depth -= 2;
if (depth >= 2 && $from.node(depth - 1).type.name === "blockquote") depth -= 1;
const node = $from.node(depth);
if (!convertible.includes(node.type.name)) return -1;
const pos = $from.before(depth);
return $to.pos <= pos + node.nodeSize ? pos : -1;
}
/** Which conversion id the block at pos is now, for a tick beside it. */
export function currentConversion(editor: Editor, pos: number): string | null {
const node = editor.state.doc.nodeAt(pos);
if (!node) return null;
const $pos = editor.state.doc.resolve(pos);
for (let d = $pos.depth; d >= 1; d--) if ($pos.node(d).type.name === "callout") return "callout";
switch (node.type.name) {
case "paragraph":
return "text";
case "heading":
return `h${node.attrs.level}`;
case "bulletList":
return "bullet";
case "orderedList":
return "ordered";
case "taskList":
return "todo";
case "blockquote":
return "quote";
case "codeBlock":
return "code";
}
return null;
}
/** The kinds of block the block at pos can turn into, each with what turns it. */
export function turnIntoActions(editor: Editor, pos: number, labels: EditorLabels): BlockAction[] {
const node = editor.state.doc.nodeAt(pos);
if (!node || !convertible.includes(node.type.name)) return [];
const end = pos + node.nodeSize;
return conversions.map(([id, icon, make]) => ({
id,
icon,
label: labels.slash[id]?.label ?? id,
run: () => {
if (id === "callout") {
// A callout holds any block, so the block goes in as it is (a
// heading stays a heading); a quote gives it its contents.
if (node.type.name === "callout" || currentConversion(editor, pos) === "callout") return;
const inner = node.type.name === "blockquote" ? node.content : Fragment.from(node);
const callout = editor.schema.nodes.callout!.create(null, inner);
const tr = editor.state.tr.replaceWith(pos, end, callout);
editor.view.dispatch(tr.setSelection(Selection.near(tr.doc.resolve(pos + 1))).scrollIntoView());
editor.commands.focus();
return;
}
// Select the block's text from its first to its last line (lists and
// callouts hold it deeper down), then make plain paragraphs of it, so
// every kind starts from the same place.
const doc = editor.state.doc;
const from = Selection.findFrom(doc.resolve(pos), 1, true)?.from ?? pos + 1;
const to = Selection.findFrom(doc.resolve(end), -1, true)?.to ?? end - 1;
const chain = editor.chain().focus().setTextSelection({ from, to }).clearNodes();
make(chain).run();
},
}));
}
/**
* The actions for the top-level block at pos: move, duplicate, copy, delete,
* plus block-specific ones (line numbers, PDF pages). Turning a block into
* another kind is on the selection toolbar.
*/
export function blockActions(editor: Editor, pos: number, labels: EditorLabels, copyLink?: () => void): BlockAction[] {
const node = editor.state.doc.nodeAt(pos);
@@ -66,39 +144,6 @@ export function blockActions(editor: Editor, pos: number, labels: EditorLabels,
const index = editor.state.doc.resolve(pos).index(0);
const out: BlockAction[] = [];
if (convertible.includes(node.type.name)) {
out.push({
id: "turnInto",
label: m.turnInto,
icon: "text",
children: conversions.map(([id, icon, make]) => ({
id,
icon,
label: labels.slash[id]?.label ?? id,
run: () => {
if (id === "callout") {
// A callout holds any block, so the block goes in as it is (a
// heading stays a heading); a quote gives it its contents.
if (node.type.name === "callout") return;
const inner = node.type.name === "blockquote" ? node.content : Fragment.from(node);
const callout = editor.schema.nodes.callout!.create(null, inner);
const tr = editor.state.tr.replaceWith(pos, end, callout);
editor.view.dispatch(tr.setSelection(Selection.near(tr.doc.resolve(pos + 1))).scrollIntoView());
editor.commands.focus();
return;
}
// Select the block's text from its first to its last line (lists and
// callouts hold it deeper down), then make plain paragraphs of it, so
// every kind starts from the same place.
const doc = editor.state.doc;
const from = Selection.findFrom(doc.resolve(pos), 1, true)?.from ?? pos + 1;
const to = Selection.findFrom(doc.resolve(end), -1, true)?.to ?? end - 1;
const chain = editor.chain().focus().setTextSelection({ from, to }).clearNodes();
make(chain).run();
},
})),
});
}
if (["bulletList", "orderedList", "taskList"].includes(node.type.name)) {
out.push({
id: "groupAsDatabase",
+25 -2
View File
@@ -2,7 +2,7 @@
import { Editor, type JSONContent } from "@tiptap/core";
import { afterEach, describe, expect, it } from "vitest";
import { blockActions } from "./blockmenu";
import { blockActions, currentConversion, turnIntoActions, turnIntoTarget } from "./blockmenu";
import { showsLineNumbers } from "./codeblock";
import { docwellExtensions } from "./extensions";
import { englishLabels } from "./labels";
@@ -18,7 +18,7 @@ function setup(content: string | JSONContent, opts: Parameters<typeof docwellExt
const types = (e: Editor) => (e.getJSON().content ?? []).map((n) => n.type);
const action = (e: Editor, pos: number, id: string) => {
const all = blockActions(e, pos, englishLabels);
const all = [...blockActions(e, pos, englishLabels), ...turnIntoActions(e, pos, englishLabels)];
return all.find((a) => a.id === id) ?? all.flatMap((a) => a.children ?? []).find((a) => a.id === id);
};
@@ -187,6 +187,29 @@ describe("blockActions", () => {
expect(e.getJSON().content![2]!.content!.map((n) => n.type)).toEqual(["paragraph"]);
});
it("leaves turning into to the selection toolbar", () => {
const e = setup(doc);
expect(blockActions(e, 0, englishLabels).map((a) => a.id)).not.toContain("turnInto");
});
it("finds the block the toolbar turns into, and what it is now", () => {
const e = setup("<h2>Title</h2><ul><li><p>a</p></li><li><p>b</p></li></ul><p>one</p><p>two</p>");
const at = (from: number, to = from) => {
e.commands.setTextSelection({ from, to });
const pos = turnIntoTarget(e);
return pos < 0 ? null : currentConversion(e, pos);
};
expect(at(2)).toBe("h2");
const list = e.state.doc.child(0).nodeSize;
// The cursor in a list item turns the whole list.
expect(at(list + 3)).toBe("bullet");
expect(turnIntoTarget(e)).toBe(list);
const para = list + e.state.doc.child(1).nodeSize;
expect(at(para + 1)).toBe("text");
// A selection over two blocks has no single block to turn.
expect(at(para + 1, para + e.state.doc.child(2).nodeSize + 2)).toBeNull();
});
it("deletes a block", () => {
const e = setup(doc);
action(e, 0, "delete")!.run!();
+9 -1
View File
@@ -677,10 +677,18 @@
}
.dw-block-gutter {
position: absolute;
right: calc(100% + 6px);
/* The padding covers the gap to the text, so the pointer can cross it. */
right: 100%;
padding-right: 6px;
display: flex;
gap: 2px;
}
/* The block the cursor is in. */
.dw-prose.ProseMirror-focused > .dw-block-current {
border-radius: var(--radius-sm);
background: var(--color-surface-hover);
box-shadow: 0 0 0 4px var(--color-surface-hover);
}
.dw-block-gutter[hidden],
.dw-block-handle[hidden] {
display: none;
+2 -1
View File
@@ -6,6 +6,7 @@ import type { IconName } from "./icons";
// One row of the sidebar page tree (the design system's PageTreeItem), nested
// 16px per depth on surface-sunken. The default slot is the row's main control
// (usually a link holding the title); the actions slot shows on hover and focus.
// The icon slot replaces the icon, e.g. with a button that changes it.
withDefaults(
defineProps<{
title?: string;
@@ -42,7 +43,7 @@ const emit = defineEmits<{ toggle: [] }>();
>
<DwIcon :name="expanded ? 'chevron-down' : 'chevron-right'" :size="14" />
</button>
<DwIcon :name="icon" :size="16" />
<slot name="icon"><DwIcon :name="icon" :size="16" /></slot>
<span class="min-w-0 flex-1 truncate" :title="title">
<slot>{{ title }}</slot>
</span>
@@ -1,6 +1,6 @@
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
<script setup lang="ts">
import { DwButton, DwCallout, DwIcon, useTheme, type IconName, type ThemeMode } from "@docwell/ui";
import { DwButton, DwCallout, DwIcon, DwLogo, useTheme, type IconName, type ThemeMode } from "@docwell/ui";
import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useRoute, useRouter } from "vue-router";
@@ -237,7 +237,14 @@ function signOut() {
:style="{ width: `${sidebar.width.value}px` }"
data-testid="sidebar"
>
<div class="flex shrink-0 items-center gap-1 px-2 pt-2">
<RouterLink
to="/"
class="flex h-11 shrink-0 items-center self-start rounded-sm px-4 pt-2"
data-testid="sidebar-logo"
>
<DwLogo class="h-6" />
</RouterLink>
<div class="flex shrink-0 items-center gap-1 px-2 pt-1">
<WorkspaceSwitcher />
<DwButton
variant="ghost"
@@ -0,0 +1,207 @@
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
<script setup lang="ts">
import { DwIcon } from "@docwell/ui";
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from "vue";
import {
emojiByGroup,
emojiGroups,
recentEmoji,
rememberEmoji,
searchEmoji,
typedEmoji,
type EmojiGroup,
} from "../lib/emoji";
// A page icon picker beside anchor: recent emoji, groups to scroll or jump to,
// and a search that also takes any emoji typed or pasted. Escape or a click
// elsewhere closes it.
const props = defineProps<{ anchor: HTMLElement; current?: string }>();
const emit = defineEmits<{ pick: [char: string]; remove: []; close: [] }>();
const box = ref<HTMLElement | null>(null);
const list = ref<HTMLElement | null>(null);
const input = ref<HTMLInputElement | null>(null);
const query = ref("");
const recent = ref(recentEmoji());
const pos = ref({ top: 0, left: 0 });
const groupIcons: Record<EmojiGroup, string> = {
smileys: "😀",
people: "👋",
nature: "🌿",
food: "🍎",
activity: "⚽",
travel: "🚗",
objects: "💡",
symbols: "🔣",
};
const results = computed(() => searchEmoji(query.value));
const typed = computed(() => typedEmoji(query.value));
function place() {
const r = props.anchor.getBoundingClientRect();
const w = box.value?.offsetWidth ?? 320;
const h = box.value?.offsetHeight ?? 380;
const left = Math.max(8, Math.min(r.left, window.innerWidth - w - 8));
const below = r.bottom + 4;
const top = below + h > window.innerHeight - 8 ? Math.max(8, r.top - h - 4) : below;
pos.value = { top, left };
}
function pick(char: string) {
rememberEmoji(char);
emit("pick", char);
}
function jump(g: EmojiGroup) {
query.value = "";
void nextTick(() => list.value?.querySelector(`[data-group="${g}"]`)?.scrollIntoView({ block: "start" }));
}
function onKey(e: KeyboardEvent) {
if (e.key === "Escape") {
e.stopPropagation();
emit("close");
} else if (e.key === "Enter" && e.target === input.value) {
const first = typed.value ?? results.value[0]?.char;
if (first) pick(first);
}
}
function onPointer(e: PointerEvent) {
const t = e.target as Node;
if (!box.value?.contains(t) && !props.anchor.contains(t)) emit("close");
}
onMounted(() => {
place();
void nextTick(() => {
place();
input.value?.focus();
});
document.addEventListener("pointerdown", onPointer, true);
window.addEventListener("resize", place);
});
onBeforeUnmount(() => {
document.removeEventListener("pointerdown", onPointer, true);
window.removeEventListener("resize", place);
});
</script>
<template>
<Teleport to="body">
<div
ref="box"
class="fixed z-50 flex w-80 max-w-[calc(100vw-16px)] flex-col rounded-md border border-line bg-surface-raised shadow-menu"
:style="{ top: `${pos.top}px`, left: `${pos.left}px` }"
role="dialog"
:aria-label="$t('emoji.title')"
data-testid="emoji-picker"
@keydown="onKey"
>
<div class="flex items-center gap-0.5 border-b border-line px-1.5 pt-1.5 pb-1" role="tablist">
<button
v-for="g in emojiGroups"
:key="g"
type="button"
class="grid size-7 cursor-pointer place-items-center rounded-sm text-base hover:bg-surface-hover"
:aria-label="$t(`emoji.groups.${g}`)"
:title="$t(`emoji.groups.${g}`)"
@click="jump(g)"
>
{{ groupIcons[g] }}
</button>
</div>
<div class="flex items-center gap-1.5 px-2 pt-2">
<label
class="flex h-control-sm min-w-0 flex-1 items-center gap-1.5 rounded-sm border border-line bg-surface px-2"
>
<DwIcon name="search" :size="14" class="shrink-0 text-ink-muted" />
<input
ref="input"
v-model="query"
class="min-w-0 flex-1 bg-transparent text-ui-sm text-ink outline-none placeholder:text-ink-faint"
:placeholder="$t('emoji.search')"
:aria-label="$t('emoji.search')"
data-testid="emoji-search"
/>
</label>
<button
v-if="current"
type="button"
class="h-control-sm shrink-0 cursor-pointer rounded-sm border border-line px-2 text-ui-sm text-ink-muted hover:border-line-strong hover:text-ink"
data-testid="emoji-remove"
@click="emit('remove')"
>
{{ $t("emoji.remove") }}
</button>
</div>
<div ref="list" class="h-72 overflow-y-auto px-2 pt-1 pb-2">
<template v-if="query.trim()">
<div class="grid grid-cols-8">
<button
v-if="typed && !results.some((r) => r.char === typed)"
type="button"
class="grid size-9 cursor-pointer place-items-center rounded-sm text-xl hover:bg-surface-hover"
@click="pick(typed)"
>
{{ typed }}
</button>
<button
v-for="e in results"
:key="e.char"
type="button"
class="grid size-9 cursor-pointer place-items-center rounded-sm text-xl hover:bg-surface-hover"
:title="e.words"
:aria-label="e.words"
@click="pick(e.char)"
>
{{ e.char }}
</button>
</div>
<p v-if="!typed && !results.length" class="px-1 py-6 text-center text-ui-sm text-ink-muted">
{{ $t("emoji.none") }}
</p>
</template>
<template v-else>
<template v-if="recent.length">
<h3 class="sticky top-0 bg-surface-raised px-1 pt-1.5 pb-1 text-ui-xs font-semibold text-ink-muted">
{{ $t("emoji.recent") }}
</h3>
<div class="grid grid-cols-8">
<button
v-for="c in recent"
:key="c"
type="button"
class="grid size-9 cursor-pointer place-items-center rounded-sm text-xl hover:bg-surface-hover"
@click="pick(c)"
>
{{ c }}
</button>
</div>
</template>
<section v-for="g in emojiGroups" :key="g" :data-group="g">
<h3 class="sticky top-0 bg-surface-raised px-1 pt-1.5 pb-1 text-ui-xs font-semibold text-ink-muted">
{{ $t(`emoji.groups.${g}`) }}
</h3>
<div class="grid grid-cols-8">
<button
v-for="e in emojiByGroup[g]"
:key="e.char"
type="button"
class="grid size-9 cursor-pointer place-items-center rounded-sm text-xl hover:bg-surface-hover"
:class="{ 'bg-accent-soft': e.char === current }"
:title="e.words"
:aria-label="e.words"
@click="pick(e.char)"
>
{{ e.char }}
</button>
</div>
</section>
</template>
</div>
</div>
</Teleport>
</template>
@@ -6,6 +6,7 @@ import { computed, ref } from "vue";
import { useRouter } from "vue-router";
import { dropPlacement, zoneAt, type DropZone } from "../lib/tree";
import { useSpacesStore } from "../stores/spaces";
import EmojiPicker from "./EmojiPicker.vue";
const props = defineProps<{ spaceId: string; node: PageNode; depth: number }>();
const emit = defineEmits<{ error: [err: unknown] }>();
@@ -18,6 +19,18 @@ const editable = computed(() => spaces.canEdit(props.spaceId));
const active = computed(() => spaces.active.page === props.node.id);
const zone = ref<DropZone | null>(null);
// The page's icon: an emoji, or the page glyph. Editors click it to pick another.
const iconButton = ref<HTMLElement | null>(null);
const picking = ref(false);
async function setIcon(icon: string) {
picking.value = false;
try {
await spaces.setIcon(props.spaceId, props.node.id, icon);
} catch (e) {
emit("error", e);
}
}
function onDragStart(e: DragEvent) {
spaces.dragging = { spaceId: props.spaceId, id: props.node.id };
e.dataTransfer?.setData("text/plain", props.node.id);
@@ -102,14 +115,35 @@ const dropClass = computed(() => {
@dragleave="zone = null"
@drop.prevent="onDrop"
>
<template #icon>
<button
v-if="editable"
ref="iconButton"
type="button"
class="grid size-5 shrink-0 cursor-pointer place-items-center rounded-xs hover:bg-line"
:class="{ 'bg-line': picking }"
:aria-label="$t('emoji.changeIcon')"
:title="$t('emoji.changeIcon')"
aria-haspopup="dialog"
:aria-expanded="picking"
data-testid="page-icon"
@click.stop="picking = !picking"
>
<span v-if="node.icon" class="text-ui-md leading-none">{{ node.icon }}</span>
<DwIcon v-else name="page" :size="16" />
</button>
<span v-else-if="node.icon" class="grid size-5 shrink-0 place-items-center text-ui-md leading-none">{{
node.icon
}}</span>
<DwIcon v-else name="page" :size="16" />
</template>
<RouterLink
:to="{ name: 'page', params: { id: node.id } }"
class="block truncate rounded-xs"
:class="active ? 'text-accent' : 'text-inherit'"
:aria-current="active ? 'page' : undefined"
>
<span v-if="node.icon" class="mr-1">{{ node.icon }}</span
>{{ node.title || $t("home.untitled") }}
{{ node.title || $t("home.untitled") }}
<DwIcon
v-if="node.restricted"
name="lock"
@@ -139,6 +173,14 @@ const dropClass = computed(() => {
/>
</template>
</DwTreeItem>
<EmojiPicker
v-if="picking && iconButton"
:anchor="iconButton"
:current="node.icon"
@pick="setIcon"
@remove="setIcon('')"
@close="picking = false"
/>
<ul v-if="open && kids.length" role="group" class="mt-px flex flex-col gap-px">
<PageTreeNode
v-for="k in kids"
+80
View File
@@ -0,0 +1,80 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// The emoji the page icon picker offers, by group, each with English words to
// find it by. Any other emoji can still be typed or pasted into the search.
export type EmojiGroup = "smileys" | "people" | "nature" | "food" | "activity" | "travel" | "objects" | "symbols";
export interface Emoji {
char: string;
words: string;
}
const raw: Record<EmojiGroup, string> = {
smileys: `😀 grinning smile happy|😃 smiley happy|😄 smile laugh|😁 grin beam|😆 laughing|😅 sweat smile|🤣 rofl rolling laugh|😂 joy tears laugh|🙂 slight smile|🙃 upside down|😉 wink|😊 blush happy|😇 innocent halo angel|🥰 love hearts|😍 heart eyes love|🤩 star struck|😘 kiss blow|😋 yum tasty|😛 tongue|😜 wink tongue|🤪 zany crazy|🤑 money|🤗 hug|🤭 oops giggle|🤫 shush quiet|🤔 thinking|🤐 zipper mouth|😐 neutral|😑 expressionless|😶 no mouth|😏 smirk|😒 unamused|🙄 eye roll|😬 grimace|😌 relieved|😔 pensive sad|😪 sleepy|😴 sleeping|😷 mask sick|🤒 thermometer ill|🤯 mind blown exploding|🥳 party celebrate|😎 cool sunglasses|🤓 nerd geek|🧐 monocle|😕 confused|😟 worried|😮 surprised open mouth|😲 astonished|😳 flushed|🥺 pleading|😢 cry tear|😭 sob crying|😱 scream fear|😤 triumph steam|😡 angry rage|🤬 cursing|😈 devil|💀 skull dead|💩 poop|🤡 clown|👻 ghost|👽 alien|🤖 robot|😺 cat smile|❤️ heart love red`,
people: `👋 wave hello hi|🤚 raised back hand|✋ hand stop|👌 ok okay|✌️ victory peace|🤞 crossed fingers luck|🤟 love you|🤘 rock horns|👈 point left|👉 point right|👆 point up|👇 point down|☝️ index up|👍 thumbs up like yes|👎 thumbs down no|✊ fist|👊 punch|👏 clap applause|🙌 raised hands hooray|🤝 handshake deal|🙏 pray thanks please|✍️ writing|💪 muscle strong|🧠 brain|👀 eyes look|👁️ eye|👤 person user|👥 people users team|🧑‍💻 developer coder technologist|🧑‍🏫 teacher|🧑‍🎓 student|🧑‍🔬 scientist|🧑‍🎨 artist|🧑‍🍳 cook chef|🧑‍🔧 mechanic|🧑‍⚕️ doctor health|🧑‍💼 office worker business|🕵️ detective|👷 construction worker|🦸 superhero|🧙 wizard mage|🏃 running|🚶 walking|🧘 yoga meditation|👪 family|👶 baby`,
nature: `🐶 dog puppy|🐱 cat kitten|🐭 mouse|🐰 rabbit bunny|🦊 fox|🐻 bear|🐼 panda|🐨 koala|🐯 tiger|🦁 lion|🐮 cow|🐷 pig|🐸 frog|🐵 monkey|🐔 chicken|🐧 penguin|🐦 bird|🦉 owl|🦄 unicorn|🐝 bee|🐛 bug|🦋 butterfly|🐢 turtle|🐍 snake|🐙 octopus|🐬 dolphin|🐳 whale|🐟 fish|🦈 shark|🌵 cactus|🎄 christmas tree|🌲 evergreen tree|🌳 tree|🌴 palm|🌱 seedling sprout|🌿 herb|🍀 clover luck|🍁 maple leaf|🍂 fallen leaves autumn|🌷 tulip|🌹 rose|🌻 sunflower|🌸 blossom|💐 bouquet flowers|🍄 mushroom|🌍 earth world globe|🌙 moon night|⭐ star|🌟 glowing star|✨ sparkles|⚡ lightning zap|🔥 fire hot|🌈 rainbow|☀️ sun|⛅ cloud sun|☁️ cloud|🌧️ rain|❄️ snow snowflake|💧 droplet water|🌊 wave ocean sea`,
food: `🍏 green apple|🍎 apple red|🍐 pear|🍊 orange|🍋 lemon|🍌 banana|🍉 watermelon|🍇 grapes|🍓 strawberry|🫐 blueberries|🍒 cherries|🍑 peach|🥭 mango|🍍 pineapple|🥥 coconut|🥝 kiwi|🍅 tomato|🥑 avocado|🥦 broccoli|🥕 carrot|🌽 corn|🌶️ pepper hot|🥔 potato|🍞 bread|🥐 croissant|🧀 cheese|🥚 egg|🍳 cooking|🥞 pancakes|🥓 bacon|🍔 burger|🍟 fries|🍕 pizza|🌭 hot dog|🌮 taco|🌯 burrito|🥗 salad|🍝 pasta spaghetti|🍜 ramen noodles|🍣 sushi|🍱 bento|🍦 ice cream|🍩 doughnut|🍪 cookie|🎂 birthday cake|🍰 cake|🧁 cupcake|🍫 chocolate|🍬 candy|🍿 popcorn|☕ coffee|🍵 tea|🧃 juice|🥤 drink|🍺 beer|🍷 wine|🍸 cocktail|🥂 cheers champagne|🍽️ dinner plate`,
activity: `⚽ soccer football|🏀 basketball|🏈 american football|⚾ baseball|🎾 tennis|🏐 volleyball|🏉 rugby|🎱 billiards|🏓 ping pong|🏸 badminton|🥅 goal|⛳ golf|🏹 archery|🎣 fishing|🥊 boxing|🎽 running shirt|⛸️ ice skate|🎿 ski|🏂 snowboard|🏋️ weights gym|🚴 cycling bike|🏆 trophy win|🥇 gold medal first|🥈 silver medal|🥉 bronze medal|🏅 medal|🎖️ military medal|🎫 ticket|🎪 circus|🎭 theatre drama|🎨 art palette paint|🎬 movie clapper film|🎤 microphone sing|🎧 headphones music|🎼 score|🎹 piano|🥁 drum|🎷 saxophone|🎺 trumpet|🎸 guitar|🎻 violin|🎲 dice game|♟️ chess|🎯 target goal dart|🎳 bowling|🎮 video game|🧩 puzzle|🎉 party popper tada|🎊 confetti|🎈 balloon|🎁 gift present`,
travel: `🚗 car|🚕 taxi|🚌 bus|🚎 trolleybus|🏎️ race car|🚓 police car|🚑 ambulance|🚒 fire engine|🚚 truck delivery|🚜 tractor|🛵 scooter|🚲 bicycle|🛴 kick scooter|🚂 train locomotive|🚆 train|🚇 metro subway|✈️ airplane flight|🛫 departure|🛬 arrival|🚀 rocket launch|🛸 ufo|🚁 helicopter|⛵ sailboat|🚤 speedboat|🚢 ship|⚓ anchor|🗺️ map|🧭 compass|🏔️ mountain snow|⛰️ mountain|🌋 volcano|🏕️ camping|🏖️ beach|🏝️ island|🏠 house home|🏡 garden home|🏢 office building|🏬 department store|🏭 factory|🏥 hospital|🏦 bank|🏨 hotel|🏪 shop store|🏫 school|🏛️ classical building|⛪ church|🏰 castle|🗼 tower|🗽 statue liberty|⛲ fountain|🌆 city|🌃 night city|🌉 bridge|🎡 ferris wheel|🎢 roller coaster|🚦 traffic light|🚧 construction|⛽ fuel`,
objects: `📄 page document|📃 curl page|📑 bookmark tabs|📝 memo note write|📋 clipboard|📌 pushpin pin|📍 location pin|📎 paperclip|🖇️ paperclips|📏 ruler|📐 triangle ruler|✂️ scissors|🗂️ dividers index|📁 folder|📂 open folder|🗃️ card box|🗄️ cabinet|🗑️ trash wastebasket|📅 calendar date|📆 tear off calendar|🗓️ spiral calendar|📇 card index|📈 chart up growth|📉 chart down|📊 bar chart stats|📒 ledger|📓 notebook|📔 notebook decorative|📕 book closed|📗 green book|📘 blue book|📙 orange book|📚 books library|📖 open book read|🔖 bookmark|🏷️ label tag|💼 briefcase work|💻 laptop computer|🖥️ desktop computer|⌨️ keyboard|🖱️ mouse computer|📱 phone mobile|☎️ telephone|📞 receiver call|📠 fax|🔋 battery|🔌 plug|💡 bulb idea|🔦 flashlight|🕯️ candle|💰 money bag|💳 card credit|🧾 receipt|✉️ envelope mail|📧 email|📨 incoming mail|📦 package box|📮 postbox|🔒 lock locked|🔓 unlocked|🔑 key|🗝️ old key|🔨 hammer|🛠️ tools|🔧 wrench|🔩 nut bolt|⚙️ gear settings|🧰 toolbox|🧲 magnet|🧪 test tube|🔬 microscope|🔭 telescope|📡 satellite|💊 pill|🩺 stethoscope|🛒 cart shopping|🎓 graduation cap|👑 crown|💎 gem diamond|⏰ alarm clock|⏳ hourglass|⌛ hourglass done|🕐 clock time|📷 camera photo|🎥 video camera|📺 television tv|📻 radio|🔔 bell notification|📣 megaphone announce|📢 loudspeaker|🔍 search magnifier|🧭 compass direction`,
symbols: `✅ check done yes|☑️ ballot check|✔️ check mark|❌ cross no|❎ cross button|➕ plus add|➖ minus|➗ divide|✖️ multiply|❓ question|❔ white question|❗ exclamation important|‼️ double exclamation|⚠️ warning|🚫 prohibited|⛔ no entry|🛑 stop|💯 hundred|🔴 red circle|🟠 orange circle|🟡 yellow circle|🟢 green circle|🔵 blue circle|🟣 purple circle|⚫ black circle|⚪ white circle|🟥 red square|🟧 orange square|🟨 yellow square|🟩 green square|🟦 blue square|🟪 purple square|⬛ black square|⬜ white square|🔶 orange diamond|🔷 blue diamond|♻️ recycle|⚛️ atom|☮️ peace|☯️ yin yang|♾️ infinity|💲 dollar|💱 exchange|©️ copyright|®️ registered|™️ trademark|🔝 top|🔜 soon|🆕 new|🆓 free|🆗 ok|🆙 up|🆒 cool|ℹ️ info information|🔤 abc letters|🔢 numbers|#️⃣ hash|➡️ right arrow|⬅️ left arrow|⬆️ up arrow|⬇️ down arrow|🔄 refresh sync|🔁 repeat|▶️ play|⏸️ pause|⏹️ stop|⏩ fast forward|💬 speech chat comment|💭 thought|🗯️ anger bubble|💤 sleep zzz|💥 boom collision|💫 dizzy|🎵 music note|🔗 link|🏁 finish flag|🚩 red flag|🏳️ white flag|🏴 black flag|💜 purple heart|💙 blue heart|💚 green heart|💛 yellow heart|🧡 orange heart|🖤 black heart|💔 broken heart`,
};
export const emojiGroups = Object.keys(raw) as EmojiGroup[];
export const emojiByGroup: Record<EmojiGroup, Emoji[]> = Object.fromEntries(
emojiGroups.map((g) => [
g,
raw[g].split("|").map((entry) => {
const [char = "", ...words] = entry.trim().split(" ");
return { char, words: words.join(" ") };
}),
]),
) as Record<EmojiGroup, Emoji[]>;
/** The emoji whose words start with every word of the query, in group order. */
export function searchEmoji(query: string): Emoji[] {
const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
if (!terms.length) return [];
const seen = new Set<string>();
const out: Emoji[] = [];
for (const g of emojiGroups) {
for (const e of emojiByGroup[g]) {
if (seen.has(e.char)) continue;
const words = e.words.split(" ");
if (terms.every((t) => words.some((w) => w.startsWith(t)))) {
seen.add(e.char);
out.push(e);
}
}
}
return out;
}
/** Text that is itself an icon: a few characters with no letters or digits, as the server keeps at most 32 bytes. */
export function typedEmoji(text: string): string | null {
const t = text.trim();
if (!t || /[\p{L}\p{N}]/u.test(t) || new TextEncoder().encode(t).length > 32) return null;
return /\p{Extended_Pictographic}/u.test(t) ? t : null;
}
const recentKey = "docwell.recentEmoji";
/** The emoji this browser picked last, newest first. */
export function recentEmoji(): string[] {
try {
const list = JSON.parse(localStorage.getItem(recentKey) ?? "[]");
return Array.isArray(list) ? list.filter((x) => typeof x === "string").slice(0, 16) : [];
} catch {
return [];
}
}
export function rememberEmoji(char: string) {
try {
localStorage.setItem(recentKey, JSON.stringify([char, ...recentEmoji().filter((c) => c !== char)].slice(0, 16)));
} catch {
// Private windows may refuse storage; the picker works without it.
}
}
+18
View File
@@ -1700,5 +1700,23 @@
"comment_created": "jemand kommentiert",
"comment_resolved": "ein Kommentar erledigt wird"
}
},
"emoji": {
"title": "Seitensymbol",
"changeIcon": "Symbol ändern",
"search": "Emoji suchen oder einfügen",
"remove": "Entfernen",
"recent": "Zuletzt verwendet",
"none": "Kein Emoji gefunden",
"groups": {
"smileys": "Smileys",
"people": "Menschen",
"nature": "Natur",
"food": "Essen und Trinken",
"activity": "Aktivitäten",
"travel": "Reisen und Orte",
"objects": "Objekte",
"symbols": "Symbole"
}
}
}
+18
View File
@@ -1700,5 +1700,23 @@
"comment_created": "someone comments",
"comment_resolved": "a comment is resolved"
}
},
"emoji": {
"title": "Page icon",
"changeIcon": "Change icon",
"search": "Search emoji or paste one",
"remove": "Remove",
"recent": "Recently used",
"none": "No emoji found",
"groups": {
"smileys": "Smileys",
"people": "People",
"nature": "Nature",
"food": "Food and drink",
"activity": "Activities",
"travel": "Travel and places",
"objects": "Objects",
"symbols": "Symbols"
}
}
}
+18
View File
@@ -1700,5 +1700,23 @@
"comment_created": "alguien comenta",
"comment_resolved": "se resuelve un comentario"
}
},
"emoji": {
"title": "Icono de la página",
"changeIcon": "Cambiar icono",
"search": "Busca un emoji o pégalo",
"remove": "Quitar",
"recent": "Usados recientemente",
"none": "No se encontró ningún emoji",
"groups": {
"smileys": "Caras",
"people": "Personas",
"nature": "Naturaleza",
"food": "Comida y bebida",
"activity": "Actividades",
"travel": "Viajes y lugares",
"objects": "Objetos",
"symbols": "Símbolos"
}
}
}
+18
View File
@@ -1700,5 +1700,23 @@
"comment_created": "quelqu’un commente",
"comment_resolved": "un commentaire est résolu"
}
},
"emoji": {
"title": "Icône de la page",
"changeIcon": "Changer l’icône",
"search": "Chercher un emoji ou en coller un",
"remove": "Retirer",
"recent": "Utilisés récemment",
"none": "Aucun emoji trouvé",
"groups": {
"smileys": "Smileys",
"people": "Personnes",
"nature": "Nature",
"food": "Nourriture et boissons",
"activity": "Activités",
"travel": "Voyages et lieux",
"objects": "Objets",
"symbols": "Symboles"
}
}
}
+18
View File
@@ -1700,5 +1700,23 @@
"comment_created": "ktoś komentuje",
"comment_resolved": "komentarz jest rozwiązany"
}
},
"emoji": {
"title": "Ikona strony",
"changeIcon": "Zmień ikonę",
"search": "Szukaj emoji lub wklej",
"remove": "Usuń",
"recent": "Ostatnio używane",
"none": "Nie znaleziono emoji",
"groups": {
"smileys": "Buźki",
"people": "Ludzie",
"nature": "Przyroda",
"food": "Jedzenie i napoje",
"activity": "Aktywności",
"travel": "Podróże i miejsca",
"objects": "Przedmioty",
"symbols": "Symbole"
}
}
}
+16
View File
@@ -138,6 +138,21 @@ export const useSpacesStore = defineStore("spaces", () => {
if (node) node.title = title;
}
/** Sets a page's icon ("" removes it) and mirrors it into the sidebar. */
async function setIcon(spaceId: string, id: string, icon: string) {
const node = trees.value[spaceId]?.find((n) => n.id === id);
const before = node?.icon;
if (node) node.icon = icon;
try {
const saved = await api.pages.update(id, { icon });
if (node) node.icon = saved.icon;
return saved;
} catch (e) {
if (node) node.icon = before ?? "";
throw e;
}
}
async function trash(spaceId: string, id: string) {
await api.pages.trash(id);
await loadTree(spaceId);
@@ -163,6 +178,7 @@ export const useSpacesStore = defineStore("spaces", () => {
createPage,
move,
setTitle,
setIcon,
trash,
};
});