diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 6f020e4..a6f83a6 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -540,6 +540,24 @@ pub fn set_scroll_to_change_font_size( .map_err(|e| e.to_string()) } +#[tauri::command] +pub fn set_toolbar_layout( + app: AppHandle, + state: State<'_, AppState>, + layout: Option, +) -> Result<(), String> { + let mut config = state.config.lock().map_err(|e| e.to_string())?; + let previous = std::mem::replace(&mut config.toolbar_layout, layout); + if let Err(error) = save_app_config(&config) { + config.toolbar_layout = previous; + return Err(error); + } + + use tauri::Emitter; + app.emit("toolbar-layout-changed", &config.toolbar_layout) + .map_err(|error| error.to_string()) +} + #[tauri::command] pub fn set_font_family(state: State<'_, AppState>, family: String) -> Result<(), String> { let mut config = state.config.lock().map_err(|e| e.to_string())?; diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index a60a50d..ff57988 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -173,6 +173,7 @@ pub fn run() { commands::import_custom_themes, commands::set_font_size, commands::set_scroll_to_change_font_size, + commands::set_toolbar_layout, commands::set_font_family, commands::set_line_height, commands::set_ui_scale, diff --git a/src-tauri/src/types.rs b/src-tauri/src/types.rs index 36636af..fde1d94 100644 --- a/src-tauri/src/types.rs +++ b/src-tauri/src/types.rs @@ -138,6 +138,12 @@ pub enum StartupView { All, } +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ToolbarLayout { + pub main: Vec, + pub more: Vec, +} + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AppConfig { pub vaults: Vec, @@ -158,6 +164,8 @@ pub struct AppConfig { #[serde(default = "default_true")] pub scroll_to_change_font_size: bool, #[serde(default)] + pub toolbar_layout: Option, + #[serde(default)] pub font_family: Option, #[serde(default)] pub line_height: Option, @@ -330,6 +338,7 @@ impl Default for AppConfig { accent_color: None, font_size: None, scroll_to_change_font_size: true, + toolbar_layout: None, font_family: None, line_height: None, ui_scale: None, diff --git a/src/lib/api.ts b/src/lib/api.ts index 3201328..4f70ff1 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -19,6 +19,7 @@ import type { TaskItem, ExternalVaultResult, StartupView, + ToolbarLayout, } from "./types"; export async function openVault(path: string): Promise { @@ -81,6 +82,10 @@ export async function setScrollToChangeFontSize(enabled: boolean): Promise return invoke("set_scroll_to_change_font_size", { enabled }); } +export async function setToolbarLayout(layout: ToolbarLayout | null): Promise { + return invoke("set_toolbar_layout", { layout }); +} + export async function setFontFamily(family: string): Promise { return invoke("set_font_family", { family }); } diff --git a/src/lib/components/AppLayout.svelte b/src/lib/components/AppLayout.svelte index f2e678c..f3d451c 100644 --- a/src/lib/components/AppLayout.svelte +++ b/src/lib/components/AppLayout.svelte @@ -1267,10 +1267,10 @@
diff --git a/src/lib/components/Editor.svelte b/src/lib/components/Editor.svelte index e396890..12c1896 100644 --- a/src/lib/components/Editor.svelte +++ b/src/lib/components/Editor.svelte @@ -39,8 +39,8 @@ import { openFile, openUrl, copyFileTo, copyImageToClipboard as copyImageToClipboardCmd, writeBytesTo, copyPngToClipboard, copyTextToClipboard } from '$lib/api'; import { save as saveDialog } from '@tauri-apps/plugin-dialog'; import { activeNote, activeNotePath, appConfig, editorDirty, sourceMode, focusMode, readOnly, quickAccessPaths, notes, navHistory, canGoBack, canGoForward, viewerNote, viewMode, notebooks, outlineWidth } from '$lib/stores/app'; - import { saveNote, saveImage, saveAttachment, readClipboardImage, addQuickAccess, removeQuickAccess, getQuickAccess, getNoteVersions, getNoteVersionContent, createVersion, aiAsk, getAllNoteTitles, readNote, renameNote } from '$lib/api'; - import type { VersionEntry, AiStreamEvent, NoteTitleEntry, TaskItem as TaskRecord, FileEvent, SearchTarget } from '$lib/types'; + import { saveNote, saveImage, saveAttachment, readClipboardImage, addQuickAccess, removeQuickAccess, getQuickAccess, getNoteVersions, getNoteVersionContent, createVersion, aiAsk, getAllNoteTitles, readNote, renameNote, setToolbarLayout } from '$lib/api'; + import type { VersionEntry, AiStreamEvent, NoteTitleEntry, TaskItem as TaskRecord, FileEvent, SearchTarget, ToolbarLayout } from '$lib/types'; import { listen } from '@tauri-apps/api/event'; import { debounce } from '$lib/utils/debounce'; import { RevisionSaveQueue, type SaveRevision } from '$lib/utils/revision-save'; @@ -56,6 +56,7 @@ import { resolveSearchTarget, visibleSearchTarget } from '$lib/editor/search-target'; import { convertListNode, type MixedListName } from '$lib/editor/mixedLists'; import { clearFormatting } from '$lib/editor/clearFormatting'; + import { toolbarLabels, resolveToolbarLayout, groupToolbarButtons, moveToolbarButton, toolbarLayoutPreference, type ToolbarButtonId, type ToolbarArea, type ResolvedToolbarLayout } from '$lib/editor/toolbar'; import { buildCodeCopyDecorations, buildTaskMetaDecorations, focusedPlaceholderDecorations } from '$lib/editor/decorations'; import { serializeInlineMarkdown } from '$lib/editor/markdown'; import { restoreTitleHeading, stripTitleHeading, type HiddenTitleHeading } from '$lib/editor/titleVisibility'; @@ -77,12 +78,18 @@ // Track virtual keyboard height on mobile via visualViewport let keyboardHeight = $state(0); - if (isMobile && typeof window !== 'undefined' && window.visualViewport) { + $effect(() => { + if (!isMobile || !window.visualViewport) return; const vv = window.visualViewport; const update = () => { keyboardHeight = Math.max(0, Math.round(window.innerHeight - vv.height - vv.offsetTop)); }; + update(); vv.addEventListener('resize', update); vv.addEventListener('scroll', update); - } + return () => { + vv.removeEventListener('resize', update); + vv.removeEventListener('scroll', update); + }; + }); let editorElement = $state(null!); const LARGE_DOC_CHARS = 100_000; @@ -137,6 +144,35 @@ let insertDropdown = $state(false); let tablePickerOpen = $state(false); let tablePickerHover = $state({ rows: 0, cols: 0 }); + let formattingBar = $state(); + let moreButton = $state(); + let morePanel = $state(); + let moreOpen = $state(false); + let moreOpenedByHover = false; + let moreCloseTimer: ReturnType | null = null; + let formattingTrigger: HTMLButtonElement | null = null; + const morePanelId = $props.id(); + let toolbarDraft = $state(null); + let toolbarSelected = $state(null); + let toolbarSaving = $state(false); + let toolbarSaveError = $state(null); + let toolbarConflict = $state(false); + let toolbarBase = ''; + let toolbarEditSession = 0; + let toolbarPendingPreference: string | null = null; + let toolbarDrag: { id: ToolbarButtonId; pointerId: number; startX: number; startY: number; x: number; y: number; button: HTMLButtonElement; active: boolean } | null = null; + let toolbarDraggedId = $state(null); + let toolbarDrop = $state<{ area: ToolbarArea; index: number; left: number; top: number; height: number } | null>(null); + let toolbarDragGhost: HTMLElement | null = null; + let toolbarDragFrame = 0; + let toolbarCapture: HTMLElement | null = null; + const toolbarLayout = $derived(toolbarDraft ?? resolveToolbarLayout($appConfig?.toolbar_layout, isMobile, !!$appConfig?.ai_provider)); + const formattingGroups = $derived(groupToolbarButtons(toolbarLayout.main, isMobile)); + const toolbarSelectedArea = $derived(toolbarSelected && toolbarDraft + ? (toolbarDraft.main.includes(toolbarSelected) ? 'main' : toolbarDraft.more.includes(toolbarSelected) ? 'more' : null) : null); + const toolbarSelectedIndex = $derived(toolbarSelected && toolbarDraft && toolbarSelectedArea + ? toolbarDraft[toolbarSelectedArea].indexOf(toolbarSelected) : -1); + const toolbarHintId = `${morePanelId}-customize-hint`; function scrollEditorBodyToBottom(source: HTMLElement | null | undefined = editorElement) { const editorBody = source?.closest('.editor-body') as HTMLElement | null; @@ -340,12 +376,10 @@ function closeAllDropdowns() { - headingDropdown = false; - colorDropdown = false; - highlightDropdown = false; - alignDropdown = false; - insertDropdown = false; - tablePickerOpen = false; + closeFormattingDropdowns(); + closeMore(); + formattingTrigger = null; + tablePickerHover = { rows: 0, cols: 0 }; } let anyDropdownOpen = $derived(headingDropdown || colorDropdown || highlightDropdown || alignDropdown || insertDropdown || tablePickerOpen); @@ -543,17 +577,6 @@ let imageViewer = $state<{ src: string; alt: string } | null>(null); let copyToast = $state<'copying' | 'done' | null>(null); - $effect(() => { - const open = headingDropdown || colorDropdown || highlightDropdown || alignDropdown || insertDropdown || tablePickerOpen; - if (!open) return; - requestAnimationFrame(() => { - document.querySelectorAll('.fmt-dropdown').forEach((el) => { - const overflow = el.getBoundingClientRect().right - (window.innerWidth - 8); - el.style.transform = overflow > 0 ? `translateX(${-overflow}px)` : ''; - }); - }); - }); - // Math insert/edit modal (opened by /math slash command or double-click on existing math node) let mathModal = $state<{ kind: 'block' | 'inline'; editPos: number | null; tex: string } | null>(null); @@ -3555,6 +3578,7 @@ } export function loadNote(path: string, content: string, taskTarget?: TaskRecord) { + endToolbarCustomization(); cancelCounts(); closeNoteSearch(false); saves.startSession(); @@ -3910,8 +3934,387 @@ insertDropdown = false; } + function beginToolbarCustomization() { + if (isMobile || toolbarSaving) return; + closeAllDropdowns(); + toolbarBase = JSON.stringify($appConfig?.toolbar_layout ?? null); + toolbarEditSession++; + toolbarDraft = resolveToolbarLayout($appConfig?.toolbar_layout, false, !!$appConfig?.ai_provider); + toolbarSelected = toolbarDraft.main[0] ?? toolbarDraft.more[0] ?? null; + toolbarSaveError = null; + toolbarConflict = false; + moreOpen = true; + // Mouse entry must not steal the note's selection; keyboard entry stays in the toolbar. + if (formattingBar?.contains(document.activeElement)) focusToolbarSelection(); + } + + function endToolbarCustomization(restoreFocus = false) { + toolbarEditSession++; + cancelToolbarDrag(); + toolbarDraft = null; + toolbarSelected = null; + toolbarSaveError = null; + toolbarConflict = false; + closeAllDropdowns(); + if (restoreFocus) moreButton?.focus({ preventScroll: true }); + } + + function resetToolbarDraft() { + if (!toolbarDraft || toolbarSaving) return; + cancelToolbarDrag(); + toolbarDraft = resolveToolbarLayout(null, false, !!$appConfig?.ai_provider); + if (!toolbarSelected || !toolbarDraft.main.includes(toolbarSelected)) toolbarSelected = toolbarDraft.main[0] ?? null; + toolbarSaveError = null; + } + + async function saveToolbarDraft() { + if (!toolbarDraft || toolbarSaving || toolbarConflict || !$appConfig) return; + if (JSON.stringify($appConfig.toolbar_layout ?? null) !== toolbarBase) { + toolbarConflict = true; + return; + } + cancelToolbarDrag(); + const preference = toolbarLayoutPreference(toolbarDraft); + const session = toolbarEditSession; + const base = toolbarBase; + toolbarPendingPreference = JSON.stringify(preference); + toolbarSaving = true; + toolbarSaveError = null; + try { + await setToolbarLayout(preference); + // A concurrent window's event wins over this request's stale local response, + // including when note navigation already dismissed this customization session. + const current = JSON.stringify($appConfig?.toolbar_layout ?? null); + if (!toolbarConflict && (current === base || current === toolbarPendingPreference)) { + appConfig.update(config => config ? { ...config, toolbar_layout: preference } : config); + } else if (session === toolbarEditSession) { + toolbarConflict = true; + } + if (session === toolbarEditSession && !toolbarConflict) { + endToolbarCustomization(!!formattingBar?.contains(document.activeElement)); + } + } catch (error) { + if (session === toolbarEditSession) toolbarSaveError = `Could not save toolbar: ${String(error)}`; + } finally { + toolbarSaving = false; + toolbarPendingPreference = null; + } + } + + function focusToolbarSelection() { + const id = toolbarSelected; + void tick().then(() => { + if (!toolbarDraft || toolbarSelected !== id || !id) return; + const button = formattingBar?.querySelector(`[data-toolbar-id="${id}"] button`); + button?.focus({ preventScroll: true }); + button?.scrollIntoView({ block: 'nearest', inline: 'nearest' }); + }); + } + + function moveSelectedToolbarButton(area: ToolbarArea, index: number, focus = false) { + if (!toolbarDraft || !toolbarSelected || toolbarSaving) return; + toolbarDraft = moveToolbarButton(toolbarDraft, toolbarSelected, area, index); + toolbarSaveError = null; + if (focus) focusToolbarSelection(); + } + + function selectToolbarControl(event: Event) { + if (!toolbarDraft) return; + const item = (event.target as Element).closest('[data-toolbar-id]'); + if (item && !toolbarSaving) toolbarSelected = item.dataset.toolbarId as ToolbarButtonId; + } + + function captureToolbarClick(event: MouseEvent) { + if (!toolbarDraft || !(event.target as Element).closest('[data-toolbar-id]')) return; + event.preventDefault(); + event.stopPropagation(); + selectToolbarControl(event); + } + + function customizeToolbarKeydown(event: KeyboardEvent) { + if (!toolbarDraft || !(event.target as Element).closest('[data-toolbar-id]')) return; + if (!['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End', 'Enter', ' '].includes(event.key)) return; + event.preventDefault(); + event.stopPropagation(); + selectToolbarControl(event); + if (toolbarSaving || !toolbarSelectedArea) return; + const area = toolbarSelectedArea; + if (event.key === 'ArrowLeft') moveSelectedToolbarButton(area, toolbarSelectedIndex - 1, true); + else if (event.key === 'ArrowRight') moveSelectedToolbarButton(area, toolbarSelectedIndex + 2, true); + else if (event.key === 'Home') moveSelectedToolbarButton(area, 0, true); + else if (event.key === 'End') moveSelectedToolbarButton(area, toolbarDraft[area].length, true); + else if (event.key === 'ArrowUp' && area === 'main') moveSelectedToolbarButton('more', toolbarDraft.more.length, true); + else if (event.key === 'ArrowDown' && area === 'more') moveSelectedToolbarButton('main', toolbarDraft.main.length, true); + } + + function customizeToolbarItem(node: HTMLElement, options: { id: ToolbarButtonId; selected: boolean }) { + const button = node.querySelector('button'); + const update = ({ id, selected }: typeof options) => { + button?.setAttribute('aria-label', toolbarLabels[id]); + button?.setAttribute('aria-pressed', String(selected)); + button?.setAttribute('aria-describedby', toolbarHintId); + button?.setAttribute('aria-keyshortcuts', 'ArrowLeft ArrowRight ArrowUp ArrowDown Home End'); + }; + update(options); + return { update }; + } + + function startToolbarDrag(event: PointerEvent) { + if (!toolbarDraft || event.button !== 0 || !event.isPrimary) return; + const item = (event.target as Element).closest('[data-toolbar-id]'); + const button = item?.querySelector('button'); + if (!item || !button) return; + event.preventDefault(); + event.stopPropagation(); + if (toolbarSaving || toolbarDrag) return; + toolbarSelected = item.dataset.toolbarId as ToolbarButtonId; + button.focus({ preventScroll: true }); + toolbarDrag = { + id: toolbarSelected, pointerId: event.pointerId, button, active: false, + startX: event.clientX, startY: event.clientY, x: event.clientX, y: event.clientY, + }; + // Capture on the stable bar, never an item that a drop can recreate. + toolbarCapture = formattingBar ?? null; + toolbarCapture?.setPointerCapture(event.pointerId); + } + + function trackToolbarDrag(event: PointerEvent) { + const drag = toolbarDrag; + if (!drag || event.pointerId !== drag.pointerId) return; + drag.x = event.clientX; + drag.y = event.clientY; + if (!drag.active && Math.hypot(drag.x - drag.startX, drag.y - drag.startY) < 5) return; + event.preventDefault(); + if (!drag.active) { + drag.active = true; + toolbarDraggedId = drag.id; + // A detached clone is only a visual ghost; Svelte keeps ownership of every real control. + const ghost = drag.button.cloneNode(true) as HTMLButtonElement; + ghost.removeAttribute('id'); + ghost.setAttribute('aria-hidden', 'true'); + ghost.inert = true; + ghost.style.cssText = 'position:fixed;left:0;top:0;z-index:1001;pointer-events:none;margin:0;width:34px;height:34px;background:var(--bg-primary);color:var(--text-primary);border:1px solid var(--accent);box-shadow:var(--shadow-lg);opacity:.95;'; + document.body.appendChild(ghost); + toolbarDragGhost = ghost; + toolbarDragFrame = requestAnimationFrame(updateToolbarDrop); + } + if (toolbarDragGhost) toolbarDragGhost.style.transform = `translate(${drag.x + 12}px, ${drag.y + 12}px)`; + } + + function updateToolbarDrop() { + toolbarDragFrame = 0; + const drag = toolbarDrag; + if (!drag?.active) return; + const zone = document.elementFromPoint(drag.x, drag.y)?.closest('[data-toolbar-area]'); + if (!zone || !formattingBar?.contains(zone)) { + toolbarDrop = null; + } else { + const area = zone.dataset.toolbarArea as ToolbarArea; + const bounds = zone.getBoundingClientRect(); + // Both regions may wrap and scroll. Continue scrolling while the pointer rests at an edge. + if (zone.scrollHeight > zone.clientHeight) { + zone.scrollTop += drag.y < bounds.top + 20 ? -8 : drag.y > bounds.bottom - 20 ? 8 : 0; + } + if (zone.scrollWidth > zone.clientWidth) { + zone.scrollLeft += drag.x < bounds.left + 20 ? -8 : drag.x > bounds.right - 20 ? 8 : 0; + } + const items = Array.from(zone.querySelectorAll('[data-toolbar-id]'), (node, index) => ({ index, rect: node.getBoundingClientRect() })) + .filter(({ rect }) => rect.bottom > bounds.top && rect.top < bounds.bottom && rect.right > bounds.left && rect.left < bounds.right); + if (items.length === 0) { + toolbarDrop = { area, index: 0, left: bounds.left + 8, top: bounds.top + 8, height: Math.max(24, bounds.height - 16) }; + } else { + const nearest = items.reduce((best, item) => Math.abs(drag.y - (item.rect.top + item.rect.height / 2)) < Math.abs(drag.y - (best.rect.top + best.rect.height / 2)) ? item : best); + const row = items.filter(({ rect }) => Math.abs(rect.top - nearest.rect.top) < 3); + const before = row.find(({ rect }) => drag.x < rect.left + rect.width / 2); + const edge = before ?? row[row.length - 1]; + toolbarDrop = { + area, index: edge.index + (before ? 0 : 1), + left: Math.max(bounds.left + 1, Math.min(before ? edge.rect.left - 2 : edge.rect.right + 1, bounds.right - 3)), + top: Math.max(bounds.top, edge.rect.top), height: Math.min(edge.rect.bottom, bounds.bottom) - Math.max(edge.rect.top, bounds.top), + }; + } + } + toolbarDragFrame = requestAnimationFrame(updateToolbarDrop); + } + + function finishToolbarDrag(event: PointerEvent) { + if (!toolbarDrag || event.pointerId !== toolbarDrag.pointerId) return; + if (toolbarDrag.active) { + toolbarDrag.x = event.clientX; + toolbarDrag.y = event.clientY; + if (toolbarDragFrame) cancelAnimationFrame(toolbarDragFrame); + updateToolbarDrop(); + } + const drop = toolbarDrag.active ? toolbarDrop : null; + if (drop && toolbarDraft && !toolbarSaving) { + toolbarDraft = moveToolbarButton(toolbarDraft, toolbarDrag.id, drop.area, drop.index); + toolbarSaveError = null; + } + cancelToolbarDrag(); + if (drop) focusToolbarSelection(); + } + + function cancelToolbarDrag(event?: PointerEvent) { + if (event && event.pointerId !== toolbarDrag?.pointerId) return; + const pointerId = toolbarDrag?.pointerId; + toolbarDrag = null; + toolbarDraggedId = null; + toolbarDrop = null; + if (toolbarDragFrame) cancelAnimationFrame(toolbarDragFrame); + toolbarDragFrame = 0; + toolbarDragGhost?.remove(); + toolbarDragGhost = null; + if (pointerId !== undefined && toolbarCapture?.hasPointerCapture(pointerId)) toolbarCapture.releasePointerCapture(pointerId); + toolbarCapture = null; + } + + function cancelMoreClose() { + if (moreCloseTimer !== null) clearTimeout(moreCloseTimer); + moreCloseTimer = null; + } + + function closeMore() { + cancelMoreClose(); + moreOpen = false; + moreOpenedByHover = false; + } + + function openMore(focus = false) { + cancelMoreClose(); + if (!moreOpen) closeFormattingDropdowns(); + moreOpen = true; + if (focus) void tick().then(() => morePanel?.querySelector('button:not(:disabled)')?.focus({ preventScroll: true })); + } + + function hoverMore(event: PointerEvent) { + if (isMobile || toolbarDraft || event.pointerType !== 'mouse') return; + cancelMoreClose(); + if (!moreOpen) { + moreOpenedByHover = true; + openMore(); + } + } + + function leaveMore(event: PointerEvent) { + if (isMobile || toolbarDraft || event.pointerType !== 'mouse') return; + const target = event.relatedTarget as Node | null; + if (target && (morePanel?.contains(target) || moreButton?.contains(target))) return; + cancelMoreClose(); + moreCloseTimer = setTimeout(() => { + moreCloseTimer = null; + if (!anyDropdownOpen && !morePanel?.contains(document.activeElement)) closeMore(); + }, 160); + } + + function toggleMore(event: MouseEvent) { + event.stopPropagation(); + if (toolbarDraft) return; + if (moreOpen && !moreOpenedByHover) { + closeAllDropdowns(); + } else { + openMore(event.detail === 0); + moreOpenedByHover = false; + } + } + + function preserveFormattingFocus(event: PointerEvent | MouseEvent) { + // Keep the DOM selection and mobile IME in the editor. Native buttons still + // activate on click; keyboard focus and touch scrolling remain available. + if (event.button === 0 && (event.target as Element).closest('button')) event.preventDefault(); + } + + type FormattingPicker = 'insert' | 'heading' | 'text-color' | 'highlight' | 'alignment' | 'table'; + function toggleFormattingPicker(event: MouseEvent, picker: FormattingPicker) { + event.stopPropagation(); + const wasOpen = picker === 'insert' ? insertDropdown : picker === 'heading' ? headingDropdown + : picker === 'text-color' ? colorDropdown : picker === 'highlight' ? highlightDropdown + : picker === 'alignment' ? alignDropdown : tablePickerOpen; + closeFormattingDropdowns(); + const clicked = event.currentTarget as HTMLButtonElement; + formattingTrigger = clicked.closest('.fmt-dropdown') + ? clicked.closest('.fmt-dropdown-wrap')?.querySelector(':scope > button') ?? clicked + : clicked; + if (wasOpen) return; + if (picker === 'insert') insertDropdown = true; + else if (picker === 'heading') headingDropdown = true; + else if (picker === 'text-color') colorDropdown = true; + else if (picker === 'highlight') highlightDropdown = true; + else if (picker === 'alignment') alignDropdown = true; + else tablePickerOpen = true; + if (event.detail === 0) void tick().then(() => formattingBar?.querySelector('.fmt-dropdown button')?.focus({ preventScroll: true })); + } + function handleFormattingBarClick(event: MouseEvent) { - if (!(event.target as Element).closest('.fmt-dropdown')) closeFormattingDropdowns(); + if (!toolbarDraft && (event.target as Element).closest('button')) closeAllDropdowns(); + } + + function handleFormattingEscape(event: KeyboardEvent) { + if (event.key !== 'Escape' || event.isComposing || (!moreOpen && !anyDropdownOpen)) return; + const target = event.target instanceof Element ? event.target : null; + if (target && !formattingBar?.contains(target) + && target.closest('[role="dialog"], [role="menu"], .note-search-bar')) return; + event.preventDefault(); + event.stopPropagation(); + if (toolbarDraft) { + if (!toolbarSaving) endToolbarCustomization(!!formattingBar?.contains(document.activeElement)); + return; + } + const focusInBar = formattingBar?.contains(document.activeElement); + if (anyDropdownOpen) { + const trigger = formattingTrigger; + closeFormattingDropdowns(); + if (focusInBar) trigger?.focus({ preventScroll: true }); + } else { + closeMore(); + if (focusInBar) moreButton?.focus({ preventScroll: true }); + } + } + + function moreKeydown(event: KeyboardEvent) { + if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { + event.preventDefault(); + openMore(true); + moreOpenedByHover = false; + } + } + + // Fixed descendants escape the scrolling button strip/list without moving + // Svelte-owned DOM. Reposition on scrolling, resizing and IME viewport changes. + function positionFormattingPopup(node: HTMLElement, more = false) { + const trigger = more ? moreButton : formattingTrigger; + let frame = 0; + const position = () => { + frame = 0; + if (!trigger || !formattingBar) return; + const vv = window.visualViewport; + const leftEdge = (vv?.offsetLeft ?? 0) + 8; + const topEdge = (vv?.offsetTop ?? 0) + 8; + const rightEdge = leftEdge + (vv?.width ?? window.innerWidth) - 16; + const viewportBottom = topEdge + (vv?.height ?? window.innerHeight) - 16; + const anchor = trigger.isConnected ? trigger.getBoundingClientRect() : formattingBar.getBoundingClientRect(); + const bottom = Math.min(formattingBar.getBoundingClientRect().top - 4, viewportBottom); + node.style.maxWidth = `${Math.max(0, rightEdge - leftEdge)}px`; + node.style.maxHeight = `${Math.max(0, bottom - topEdge)}px`; + node.style.left = `${Math.max(leftEdge, Math.min(more ? anchor.right - node.offsetWidth : anchor.left, rightEdge - node.offsetWidth))}px`; + node.style.top = `${Math.max(topEdge, bottom - node.offsetHeight)}px`; + }; + const schedule = () => { if (!frame) frame = requestAnimationFrame(position); }; + position(); + const resize = new ResizeObserver(schedule); + resize.observe(node); + if (formattingBar) resize.observe(formattingBar); + window.addEventListener('resize', schedule); + document.addEventListener('scroll', schedule, true); + window.visualViewport?.addEventListener('resize', schedule); + window.visualViewport?.addEventListener('scroll', schedule); + return { destroy() { + if (frame) cancelAnimationFrame(frame); + resize.disconnect(); + window.removeEventListener('resize', schedule); + document.removeEventListener('scroll', schedule, true); + window.visualViewport?.removeEventListener('resize', schedule); + window.visualViewport?.removeEventListener('scroll', schedule); + } }; } // ── In-note search functions ── @@ -4481,17 +4884,52 @@ } }); - // Close formatting dropdowns when clicking outside the formatting bar $effect(() => { - if (!anyDropdownOpen) return; - function onClickAway(e: MouseEvent) { - const bar = document.querySelector('.editor-formatting-bar'); - if (bar && !bar.contains(e.target as Node)) { - closeAllDropdowns(); - } + if (!anyDropdownOpen && !moreOpen) return; + function onAway(event: Event) { + if (!toolbarDraft && !formattingBar?.contains(event.target as Node)) closeAllDropdowns(); } - document.addEventListener('mousedown', onClickAway); - return () => document.removeEventListener('mousedown', onClickAway); + document.addEventListener('pointerdown', onAway); + document.addEventListener('focusin', onAway); + window.addEventListener('keydown', handleFormattingEscape, true); + return () => { + document.removeEventListener('pointerdown', onAway); + document.removeEventListener('focusin', onAway); + window.removeEventListener('keydown', handleFormattingEscape, true); + }; + }); + + $effect(() => { + void $activeNotePath; + void $sourceMode; + void $viewerNote; + void $readOnly; + untrack(() => endToolbarCustomization()); + }); + + $effect(() => { + const preference = JSON.stringify($appConfig?.toolbar_layout ?? null); + untrack(() => { + if (toolbarDraft && preference !== toolbarBase && preference !== toolbarPendingPreference) toolbarConflict = true; + }); + }); + + $effect(() => { + if (!toolbarDraft) return; + const blur = () => cancelToolbarDrag(); + window.addEventListener('pointermove', trackToolbarDrag, { passive: false }); + window.addEventListener('pointerup', finishToolbarDrag); + window.addEventListener('pointercancel', cancelToolbarDrag); + window.addEventListener('lostpointercapture', cancelToolbarDrag); + window.addEventListener('blur', blur); + return () => { + window.removeEventListener('pointermove', trackToolbarDrag); + window.removeEventListener('pointerup', finishToolbarDrag); + window.removeEventListener('pointercancel', cancelToolbarDrag); + window.removeEventListener('lostpointercapture', cancelToolbarDrag); + window.removeEventListener('blur', blur); + cancelToolbarDrag(); + }; }); // Count immediately when Info opens or the document/mode changes, but never @@ -6078,6 +6516,17 @@ else unlistenFileChange = fn; }).catch(e => console.error('Failed to listen for note changes:', e)); + let unlistenToolbarLayout: (() => void) | null = null; + listen('toolbar-layout-changed', (event) => { + const preference = JSON.stringify(event.payload); + if (toolbarDraft && preference !== toolbarBase && preference !== toolbarPendingPreference) toolbarConflict = true; + if (!toolbarDraft) closeAllDropdowns(); + appConfig.update(config => config ? { ...config, toolbar_layout: event.payload } : config); + }).then(fn => { + if (editorDisposed) fn(); + else unlistenToolbarLayout = fn; + }).catch(e => console.error('Failed to listen for toolbar changes:', e)); + function handleOpenNote(event: Event) { const path = (event as CustomEvent).detail; if (typeof path === 'string' && path) void navigateToWikiLink(path, ''); @@ -6087,6 +6536,7 @@ onDestroy(() => { void flushSave(); closeAiMenu(); + endToolbarCustomization(); editorDisposed = true; if (editorNavigationToken !== null) cancelNoteNavigation(editorNavigationToken); saves.startSession(); @@ -6098,10 +6548,350 @@ clearTargetReveal(); destroyEditor(); unlistenFileChange?.(); + unlistenToolbarLayout?.(); if (infoPathCopyTimer) clearTimeout(infoPathCopyTimer); }); +{#snippet tableSizePicker()} + +{/snippet} + +{#snippet toolbarControl(id: ToolbarButtonId)} + {#if id === 'insert'} +
+ + {#if insertDropdown} + + {/if} + {#if isMobile && tablePickerOpen} + {@render tableSizePicker()} + {/if} +
+ {:else if id === 'heading'} +
+ + {#if headingDropdown} + + {/if} +
+ {:else if id === 'bold'} + + {:else if id === 'italic'} + + {:else if id === 'underline'} + + {:else if id === 'strike'} + + {:else if id === 'text-color'} +
+ + {#if colorDropdown} + + {/if} +
+ {:else if id === 'link'} + + {:else if id === 'bullet-list'} + + {:else if id === 'ordered-list'} + + {:else if id === 'task-list'} + + {:else if id === 'undo'} + + {:else if id === 'redo'} + + {:else if id === 'inline-code'} + + {:else if id === 'code-block'} + + {:else if id === 'quote'} + + {:else if id === 'details'} + + {:else if id === 'callout'} + + {:else if id === 'table'} +
+ + {#if tablePickerOpen} + {@render tableSizePicker()} + {/if} +
+ {:else if id === 'horizontal-rule'} + + {:else if id === 'highlight'} + {#if isMobile} + + {:else} +
+ + {#if highlightDropdown} + + {/if} +
+ {/if} + {:else if id === 'subscript'} + + {:else if id === 'superscript'} + + {:else if id === 'alignment'} +
+ + {#if alignDropdown} + + {/if} +
+ {:else if id === 'indent'} + + {:else if id === 'outdent'} + + {:else if id === 'date-time'} + + {:else if id === 'ai-actions'} + + {/if} +{/snippet} + +{#snippet editableToolbarControl(id: ToolbarButtonId)} +
+ {@render toolbarControl(id)} +
+{/snippet} + + + @@ -6636,493 +7426,101 @@ {#if editorReady && !$sourceMode && !$viewerNote} -
0 ? `bottom: ${keyboardHeight}px;` : ''}${anyDropdownOpen ? 'overflow: visible;' : ''}` : ''} onclick={handleFormattingBarClick} onkeydown={(e) => { if (e.key === 'Escape') closeFormattingDropdowns(); }}> - {#if isMobile} - - - -
- - {#if insertDropdown} -
- - {#if isAndroid} - - {/if} - - - - - - - - -
- {/if} -
- -
- - -
- - {#if headingDropdown} -
- - - - -
- {/if} -
- -
- - - - - - - -
- - - - -
- - - - - - - - - - -
- - - - -
- - - - -
- - - - - - {#if $appConfig?.ai_provider} -
- - {/if} - - {:else} - - - -
- - {#if insertDropdown} -
- - - - - -
- {/if} -
- -
- - -
- - {#if headingDropdown} -
- - - - - -
- {/if} -
- -
- - - - - - - - -
- - {#if colorDropdown} -
- {#each textColors as color} - - {/each} -
- {/if} -
- -
- - - - -
- - - - - - -
- - - - - -
- - - - - - - - - - - - - - - -
- - {#if tablePickerOpen} -
-
- {#each Array(8) as _, r} - {#each Array(10) as _, c} - - {/each} - {/each} -
-
- {tablePickerHover.rows > 0 ? `${tablePickerHover.rows} x ${tablePickerHover.cols}` : 'Select size'} -
-
- {/if} -
- - - - -
- - -
- - {#if highlightDropdown} -
- {#each highlightColors as color} - - {/each} - -
- {/if} -
- - - - - -
- - -
- - {#if alignDropdown} -
- - - - -
+ Drop buttons here + {/each} + {:else} + {#each formattingGroups as group, index} + {#if index > 0}
{/if} + {#each group as id (id)} + {@render toolbarControl(id)} + {/each} + {/each} {/if}
- -
- - - - - + {#if !isMobile} + + {#if moreOpen} + + {/if} + {#if toolbarDrop} + + {/if} {/if}
{/if} @@ -8272,6 +8670,274 @@ flex-wrap: wrap; } + .editor-formatting-bar.customizing { + flex-wrap: nowrap; + } + + .fmt-main-controls { + display: contents; + } + + .fmt-more-button { + flex-shrink: 0; + } + + .fmt-more-panel { + position: fixed; + z-index: 99; + width: max-content; + display: flex; + flex-direction: column; + gap: 6px; + box-sizing: border-box; + overflow: auto; + overscroll-behavior: contain; + background: var(--bg-primary); + border: 1px solid var(--border-color); + border-radius: 8px; + box-shadow: var(--shadow-lg); + padding: 6px; + } + + .fmt-more-controls { + display: grid; + grid-template-columns: repeat(var(--toolbar-more-columns, 7), 32px); + gap: 2px; + align-content: start; + justify-content: start; + } + + .fmt-customize-entry { + min-height: 30px; + padding: 6px 8px; + border: 0; + border-radius: 4px; + background: none; + color: var(--text-secondary); + text-align: left; + font-size: 12px; + white-space: nowrap; + cursor: pointer; + } + + .fmt-more-controls + .fmt-customize-entry { + border-top: 1px solid var(--border-light); + border-radius: 0 0 4px 4px; + padding-top: 9px; + } + + .fmt-customize-entry:hover { + background: var(--bg-hover); + color: var(--text-primary); + } + + .editor-formatting-bar.customizing { + background: var(--bg-secondary); + gap: 8px; + } + + .customizing .fmt-main-controls, + .fmt-more-panel.customizing .fmt-more-controls { + border: 1px dashed var(--border-color); + border-radius: 6px; + padding: 5px; + min-height: 42px; + box-sizing: border-box; + overflow: auto; + overscroll-behavior: contain; + } + + .customizing .fmt-main-controls { + display: flex; + flex: 1; + min-width: 0; + flex-wrap: wrap; + align-items: center; + gap: 2px; + max-height: 116px; + } + + .fmt-more-panel.customizing { + width: 280px; + padding: 12px; + gap: 8px; + } + + .fmt-more-panel.customizing .fmt-more-controls { + max-height: 152px; + min-height: 58px; + } + + .fmt-area-label { + font-size: 11px; + font-weight: 600; + color: var(--text-tertiary); + flex-shrink: 0; + } + + .fmt-empty-drop { + font-size: 11px; + color: var(--text-tertiary); + padding: 7px 4px; + grid-column: 1 / -1; + line-height: 1.5; + pointer-events: none; + } + + .fmt-control { + flex-shrink: 0; + border-radius: 4px; + touch-action: none; + } + + .fmt-control .fmt-btn { + cursor: grab; + background: none; + color: var(--text-secondary); + } + + .fmt-control.selected { + outline: 2px solid var(--accent); + outline-offset: -1px; + background: var(--accent-light); + } + + .fmt-control.dragging { + opacity: 0.3; + } + + .customizing .drop-target { + border-color: var(--accent); + background: var(--accent-light); + } + + .fmt-drop-indicator { + position: fixed; + width: 3px; + border-radius: 2px; + background: var(--accent); + z-index: 1000; + pointer-events: none; + } + + .fmt-customize-heading strong { + font-size: 13px; + font-weight: 600; + color: var(--text-primary); + } + + .fmt-customize-heading p, + .fmt-customize-hint { + margin: 5px 0 0; + font-size: 11px; + line-height: 1.5; + color: var(--text-tertiary); + } + + .fmt-customize-selection { + border-top: 1px solid var(--border-light); + padding-top: 9px; + } + + .fmt-selected-label { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 8px; + margin-bottom: 7px; + font-size: 11px; + } + + .fmt-selected-label strong { + color: var(--text-primary); + font-weight: 500; + } + + .fmt-selected-label span { + color: var(--text-tertiary); + white-space: nowrap; + } + + .fmt-customize-moves, + .fmt-customize-actions { + display: flex; + gap: 5px; + } + + .fmt-customize-moves button, + .fmt-customize-actions button { + display: flex; + align-items: center; + justify-content: center; + min-width: 28px; + min-height: 28px; + padding: 4px 8px; + border: 1px solid var(--border-color); + border-radius: 5px; + background: var(--bg-primary); + color: var(--text-secondary); + font-size: 11px; + cursor: pointer; + } + + .fmt-customize-moves button:hover:not(:disabled), + .fmt-customize-actions button:hover:not(:disabled) { + background: var(--bg-hover); + } + + .fmt-customize-moves .fmt-move-area { + flex: 1; + } + + .fmt-customize-actions { + border-top: 1px solid var(--border-light); + padding-top: 9px; + } + + .fmt-customize-actions .fmt-customize-reset { + margin-right: auto; + border-color: transparent; + background: none; + } + + .fmt-customize-actions .fmt-customize-done { + background: var(--accent); + color: var(--bg-primary); + border-color: var(--accent); + } + + .fmt-customize-actions .fmt-customize-done:hover:not(:disabled) { + background: var(--accent); + filter: brightness(1.1); + } + + .fmt-more-panel button:disabled { + opacity: 0.45; + cursor: default; + } + + .fmt-customize-entry:focus-visible, + .fmt-customize-moves button:focus-visible, + .fmt-customize-actions button:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 1px; + } + + .fmt-customize-error { + margin: 0; + font-size: 11px; + line-height: 1.5; + color: var(--danger, #e53e3e); + overflow-wrap: anywhere; + } + + + .fmt-btn:focus-visible, + .fmt-dropdown button:focus-visible { + outline: 2px solid var(--accent); + outline-offset: -2px; + } + .fmt-btn { background: none; border: none; @@ -8316,9 +8982,11 @@ } .fmt-dropdown { - position: absolute; - bottom: calc(100% + 4px); - left: 0; + position: fixed; + bottom: auto; + box-sizing: border-box; + overflow: auto; + overscroll-behavior: contain; background: var(--bg-primary); border: 1px solid var(--border-color); border-radius: 8px; @@ -11322,19 +11990,41 @@ z-index: 50; padding: 4px 8px; padding-bottom: calc(4px + env(safe-area-inset-bottom)); - overflow-x: auto; + overflow: visible; flex-wrap: nowrap; - -webkit-overflow-scrolling: touch; - scrollbar-width: none; gap: 1px; background: var(--bg-secondary); border-top: 1px solid var(--border-color); } - .editor-container.mobile .editor-formatting-bar::-webkit-scrollbar { + .editor-container.mobile .fmt-main-controls::-webkit-scrollbar { display: none; } + .editor-container.mobile .fmt-main-controls { + display: flex; + flex: 1; + min-width: 0; + align-items: center; + flex-wrap: nowrap; + gap: 1px; + overflow-x: auto; + scrollbar-width: none; + -webkit-overflow-scrolling: touch; + } + + + .editor-container.mobile .table-picker-grid { + grid-template-columns: repeat(10, 44px); + grid-template-rows: repeat(8, 44px); + } + + .editor-container.mobile .table-picker-dropdown .table-picker-cell { + width: 44px; + height: 44px; + padding: 0; + } + .editor-container.mobile .fmt-btn { min-width: 38px; height: 38px; @@ -11348,14 +12038,7 @@ } .editor-container.mobile .fmt-dropdown { - position: absolute; - bottom: calc(100% + 4px); - left: 0; - right: auto; min-width: 180px; - max-width: calc(100vw - 16px); - max-height: 60vh; - overflow-y: auto; } .editor-container.mobile .fmt-dropdown button { @@ -11365,12 +12048,8 @@ } .editor-container.mobile .insert-dropdown { - position: absolute; - bottom: calc(100% + 4px); - left: 0; - right: auto; + width: max-content; min-width: 200px; - max-width: calc(100vw - 16px); } .editor-container.mobile .shortcuts-hint { diff --git a/src/lib/components/NoteList.svelte b/src/lib/components/NoteList.svelte index e8373ea..c2234cf 100644 --- a/src/lib/components/NoteList.svelte +++ b/src/lib/components/NoteList.svelte @@ -1227,10 +1227,10 @@ {#if !isMobile} {/if} diff --git a/src/lib/editor/toolbar.ts b/src/lib/editor/toolbar.ts new file mode 100644 index 0000000..c53064b --- /dev/null +++ b/src/lib/editor/toolbar.ts @@ -0,0 +1,107 @@ +import type { ToolbarLayout } from '../types'; + +export const toolbarLabels = { + insert: 'Insert', + heading: 'Heading', + bold: 'Bold', + italic: 'Italic', + underline: 'Underline', + strike: 'Strikethrough', + 'text-color': 'Text color', + link: 'Link', + 'bullet-list': 'Bullet list', + 'ordered-list': 'Numbered list', + 'task-list': 'Task list', + undo: 'Undo', + redo: 'Redo', + 'inline-code': 'Inline code', + 'code-block': 'Code block', + quote: 'Quote', + details: 'Collapsible section', + callout: 'Callout', + table: 'Table', + 'horizontal-rule': 'Horizontal rule', + highlight: 'Highlight', + subscript: 'Subscript', + superscript: 'Superscript', + alignment: 'Text alignment', + indent: 'Indent', + outdent: 'Outdent', + 'date-time': 'Date and time', + 'ai-actions': 'AI actions', +} as const; + +export type ToolbarButtonId = keyof typeof toolbarLabels; +export type ToolbarArea = 'main' | 'more'; +export type ResolvedToolbarLayout = Record; + +const desktopGroups: readonly (readonly ToolbarButtonId[])[] = [ + ['insert'], ['heading'], ['bold', 'italic', 'underline', 'strike', 'text-color'], + ['link'], ['bullet-list', 'ordered-list', 'task-list'], ['undo', 'redo'], + ['inline-code', 'code-block', 'quote', 'details', 'callout', 'table', 'horizontal-rule'], + ['highlight', 'subscript', 'superscript'], ['alignment'], ['indent', 'outdent'], +]; +const mobileGroups: readonly (readonly ToolbarButtonId[])[] = [ + ['insert'], ['heading'], ['bold', 'italic', 'underline', 'strike'], ['link'], + ['bullet-list', 'ordered-list', 'task-list', 'indent', 'outdent'], + ['highlight'], ['date-time'], ['undo', 'redo'], ['ai-actions'], +]; + +export function toolbarGroups(mobile: boolean, hasAi: boolean): ToolbarButtonId[][] { + return (mobile ? mobileGroups : desktopGroups) + .map((group) => group.filter((id) => id !== 'ai-actions' || hasAi)) + .filter((group) => group.length > 0); +} + +export function resolveToolbarLayout( + layout: ToolbarLayout | null | undefined, mobile: boolean, hasAi: boolean, +): ResolvedToolbarLayout { + const available = toolbarGroups(mobile, hasAi).flat(); + if (mobile || !layout) return { main: available, more: [] }; + const allowed = new Set(available); + const seen = new Set(); + const take = (ids: readonly string[]) => ids.filter((id): id is ToolbarButtonId => { + if (!allowed.has(id) || seen.has(id)) return false; + seen.add(id); + return true; + }); + const main = take(layout.main); + const more = take(layout.more); + // Newly added controls stay reachable without changing the user's saved order. + main.push(...available.filter((id) => !seen.has(id))); + return { main, more }; +} + +export function groupToolbarButtons(ids: readonly ToolbarButtonId[], mobile: boolean): ToolbarButtonId[][] { + const defaults = mobile ? mobileGroups : desktopGroups; + const groups: ToolbarButtonId[][] = []; + let previous = -1; + for (const id of ids) { + const group = defaults.findIndex((items) => items.includes(id)); + if (group !== previous || groups.length === 0) groups.push([]); + groups[groups.length - 1].push(id); + previous = group; + } + return groups; +} + +/** Index is an insertion gap in the destination list before removing the dragged item. */ +export function moveToolbarButton( + layout: ResolvedToolbarLayout, id: ToolbarButtonId, area: ToolbarArea, index: number, +): ResolvedToolbarLayout { + const from = layout.main.includes(id) ? 'main' : 'more'; + const oldIndex = layout[from].indexOf(id); + if (oldIndex < 0) return layout; + const gap = Math.max(0, Math.min(index, layout[area].length)); + const target = gap - (from === area && oldIndex < gap ? 1 : 0); + if (from === area && target === oldIndex) return layout; + const next = { main: layout.main.filter((item) => item !== id), more: layout.more.filter((item) => item !== id) }; + next[area].splice(target, 0, id); + return next; +} + +export function toolbarLayoutPreference(layout: ResolvedToolbarLayout): ToolbarLayout | null { + const defaults = desktopGroups.flat(); + return layout.more.length === 0 && layout.main.length === defaults.length + && layout.main.every((id, index) => id === defaults[index]) ? null : layout; +} diff --git a/src/lib/types.ts b/src/lib/types.ts index f81753f..89f032f 100644 --- a/src/lib/types.ts +++ b/src/lib/types.ts @@ -93,6 +93,11 @@ export interface CustomTheme { export type StartupView = "all" | "quickaccess" | "tasks" | "daily"; +export interface ToolbarLayout { + main: string[]; + more: string[]; +} + export interface AppConfig { vaults: VaultConfig[]; active_vault: string | null; @@ -103,6 +108,7 @@ export interface AppConfig { accent_color: string | null; font_size: number | null; scroll_to_change_font_size: boolean; + toolbar_layout: ToolbarLayout | null; font_family: string | null; line_height: number | null; ui_scale: number | null; diff --git a/tests/toolbar-layout.test.mjs b/tests/toolbar-layout.test.mjs new file mode 100644 index 0000000..ca52de0 --- /dev/null +++ b/tests/toolbar-layout.test.mjs @@ -0,0 +1,48 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { moveToolbarButton, resolveToolbarLayout } from '../src/lib/editor/toolbar.ts'; + +const layout = () => Object.freeze({ + main: Object.freeze(['bold', 'italic', 'link']), + more: Object.freeze(['table', 'quote']), +}); + +test('moving a button between toolbar and More preserves the other buttons and their order', () => { + const original = layout(); + assert.deepEqual(moveToolbarButton(original, 'italic', 'more', 1), { + main: ['bold', 'link'], more: ['table', 'italic', 'quote'], + }); + assert.deepEqual(moveToolbarButton(original, 'quote', 'main', 1), { + main: ['bold', 'quote', 'italic', 'link'], more: ['table'], + }); +}); + +test('reordering uses insertion gaps before removing the dragged button', () => { + const original = layout(); + assert.deepEqual(moveToolbarButton(original, 'bold', 'main', 3).main, ['italic', 'link', 'bold']); + assert.deepEqual(moveToolbarButton(original, 'link', 'main', 0).main, ['link', 'bold', 'italic']); + assert.deepEqual(moveToolbarButton(original, 'table', 'more', 2).more, ['quote', 'table']); +}); + +test('self drops, boundary moves and stale dragged buttons leave the layout unchanged', () => { + const original = layout(); + assert.equal(moveToolbarButton(original, 'italic', 'main', 1), original); + assert.equal(moveToolbarButton(original, 'italic', 'main', 2), original); + assert.equal(moveToolbarButton(original, 'bold', 'main', -1), original); + assert.equal(moveToolbarButton(original, 'link', 'main', 4), original); + assert.equal(moveToolbarButton(original, 'heading', 'more', 0), original); +}); + +test('saved layouts keep user order without duplicate or unavailable buttons and expose newly available controls', () => { + const saved = Object.freeze({ + main: Object.freeze(['table', 'bold', 'bold', 'removed-command']), + more: Object.freeze(['bold', 'italic', 'italic']), + }); + const resolved = resolveToolbarLayout(saved, false, false); + assert.deepEqual(resolved.main.slice(0, 2), ['table', 'bold']); + assert.deepEqual(resolved.more, ['italic']); + assert.ok(resolved.main.includes('link')); + assert.equal(resolved.main.includes('removed-command'), false); + const buttons = [...resolved.main, ...resolved.more]; + assert.equal(new Set(buttons).size, buttons.length); +});