Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(ui): toolbar primitive, use in md, channel, canvas, better md edit toolbar (#6360)

Seamusbecbdd235191
diff --git a/apps/web/src/components/ui/components/Button.docs.tsx b/apps/web/src/components/ui/components/Button.docs.tsx
index 48b3966352..8001110b30 100644
--- a/apps/web/src/components/ui/components/Button.docs.tsx
+++ b/apps/web/src/components/ui/components/Button.docs.tsx
@@ -2,7 +2,7 @@ import { defineDoc } from '@app/features/ui-gallery/types';
import ArrowRightIcon from '@phosphor/arrow-right.svg';
import PlusIcon from '@phosphor/plus.svg';
import TrashIcon from '@phosphor/trash.svg';
-import { For } from 'solid-js';
+import { For, Show } from 'solid-js';
import { Button, type ButtonVariant } from './Button';
import { ButtonGroup } from './ButtonGroup';
@@ -80,6 +80,53 @@ function IconOnlyDemo() {
}
// #endregion
+// #region demo:size-compositions
+function SizeCompositionsDemo() {
+ const sizes = [
+ { size: 'xs', iconSize: 'icon-xs' },
+ { size: 'sm', iconSize: 'icon-sm' },
+ { size: 'md', iconSize: 'icon-md' },
+ { size: 'lg', iconSize: 'icon-lg' },
+ { size: 'xl', iconSize: undefined },
+ ] as const;
+
+ return (
+ <div class="flex w-full flex-col gap-3">
+ <For each={sizes}>
+ {({ size, iconSize }) => (
+ <div class="flex items-center gap-3">
+ <span class="w-8 shrink-0 font-mono text-xs text-ink-subtle">
+ {size}
+ </span>
+ <Button variant="outline" size={size} square label="Add item">
+ <PlusIcon />
+ </Button>
+ <Button variant="outline" size={size}>
+ Button
+ </Button>
+ <Button variant="outline" size={size}>
+ <PlusIcon />
+ With icon
+ </Button>
+ <Show when={iconSize}>
+ {(resolvedIconSize) => (
+ <Button
+ variant="outline"
+ size={resolvedIconSize()}
+ label={resolvedIconSize()}
+ >
+ <PlusIcon />
+ </Button>
+ )}
+ </Show>
+ </div>
+ )}
+ </For>
+ </div>
+ );
+}
+// #endregion
+
// #region demo:group
function GroupDemo() {
return (
@@ -153,6 +200,14 @@ export default defineDoc({
'Use an `icon-*` size for square buttons. `label` is required — it names the button for screen readers and becomes its tooltip.',
render: IconOnlyDemo,
},
+ {
+ id: 'size-compositions',
+ title: 'Compositions by size',
+ description:
+ 'Square regular-size, text-only, text-with-icon, and matching dedicated `icon-*` buttons shown together for direct comparison.',
+ render: SizeCompositionsDemo,
+ fill: true,
+ },
{
id: 'group',
title: 'Button group',
diff --git a/apps/web/src/components/ui/components/Button.tsx b/apps/web/src/components/ui/components/Button.tsx
index 35b7451e4e..4545f28322 100644
--- a/apps/web/src/components/ui/components/Button.tsx
+++ b/apps/web/src/components/ui/components/Button.tsx
@@ -24,7 +24,7 @@ const BUTTON_TOUCH_STYLES =
export const buttonVariants = createVariants(
cn(
'relative inline-flex shrink-0 items-center justify-center whitespace-nowrap text-sm',
- 'rounded-md border-1 border-transparent font-medium outline-none select-none transition-colors',
+ 'rounded-md border-1 border-transparent font-medium outline-none select-none transition-colors [&_*]:select-none',
'data-disabled:cursor-not-allowed data-disabled:opacity-30',
'[&_svg]:pointer-events-none [&_svg]:shrink-0'
),
@@ -45,17 +45,17 @@ export const buttonVariants = createVariants(
},
size: {
xs: "h-5 gap-1 px-1 text-xs [&>svg:not([class*='size-'])]:size-3",
- 'icon-xs': "size-5 p-0.5 [&>svg:not([class*='size-'])]:size-4",
+ 'icon-xs': "size-5 p-0.5 [&>svg:not([class*='size-'])]:size-3",
sm: CONTROL_SIZE_VARIANTS.sm,
md: CONTROL_SIZE_VARIANTS.md,
lg: `${CONTROL_SIZE_VARIANTS.lg} rounded-lg`,
xl: "h-12 gap-2 px-4 text-base rounded-lg [&>svg:not([class*='size-'])]:size-5",
'icon-lg':
- "size-11 aspect-square p-2 [&>svg:not([class*='size-'])]:size-7",
+ "size-9 aspect-square p-2 [&>svg:not([class*='size-'])]:size-5",
'icon-md':
- "size-9 aspect-square p-1.5 [&>svg:not([class*='size-'])]:size-6",
+ "size-8 aspect-square p-1.5 [&>svg:not([class*='size-'])]:size-4",
'icon-sm':
- "size-6 aspect-square p-1 [&>svg:not([class*='size-'])]:size-4",
+ "size-6 aspect-square p-1 [&>svg:not([class*='size-'])]:size-3.5",
},
},
{
diff --git a/apps/web/src/components/ui/components/ButtonGroup.tsx b/apps/web/src/components/ui/components/ButtonGroup.tsx
index bdd3ff80db..4b09c16037 100644
--- a/apps/web/src/components/ui/components/ButtonGroup.tsx
+++ b/apps/web/src/components/ui/components/ButtonGroup.tsx
@@ -1,5 +1,6 @@
import { createContext, type JSX, useContext } from 'solid-js';
import { cn } from '../utils/classname';
+import { createVariants } from '../utils/variants';
import type { ButtonSize, ButtonVariant } from './Button';
import { Layer } from './Layer';
@@ -26,73 +27,80 @@ type ButtonGroupProps = {
children?: JSX.Element;
};
-const groupVariantStyles: Record<ButtonVariant, string> = {
- danger: 'border border-failure/50 ',
- outline: 'border border-edge-muted ',
- accent: 'border border-accent ',
- success: 'border border-success ',
- ghost: ' ',
- strong: 'border border-transparent',
- cta: 'border border-transparent ',
-};
-
-const dividerVariantStyles: Record<ButtonVariant, string> = {
- danger: 'bg-failure/50',
- outline: 'bg-edge-muted',
- accent: 'bg-accent',
- success: 'bg-success',
- ghost: 'bg-edge-muted',
- strong: 'bg-surface-4/50',
- cta: 'bg-surface/50',
-};
-
-/* explicit cross-axis size so the group's outer box matches a standalone
- Button of the same size (border-box absorbs the 1px outer border) */
-const groupHorizontalSize: Record<ButtonSize, string> = {
- xs: '',
- 'icon-xs': 'h-5',
- xl: 'h-12',
- lg: '',
- md: '',
- sm: 'h-6',
- 'icon-lg': 'h-11',
- 'icon-md': 'h-9',
- 'icon-sm': 'h-6',
-};
-
-const groupVerticalSize: Record<ButtonSize, string> = {
- xs: '',
- 'icon-xs': 'w-5',
- xl: '',
- lg: '',
- md: '',
- sm: '',
- 'icon-lg': 'w-11',
- 'icon-md': 'w-9',
- 'icon-sm': 'w-6',
-};
+// Focus ring painted on the group frame when a contained input-group control
+// is focused; the borderless `ghost` frame opts out.
+const groupFocusRing =
+ 'has-[[data-slot=input-group-control]:focus-visible]:border-[color-mix(in_oklch,var(--color-edge)_80%,var(--color-ink))] has-[[data-slot=input-group-control]:focus-visible]:ring-2 has-[[data-slot=input-group-control]:focus-visible]:ring-edge-muted';
+
+/** Canonical classes for the button-group frame. */
+export const buttonGroupVariants = createVariants(
+ cn(
+ 'inline-flex items-center justify-center overflow-hidden',
+ 'data-[orientation=horizontal]:flex-row',
+ 'data-[orientation=vertical]:flex-col',
+ // strip per-button rounding + borders so the group owns the frame
+ '**:data-button:rounded-none **:data-button:border-0'
+ ),
+ {
+ variant: {
+ danger: cn('border-1 border-failure/50', groupFocusRing),
+ outline: cn('border-1 border-edge-muted', groupFocusRing),
+ accent: cn('border-1 border-accent', groupFocusRing),
+ success: cn('border-1 border-success', groupFocusRing),
+ ghost: '',
+ strong: cn('border-1 border-transparent', groupFocusRing),
+ cta: cn('border-1 border-transparent', groupFocusRing),
+ },
+ // Explicit cross-axis size so the frame matches a standalone Button of the
+ // same size (border-box absorbs the 1px frame); radius tracks size too.
+ size: {
+ xs: 'rounded-md',
+ sm: 'rounded-md data-[orientation=horizontal]:h-6',
+ md: 'rounded-md',
+ lg: 'rounded-lg',
+ xl: 'rounded-lg data-[orientation=horizontal]:h-12',
+ 'icon-xs':
+ 'rounded-md data-[orientation=horizontal]:h-5 data-[orientation=vertical]:w-5',
+ 'icon-sm':
+ 'rounded-md data-[orientation=horizontal]:h-6 data-[orientation=vertical]:w-6',
+ 'icon-md':
+ 'rounded-md data-[orientation=horizontal]:h-8 data-[orientation=vertical]:w-8',
+ 'icon-lg':
+ 'rounded-md data-[orientation=horizontal]:h-9 data-[orientation=vertical]:w-9',
+ },
+ },
+ {
+ variant: 'ghost',
+ size: 'md',
+ }
+);
-const groupRadius: Record<ButtonSize, string> = {
- xs: 'rounded-md',
- 'icon-xs': 'rounded-md',
- sm: 'rounded-md',
- 'icon-sm': 'rounded-md',
- md: 'rounded-md',
- 'icon-md': 'rounded-md',
- lg: 'rounded-lg',
- 'icon-lg': 'rounded-md',
- xl: 'rounded-lg',
-};
+/** Divider frame classes; `variant` picks the rule color. */
+export const buttonGroupDividerVariants = createVariants(
+ cn(
+ 'shrink-0 self-stretch',
+ 'data-[orientation=horizontal]:w-px',
+ 'data-[orientation=vertical]:h-px'
+ ),
+ {
+ variant: {
+ danger: 'bg-failure/50',
+ outline: 'bg-edge-muted',
+ accent: 'bg-accent',
+ success: 'bg-success',
+ ghost: 'bg-edge-muted',
+ strong: 'bg-surface-4/50',
+ cta: 'bg-surface/50',
+ },
+ },
+ {
+ variant: 'outline',
+ }
+);
export const ButtonGroup = (props: ButtonGroupProps) => {
const orientation = () => props.orientation ?? 'horizontal';
- const variant = () => props.variant ?? 'ghost';
const size = () => props.size ?? 'md';
- const sizeClass = () => {
- return orientation() === 'horizontal'
- ? groupHorizontalSize[size()]
- : groupVerticalSize[size()];
- };
const ctx: ButtonGroupContextValue = {
get variant() {
@@ -114,17 +122,7 @@ export const ButtonGroup = (props: ButtonGroupProps) => {
data-orientation={orientation()}
data-size={size()}
class={cn(
- 'data-[orientation=horizontal]:flex-row items-center',
- 'data-[orientation=vertical]:flex-col justify-center',
- 'inline-flex overflow-hidden',
- /* strip per-button rounding + borders so the group owns the frame */
- '**:data-button:rounded-none',
- '**:data-button:border-0',
- groupVariantStyles[variant()],
- variant() !== 'ghost' &&
- 'has-[[data-slot=input-group-control]:focus-visible]:border-[color-mix(in_oklch,var(--color-edge)_80%,var(--color-ink))] has-[[data-slot=input-group-control]:focus-visible]:ring-2 has-[[data-slot=input-group-control]:focus-visible]:ring-edge-muted',
- groupRadius[size()],
- sizeClass(),
+ buttonGroupVariants({ variant: props.variant, size: props.size }),
props.class
)}
role="group"
@@ -141,17 +139,13 @@ type DividerProps = { class?: string };
const Divider = (props: DividerProps) => {
const group = useButtonGroupContext();
const orientation = () => group?.orientation ?? 'horizontal';
- const variant = () => group?.variant ?? 'outline';
return (
<div
role="separator"
aria-orientation={orientation()}
data-orientation={orientation()}
class={cn(
- 'shrink-0 self-stretch',
- 'data-[orientation=horizontal]:w-px',
- 'data-[orientation=vertical]:h-px',
- dividerVariantStyles[variant()],
+ buttonGroupDividerVariants({ variant: group?.variant }),
props.class
)}
/>
diff --git a/apps/web/src/components/ui/components/Dropdown.tsx b/apps/web/src/components/ui/components/Dropdown.tsx
index 3a7886c63e..7d1096c3db 100644
--- a/apps/web/src/components/ui/components/Dropdown.tsx
+++ b/apps/web/src/components/ui/components/Dropdown.tsx
@@ -76,8 +76,10 @@ export type DropdownGroupProps = ComponentProps<
export type DropdownItemProps = ComponentProps<typeof KobalteDropdownMenu.Item>;
export type DropdownSubProps = ComponentProps<typeof KobalteDropdownMenu.Sub>;
+// Text size is inherited from `Dropdown.Content` (defaults to `text-sm`) so a
+// menu can be resized by passing a `text-*` class to the content.
const ROW_CLASS =
- 'group rounded-lg w-full flex items-center gap-1.5 p-1.5 px-2 text-left font-normal text-sm cursor-default outline-none data-highlighted:bg-ink/5 data-disabled:opacity-50 data-disabled:cursor-not-allowed';
+ 'group rounded-lg w-full flex items-center gap-1.5 p-1.5 px-2 text-left font-normal cursor-default outline-none data-highlighted:bg-ink/5 data-disabled:opacity-50 data-disabled:cursor-not-allowed';
function resolvePortalMount(
searchRef: HTMLElement | undefined,
@@ -202,7 +204,7 @@ function DropdownContent(props: DropdownContentProps) {
>
<KobalteDropdownMenu.Content
class={cn(
- 'rounded-xl size-auto z-action-menu menu-open-animation shadow-menu bg-menu',
+ 'rounded-xl size-auto z-action-menu menu-open-animation shadow-menu bg-menu text-sm',
local.class
)}
depth={local.depth ?? 2}
@@ -244,7 +246,7 @@ function DropdownSubContent(props: DropdownSubContentProps) {
>
<KobalteDropdownMenu.SubContent
class={cn(
- 'rounded-xl size-auto z-action-menu menu-open-animation bg-menu [--color-surface:var(--color-menu)]',
+ 'rounded-xl size-auto z-action-menu menu-open-animation bg-menu text-sm [--color-surface:var(--color-menu)]',
local.class
)}
depth={local.depth ?? 2}
diff --git a/apps/web/src/components/ui/components/Toolbar.docs.tsx b/apps/web/src/components/ui/components/Toolbar.docs.tsx
new file mode 100644
index 0000000000..ba499e9215
--- /dev/null
+++ b/apps/web/src/components/ui/components/Toolbar.docs.tsx
@@ -0,0 +1,96 @@
+import { defineDoc } from '@app/features/ui-gallery/types';
+import ArrowCounterClockwiseIcon from '@phosphor/arrow-counter-clockwise.svg';
+import CopyIcon from '@phosphor/copy.svg';
+import LinkIcon from '@phosphor/link.svg';
+import ZoomOutIcon from '@phosphor/magnifying-glass-minus.svg';
+import ZoomInIcon from '@phosphor/magnifying-glass-plus.svg';
+import TrashIcon from '@phosphor/trash.svg';
+import { createSignal } from 'solid-js';
+import { Toolbar } from './Toolbar';
+
+// #region demo:basic
+function BasicDemo() {
+ return (
+ <Toolbar size="icon-sm">
+ <Toolbar.Group>
+ <Toolbar.Button label="Undo">
+ <ArrowCounterClockwiseIcon />
+ </Toolbar.Button>
+ </Toolbar.Group>
+ <Toolbar.Divider />
+ <Toolbar.Group>
+ <Toolbar.Button label="Copy">
+ <CopyIcon />
+ </Toolbar.Button>
+ <Toolbar.Button label="Copy link">
+ <LinkIcon />
+ </Toolbar.Button>
+ </Toolbar.Group>
+ <Toolbar.Divider />
+ <Toolbar.Button label="Delete" class="text-failure-ink">
+ <TrashIcon />
+ </Toolbar.Button>
+ </Toolbar>
+ );
+}
+// #endregion
+
+// #region demo:medium
+function MediumDemo() {
+ const [zoom, setZoom] = createSignal(100);
+
+ return (
+ <Toolbar size="md">
+ <Toolbar.Button onClick={() => setZoom(100)}>
+ Fit to screen
+ </Toolbar.Button>
+ <Toolbar.Divider />
+ <Toolbar.Group>
+ <Toolbar.Button
+ size="icon-md"
+ label="Zoom out"
+ onClick={() => setZoom((value) => Math.max(25, value - 25))}
+ >
+ <ZoomOutIcon />
+ </Toolbar.Button>
+ <Toolbar.Button class="w-14 tabular-nums" onClick={() => setZoom(100)}>
+ {zoom()}%
+ </Toolbar.Button>
+ <Toolbar.Button
+ size="icon-md"
+ label="Zoom in"
+ onClick={() => setZoom((value) => Math.min(200, value + 25))}
+ >
+ <ZoomInIcon />
+ </Toolbar.Button>
+ </Toolbar.Group>
+ </Toolbar>
+ );
+}
+// #endregion
+
+export default defineDoc({
+ name: 'Toolbar',
+ category: 'Actions',
+ description:
+ 'A floating surface for compact actions. It owns the frame and shares button size and variant defaults with its children.',
+ status: 'stable',
+ exports: ['Toolbar'],
+ import: "import { Toolbar } from '@ui';",
+ demos: [
+ {
+ id: 'basic',
+ title: 'Basic',
+ description:
+ 'Group related buttons and separate distinct action sets with `Toolbar.Divider`.',
+ render: BasicDemo,
+ },
+ {
+ id: 'medium',
+ title: 'Medium with text',
+ description:
+ 'The `md` size supports text actions and compact widgets alongside icon controls.',
+ render: MediumDemo,
+ },
+ ],
+});
diff --git a/apps/web/src/components/ui/components/Toolbar.tsx b/apps/web/src/components/ui/components/Toolbar.tsx
new file mode 100644
index 0000000000..691cbfb93f
--- /dev/null
+++ b/apps/web/src/components/ui/components/Toolbar.tsx
@@ -0,0 +1,166 @@
+import { createContext, type JSX, splitProps, useContext } from 'solid-js';
+import { cn } from '../utils/classname';
+import {
+ Button,
+ type ButtonProps,
+ type ButtonSize,
+ type ButtonVariant,
+} from './Button';
+import { Layer } from './Layer';
+
+type ToolbarOrientation = 'horizontal' | 'vertical';
+
+type ToolbarContextValue = {
+ size: ButtonSize;
+ variant: ButtonVariant;
+ orientation: ToolbarOrientation;
+};
+
+const ToolbarContext = createContext<ToolbarContextValue>();
+
+const useToolbarContext = () => useContext(ToolbarContext);
+
+export type ToolbarProps = Omit<JSX.HTMLAttributes<HTMLDivElement>, 'style'> & {
+ depth?: 0 | 1 | 2 | 3 | 4;
+ orientation?: ToolbarOrientation;
+ /** Default size for `Toolbar.Button` children. Defaults to `md`. */
+ size?: ButtonSize;
+ /** Default variant for `Toolbar.Button` children. Defaults to `ghost`. */
+ variant?: ButtonVariant;
+ style?: JSX.CSSProperties;
+};
+
+/**
+ * An opinionated floating bar of controls. Owns its surface chrome
+ * (`rounded-xl`, padding, border, background, shadow) and sets the default
+ * size/variant for its `Toolbar.Button` children, so callers compose controls
+ * without restyling them. Pair with a positioning wrapper (e.g.
+ * `PopupPositioner`) when it needs to float against an anchor.
+ *
+ * @do Cluster related controls with `Toolbar.Group` and separate distinct
+ * action sets with `Toolbar.Divider`.
+ * @do Set shared button size and variant on the Toolbar root.
+ * @dont Do not recreate the toolbar's background, border, padding, or shadow
+ * at the call site.
+ */
+export function Toolbar(props: ToolbarProps) {
+ const [local, rest] = splitProps(props, [
+ 'children',
+ 'class',
+ 'depth',
+ 'orientation',
+ 'size',
+ 'variant',
+ ]);
+
+ const ctx: ToolbarContextValue = {
+ get size() {
+ return local.size ?? 'md';
+ },
+ get variant() {
+ return local.variant ?? 'ghost';
+ },
+ get orientation() {
+ return local.orientation ?? 'horizontal';
+ },
+ };
+
+ return (
+ <ToolbarContext.Provider value={ctx}>
+ <Layer depth={local.depth ?? 2}>
+ <div
+ data-slot="toolbar"
+ data-orientation={ctx.orientation}
+ role="toolbar"
+ aria-orientation={ctx.orientation}
+ class={cn(
+ 'inline-flex items-center gap-1 rounded-xl border border-edge bg-surface p-1.5 shadow-lg',
+ 'data-[orientation=vertical]:flex-col data-[orientation=vertical]:items-stretch',
+ local.class
+ )}
+ {...rest}
+ >
+ {local.children}
+ </div>
+ </Layer>
+ </ToolbarContext.Provider>
+ );
+}
+
+export type ToolbarButtonProps = ButtonProps;
+
+/** A `Button` that inherits the toolbar's default size and variant. */
+function ToolbarButton(props: ToolbarButtonProps) {
+ const ctx = useToolbarContext();
+ const [local, rest] = splitProps(props, ['size', 'variant']);
+
+ return (
+ <Button
+ size={local.size ?? ctx?.size ?? 'md'}
+ variant={local.variant ?? ctx?.variant ?? 'ghost'}
+ {...rest}
+ />
+ );
+}
+
+export type ToolbarGroupProps = {
+ children?: JSX.Element;
+ class?: string;
+};
+
+/** Clusters related controls with tighter spacing inside a toolbar. */
+function ToolbarGroup(props: ToolbarGroupProps) {
+ const ctx = useToolbarContext();
+ const orientation = () => ctx?.orientation ?? 'horizontal';
+
+ return (
+ <div
+ role="group"
+ data-slot="toolbar-group"
+ data-orientation={orientation()}
+ class={cn(
+ 'inline-flex items-center gap-0.5',
+ 'data-[orientation=vertical]:flex-col data-[orientation=vertical]:items-stretch',
+ props.class
+ )}
+ >
+ {props.children}
+ </div>
+ );
+}
+
+export type ToolbarDividerProps = {
+ class?: string;
+};
+
+/** A separator between toolbar clusters, matched to the toolbar orientation. */
+function ToolbarDivider(props: ToolbarDividerProps) {
+ const ctx = useToolbarContext();
+ const orientation = () => ctx?.orientation ?? 'horizontal';
+
+ return (
+ <div
+ role="separator"
+ aria-orientation={
+ orientation() === 'horizontal' ? 'vertical' : 'horizontal'
+ }
+ data-orientation={orientation()}
+ class={cn(
+ 'shrink-0 self-stretch bg-edge-muted',
+ 'data-[orientation=horizontal]:mx-0.5 data-[orientation=horizontal]:my-1 data-[orientation=horizontal]:w-px',
+ 'data-[orientation=vertical]:my-0.5 data-[orientation=vertical]:mx-1 data-[orientation=vertical]:h-px',
+ props.class
+ )}
+ />
+ );
+}
+
+/** Pushes subsequent controls to the far end of the toolbar. */
+function ToolbarSpacer() {
+ return <div data-slot="toolbar-spacer" class="grow" />;
+}
+
+Toolbar.Button = ToolbarButton;
+Toolbar.Group = ToolbarGroup;
+Toolbar.Divider = ToolbarDivider;
+Toolbar.Spacer = ToolbarSpacer;
diff --git a/apps/web/src/components/ui/components/Tooltip.tsx b/apps/web/src/components/ui/components/Tooltip.tsx
index cfa2c0e440..6f555d5597 100644
--- a/apps/web/src/components/ui/components/Tooltip.tsx
+++ b/apps/web/src/components/ui/components/Tooltip.tsx
@@ -22,6 +22,18 @@ type TooltipProps = ParentProps<{
disabled?: boolean;
}>;
+export type TooltipClassOptions = {
+ class?: string;
+};
+
+/** Canonical classes for tooltip content and tooltip-like static hints. */
+export function tooltipClasses(options: TooltipClassOptions = {}): string {
+ return cn(
+ 'flex items-center justify-center rounded-lg bg-tooltip p-2 text-xs text-ink-muted wrap-break-word',
+ options.class
+ );
+}
+
/**
* @example
* <Tooltip label="" hotkey={}>
@@ -121,10 +133,7 @@ export function Tooltip(props: TooltipProps) {
<Show when={open()}>
<KobalteTooltip.Portal>
<KobalteTooltip.Content class="z-tool-tip max-w-[calc(100vw-32px)]">
- <Surface
- class="flex items-center justify-center p-2 text-ink-muted text-xs wrap-break-word bg-tooltip"
- depth={3}
- >
+ <Surface class={tooltipClasses()} depth={3}>
<div class="flex flex-row items-center gap-2">
<div class="text-xs">{props.label}</div>
<Show when={hasHotkey()}>
diff --git a/apps/web/src/components/ui/index.ts b/apps/web/src/components/ui/index.ts
index 5955cf406b..aca0c91459 100644
--- a/apps/web/src/components/ui/index.ts
+++ b/apps/web/src/components/ui/index.ts
@@ -153,7 +153,15 @@ export type {
export { TextField } from './components/TextField';
export type { ToggleSwitchProps } from './components/ToggleSwitch';
export { ToggleSwitch } from './components/ToggleSwitch';
-export { Tooltip } from './components/Tooltip';
+export type {
+ ToolbarButtonProps,
+ ToolbarDividerProps,
+ ToolbarGroupProps,
+ ToolbarProps,
+} from './components/Toolbar';
+export { Toolbar } from './components/Toolbar';
+export type { TooltipClassOptions } from './components/Tooltip';
+export { Tooltip, tooltipClasses } from './components/Tooltip';
export { cn } from './utils/classname';
export type { CtrlJKMenuNavigationOptions } from './utils/menuKeyboardNavigation';
export {
diff --git a/apps/web/src/features/block-canvas/component/FileSelector.tsx b/apps/web/src/features/block-canvas/component/FileSelector.tsx
index 678dee7801..3ffae9aeeb 100644
--- a/apps/web/src/features/block-canvas/component/FileSelector.tsx
+++ b/apps/web/src/features/block-canvas/component/FileSelector.tsx
@@ -93,7 +93,7 @@ export function FileSelector() {
<Dropdown open={fileSelectorOpen()} onOpenChange={setFileSelectorOpen}>
<Dropdown.Trigger
variant="ghost"
- size="icon-md"
+ size="icon-sm"
label="File"
tabIndex={-1}
>
diff --git a/apps/web/src/features/block-canvas/component/MediaSelector.tsx b/apps/web/src/features/block-canvas/component/MediaSelector.tsx
index c86fe73776..da9d408c17 100644
--- a/apps/web/src/features/block-canvas/component/MediaSelector.tsx
+++ b/apps/web/src/features/block-canvas/component/MediaSelector.tsx
@@ -132,7 +132,7 @@ export function MediaSelector() {
<Dropdown open={imageSelectorOpen()} onOpenChange={setImageSelectorOpen}>
<Dropdown.Trigger
variant="ghost"
- size="icon-md"
+ size="icon-sm"
label="Media"
tabIndex={-1}
>
diff --git a/apps/web/src/features/block-canvas/component/ToolBar.tsx b/apps/web/src/features/block-canvas/component/ToolBar.tsx
index 0222b2f64c..ff095a3a06 100644
--- a/apps/web/src/features/block-canvas/component/ToolBar.tsx
+++ b/apps/web/src/features/block-canvas/component/ToolBar.tsx
@@ -24,7 +24,7 @@ import ZoomIn from '@phosphor/magnifying-glass-plus.svg';
import PencilSimple from '@phosphor/pencil-simple.svg';
import Rectangle from '@phosphor/rectangle.svg';
import Text from '@phosphor/text-t.svg';
-import { Button, cn, Dropdown, Hotkey } from '@ui';
+import { Button, ButtonGroup, Dropdown, Hotkey, Toolbar } from '@ui';
import { createSignal, Show } from 'solid-js';
import { Dynamic } from 'solid-js/web';
import { Tools } from '../constants';
@@ -40,9 +40,6 @@ import { connectorTypeMenuTriggerSignal } from './TopBar';
const ConnectorTypeSubMenu = (props: {
onSelect: (connectionStye: EdgeConnectionStyle) => void;
}) => {
- const SmallCaretDown = () => (
- <CaretDown style={{ width: '12px' }} class="text-ink-muted" />
- );
const [connectorTypeMenuTrigger, setConnectorTypeMenuTrigger] =
connectorTypeMenuTriggerSignal;
@@ -52,13 +49,8 @@ const ConnectorTypeSubMenu = (props: {
open={connectorTypeMenuTrigger()}
onOpenChange={setConnectorTypeMenuTrigger}
>
- <Dropdown.Trigger
- variant="ghost"
- size="icon-md"
- style={{ width: '12px', margin: '0 -2px 0 -4px' }}
- tabIndex={-1}
- >
- <SmallCaretDown />
+ <Dropdown.Trigger size="icon-sm" label="Connector options" tabIndex={-1}>
+ <CaretDown class="size-3 text-ink-muted" />
</Dropdown.Trigger>
<Dropdown.Content>
<Dropdown.Group>
@@ -181,16 +173,13 @@ export function ToolBar() {
return (
<ScopedPortal scope="block">
{/* Full-frame mobile/tablet: rest above the floating bottom chrome. */}
- <div class="absolute left-1/2 bottom-2 touch:bottom-[calc(var(--mobile-content-inset-bottom,0)+0.5rem)] flex flex-row p-1 bg-surface border border-edge -translate-x-1/2">
- <div
- class={cn(
- 'flex flex-row items-center space-x-2',
- canEdit() && 'border-r border-edge'
- )}
- >
- <Button
+ <Toolbar
+ size="icon-sm"
+ class="absolute left-1/2 bottom-2 touch:bottom-[calc(var(--mobile-content-inset-bottom,0)+0.5rem)] -translate-x-1/2"
+ >
+ <Toolbar.Group>
+ <Toolbar.Button
variant={activeTool() === Tools.Grab ? 'accent' : 'ghost'}
- size="icon-md"
label="Hand tool"
hotkey={TOKENS.canvas.handTool}
onClick={() => {
@@ -198,16 +187,15 @@ export function ToolBar() {
}}
>
<Hand />
- </Button>
+ </Toolbar.Button>
<Show when={!isTouchDevice()}>
- <Button
+ <Toolbar.Button
variant={
activeTool() === Tools.ZoomIn || activeTool() === Tools.ZoomOut
? 'accent'
: 'ghost'
}
- size="icon-md"
label="Zoom"
hotkey={TOKENS.canvas.zoomInTool}
/* scuffed: previously also showed a second row
@@ -218,11 +206,11 @@ export function ToolBar() {
}}
>
{activeTool() === Tools.ZoomOut ? <ZoomOut /> : <ZoomIn />}
- </Button>
+ </Toolbar.Button>
</Show>
<Show when={canEdit()}>
- <Button
+ <Toolbar.Button
variant={
activeTool() === Tools.Select ||
activeTool() === Tools.Resize ||
@@ -230,7 +218,6 @@ export function ToolBar() {
? 'accent'
: 'ghost'
}
- size="icon-md"
label="Move"
hotkey={TOKENS.canvas.selectTool}
onClick={() => {
@@ -238,14 +225,14 @@ export function ToolBar() {
}}
>
<Cursor />
- </Button>
+ </Toolbar.Button>
</Show>
- </div>
+ </Toolbar.Group>
<Show when={canEdit()}>
- <div class="flex flex-row px-2 items-center space-x-2">
- <Button
+ <Toolbar.Divider />
+ <Toolbar.Group>
+ <Toolbar.Button
variant={activeTool() === Tools.Shape ? 'accent' : 'ghost'}
- size="icon-md"
label="Rectangle"
hotkey={TOKENS.canvas.shapeTool}
onClick={() => {
@@ -253,11 +240,10 @@ export function ToolBar() {
}}
>
<Rectangle />
- </Button>
+ </Toolbar.Button>
- <Button
+ <Toolbar.Button
variant={activeTool() === Tools.Pencil ? 'accent' : 'ghost'}
- size="icon-md"
label="Pencil"
hotkey={TOKENS.canvas.pencilTool}
onClick={() => {
@@ -265,29 +251,30 @@ export function ToolBar() {
}}
>
<PencilSimple />
- </Button>
+ </Toolbar.Button>
- <Button
- variant={activeTool() === Tools.Line ? 'accent' : 'ghost'}
- size="icon-md"
- label="Connector"
- hotkey={TOKENS.canvas.lineTool}
- onClick={() => {
- toolManager.setSelectedTool(Tools.Line);
- }}
- >
- <Dynamic component={connectorIcon()} />
- </Button>
- <ConnectorTypeSubMenu onSelect={onSelectConnectionStyle} />
+ <ButtonGroup variant="outline" size="icon-sm">
+ <Button
+ variant={activeTool() === Tools.Line ? 'accent' : 'outline'}
+ label="Connector"
+ hotkey={TOKENS.canvas.lineTool}
+ onClick={() => {
+ toolManager.setSelectedTool(Tools.Line);
+ }}
+ >
+ <Dynamic component={connectorIcon()} />
+ </Button>
+ <ButtonGroup.Divider />
+ <ConnectorTypeSubMenu onSelect={onSelectConnectionStyle} />
+ </ButtonGroup>
<Show when={ENABLE_CANVAS_TEXT}>
- <Button
+ <Toolbar.Button
variant={
activeTool() === Tools.Text || activeTool() === Tools.Typing
? 'accent'
: 'ghost'
}
- size="icon-md"
label="Text"
hotkey={TOKENS.canvas.textTool}
onClick={() => {
@@ -295,21 +282,22 @@ export function ToolBar() {
}}
>
<Text />
- </Button>
+ </Toolbar.Button>
</Show>
- </div>
+ </Toolbar.Group>
</Show>
- <Show when={canEdit()}>
- <div class="flex flex-row px-2 items-center space-x-2 border-l border-edge">
+ <Show when={canEdit() && (ENABLE_CANVAS_IMAGES || ENABLE_CANVAS_FILES)}>
+ <Toolbar.Divider />
+ <Toolbar.Group>
<Show when={ENABLE_CANVAS_IMAGES}>
<MediaSelector />
</Show>
<Show when={ENABLE_CANVAS_FILES}>
<FileSelector />
</Show>
- </div>
+ </Toolbar.Group>
</Show>
- </div>
+ </Toolbar>
</ScopedPortal>
);
}
diff --git a/apps/web/src/features/block-code/component/cmTheme.ts b/apps/web/src/features/block-code/component/cmTheme.ts
index 88a0dd1242..5dfddd70ce 100644
--- a/apps/web/src/features/block-code/component/cmTheme.ts
+++ b/apps/web/src/features/block-code/component/cmTheme.ts
@@ -29,7 +29,7 @@ const base = {
failure50: 'rgb(from var(--color-failure) r g b / 0.5)',
activeLine: 'rgb(from var(--color-edge) r g b / 0.3)',
- selection: 'rgb(from var(--color-edge) r g b / 0.6)',
+ selection: 'rgb(from var(--color-ink) r g b / 0.1)',
menuSelected: 'var(--color-hover)',
searchMatch: 'rgb(from var(--color-accent) r g b / 0.2)',
diff --git a/apps/web/src/features/block-md/component/ComposeTask.tsx b/apps/web/src/features/block-md/component/ComposeTask.tsx
index 69ac511a15..fc43318c7e 100644
--- a/apps/web/src/features/block-md/component/ComposeTask.tsx
+++ b/apps/web/src/features/block-md/component/ComposeTask.tsx
@@ -787,6 +787,7 @@ export function ComposeTask(props: ComposeTaskProps) {
.withCode()
.withMedia({ fileDrop: true })
.withSelectionData()
+ .withFloatingFormatMenu()
.withHistory()
.onChange(setContent)
.onFocusLeave({
diff --git a/apps/web/src/features/block-md/component/FormatTools.tsx b/apps/web/src/features/block-md/component/FormatTools.tsx
index 0970d5e00b..cc1bf7a44f 100644
--- a/apps/web/src/features/block-md/component/FormatTools.tsx
+++ b/apps/web/src/features/block-md/component/FormatTools.tsx
@@ -14,6 +14,7 @@ import { toast } from '@core/component/Toast/Toast';
import { ENABLE_MARKDOWN_COMMENTS } from '@core/constant/featureFlags';
import type { ValidHotkey } from '@core/hotkey/types';
import { useCanComment, useCanEdit } from '@core/signal/permissions';
+import DotsThreeLarge from '@icon/dots-three-large.svg';
import {
$isTableCellNode,
$isTableSelection,
@@ -21,6 +22,7 @@ import {
$unmergeCell,
} from '@lexical/table';
import type { ElementName } from '@macro-inc/lexical-core';
+import CaretDown from '@phosphor/caret-down.svg';
import CaretRight from '@phosphor/caret-right.svg';
import ChatTeardrop from '@phosphor/chat-teardrop.svg';
import Check from '@phosphor/check-square.svg';
@@ -53,7 +55,14 @@ import TextSub from '@phosphor/text-subscript.svg';
import TextSuper from '@phosphor/text-superscript.svg';
import TextT from '@phosphor/text-t.svg';
import TextUnderline from '@phosphor/text-underline.svg';
-import { Button, Dropdown, Hotkey, SingleSelectCheck } from '@ui';
+import {
+ Button,
+ type ButtonSize,
+ Dropdown,
+ Hotkey,
+ SingleSelectCheck,
+ Toolbar,
+} from '@ui';
import {
$getSelection,
COMMAND_PRIORITY_LOW,
@@ -218,6 +227,7 @@ const InlineFormatButton = (props: {
selection: () => SelectionData | undefined;
onClick: (e: MouseEvent) => void;
buttonIsDisabled: Accessor<boolean>;
+ size?: ButtonSize;
}) => {
const icon = InlineIcons[props.format];
const isActive = () => isInlineFormatActive(props.selection(), props.format);
@@ -225,7 +235,7 @@ const InlineFormatButton = (props: {
<Button
label={InlineLabels[props.format]}
shortcut={InlineShortcuts[props.format]}
- size="icon-sm"
+ size={props.size ?? 'icon-sm'}
variant={isActive() ? 'accent' : 'ghost'}
class="rounded-md"
depth={3}
@@ -258,9 +268,7 @@ const InlineFormatMenuItem = (props: {
<Dynamic component={icon} class="size-4 shrink-0" />
<span class="flex-1 truncate">{InlineLabels[props.format]}</span>
<Show when={InlineShortcuts[props.format]}>
- {(shortcut) => (
- <Hotkey shortcut={shortcut()} class="text-ink-muted" showPlus />
- )}
+ {(shortcut) => <Hotkey shortcut={shortcut()} theme="subtle" />}
</Show>
<SingleSelectCheck active={isActive()} />
</Dropdown.Item>
@@ -272,13 +280,14 @@ export const ElementFormatButton = (props: {
selection: () => SelectionData | undefined;
onClick: (e: MouseEvent) => void;
buttonIsDisabled: Accessor<boolean>;
+ size?: ButtonSize;
}) => {
const name = NodeMenuOptions[props.format]?.label || 'Body';
const icon = NodeMenuOptions[props.format]?.icon;
return (
<Button
tooltip={name}
- size="icon-sm"
+ size={props.size ?? 'icon-sm'}
class="rounded-md"
depth={3}
variant={
@@ -347,8 +356,13 @@ const ElementFormatMenuItem = (
);
};
-export function FormatTools(props: { withinPopup?: boolean }) {
+export function FormatTools(props: {
+ withinPopup?: boolean;
+ size?: ButtonSize;
+ onRequestLink?: () => void;
+}) {
const mdData = mdStore.get;
+ const buttonSize = () => props.size ?? 'icon-sm';
const editor = () => mdData.editor;
const titleEditor = () => mdData.titleEditor;
const selection = () => mdData.selection;
@@ -515,7 +529,7 @@ export function FormatTools(props: { withinPopup?: boolean }) {
<Dropdown open={menuOpen()} onOpenChange={setMenuOpen}>
<Dropdown.Trigger
variant={isActive() ? 'accent' : 'ghost'}
- size="icon-sm"
+ size={buttonSize()}
class="rounded-md"
depth={3}
tooltip={'Text Styles'}
@@ -579,7 +593,7 @@ export function FormatTools(props: { withinPopup?: boolean }) {
<Dropdown open={menuOpen()} onOpenChange={setMenuOpen}>
<Dropdown.Trigger
variant={isActive() ? 'accent' : 'ghost'}
- size="icon-sm"
+ size={buttonSize()}
class="rounded-md"
depth={3}
tooltip="Text Styles"
@@ -638,7 +652,7 @@ export function FormatTools(props: { withinPopup?: boolean }) {
? 'accent'
: 'ghost'
}
- size="icon-sm"
+ size={buttonSize()}
class="rounded-md"
depth={3}
tooltip={props.label ?? 'More Formats'}
@@ -687,7 +701,7 @@ export function FormatTools(props: { withinPopup?: boolean }) {
? 'accent'
: 'ghost'
}
- size="icon-sm"
+ size={buttonSize()}
class="rounded-md"
depth={3}
tooltip={props.label ?? 'More Formats'}
@@ -733,72 +747,170 @@ export function FormatTools(props: { withinPopup?: boolean }) {
'quote',
];
+ // The inline formats that aren't surfaced as their own buttons, tucked
+ // behind a "..." trigger that opens them as a horizontal row of buttons.
+ const MoreInlineFormats: InlineFormat[] = [
+ 'underline',
+ 'strikethrough',
+ 'highlight',
+ 'code',
+ 'superscript',
+ 'subscript',
+ ];
+ const MoreInlineDropdown = () => {
+ const [moreInlineOpen, setMoreInlineOpen] = createSignal(false);
+ return (
+ <Dropdown open={moreInlineOpen()} onOpenChange={setMoreInlineOpen}>
+ <Dropdown.Trigger
+ variant="ghost"
+ size={buttonSize()}
+ class="rounded-md"
+ depth={3}
+ tooltip="More formatting"
+ disabled={buttonIsDisabled()}
+ tabIndex={-1}
+ >
+ <DotsThreeLarge />
+ </Dropdown.Trigger>
+ <Show when={!buttonIsDisabled()}>
+ <Dropdown.Content
+ onCloseAutoFocus={() => {
+ lastFocusedEditor()?.focus();
+ }}
+ >
+ <Dropdown.Group>
+ <div class="flex items-center gap-1">
+ <For each={MoreInlineFormats}>
+ {(format) => (
+ <InlineFormatButton
+ format={format}
+ selection={selection}
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ inlineFormat(format);
+ }}
+ buttonIsDisabled={buttonIsDisabled}
+ />
+ )}
+ </For>
+ </div>
+ </Dropdown.Group>
+ </Dropdown.Content>
+ </Show>
+ </Dropdown>
+ );
+ };
+
+ // A single "Text" trigger that opens the block-level style menu
+ // (paragraph, headings, lists, code, quote), used by the selection popup.
+ // Reflects the selected block when the selection is a single block type.
+ const TextBlockDropdown = () => {
+ const [textMenuOpen, setTextMenuOpen] = createSignal(false);
+ const blockFormats: ElementName[] = [
+ 'paragraph',
+ 'heading1',
+ 'heading2',
+ 'heading3',
+ 'list-bullet',
+ 'list-number',
+ 'list-check',
+ 'code',
+ 'quote',
+ ];
+ const currentBlockLabel = () => {
+ const active = blockFormats.filter((format) =>
+ isElementFormatActive(selection(), format)
+ );
+ return active.length === 1
+ ? (NodeMenuOptions[active[0]]?.label ?? 'Text')
+ : 'Text';
+ };
+ return (
+ <Dropdown open={textMenuOpen()} onOpenChange={setTextMenuOpen}>
+ <Dropdown.Trigger
+ variant="ghost"
+ size="sm"
+ class="gap-1 rounded-md"
+ depth={3}
+ tooltip="Text style"
+ disabled={buttonIsDisabled()}
+ tabIndex={-1}
+ >
+ {currentBlockLabel()}
+ <CaretDown class="size-3" />
+ </Dropdown.Trigger>
+ <Show when={!buttonIsDisabled()}>
+ <Dropdown.Content
+ class="text-xs"
+ onCloseAutoFocus={() => {
+ lastFocusedEditor()?.focus();
+ }}
+ >
+ <Dropdown.Group>
+ <For each={blockFormats}>
+ {(format) => (
+ <ElementFormatMenuItem
+ format={format}
+ selection={selection}
+ onClick={() => {
+ nodeFormat(format);
+ setTextMenuOpen(false);
+ }}
+ useIcon={true}
+ useStyle={false}
+ buttonIsDisabled={buttonIsDisabled}
+ />
+ )}
+ </For>
+ </Dropdown.Group>
+ </Dropdown.Content>
+ </Show>
+ </Dropdown>
+ );
+ };
+
if (props.withinPopup) {
return (
- <div class="flex h-full gap-1 items-center">
+ <div class="flex h-full items-center gap-1">
<Show when={canEdit()}>
- <ElementFormatButton
- format="paragraph"
- onClick={(e) => {
- e.preventDefault();
- e.stopPropagation();
- nodeFormat('paragraph');
- }}
- buttonIsDisabled={buttonIsDisabled}
- selection={selection}
- />
- <ElementFormatMenu
- elements={['heading1', 'heading2', 'heading3']}
- icon={TextH}
- label="Headings"
- buttonIsDisabled={buttonIsDisabled}
- />
- <ElementFormatMenu
- elements={['list-bullet', 'list-number', 'list-check']}
- icon={ListBullets}
- label="Lists"
- buttonIsDisabled={buttonIsDisabled}
- />
- <ElementFormatButton
- format="code"
+ <InlineFormatButton
+ format="bold"
selection={selection}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
- nodeFormat('code');
+ inlineFormat('bold');
}}
buttonIsDisabled={buttonIsDisabled}
+ size={buttonSize()}
/>
- <ElementFormatButton
- format="quote"
+ <InlineFormatButton
+ format="italic"
selection={selection}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
- nodeFormat('quote');
+ inlineFormat('italic');
}}
buttonIsDisabled={buttonIsDisabled}
- />
- <InlineFormatPopDown
- formats={[
- 'bold',
- 'italic',
- 'underline',
- 'strikethrough',
- 'code',
- 'highlight',
- 'superscript',
- 'subscript',
- ]}
- buttonIsDisabled={buttonIsDisabled}
+ size={buttonSize()}
/>
<Button
variant="ghost"
- size="icon-sm"
+ size={buttonSize()}
class="rounded-md"
depth={3}
onPointerDown={(e: PointerEvent) => e.preventDefault()}
- onClick={handleLink}
+ onClick={(e) => {
+ if (!selection()?.hasLinks && props.onRequestLink) {
+ e.preventDefault();
+ e.stopPropagation();
+ props.onRequestLink();
+ } else {
+ handleLink(e);
+ }
+ }}
tooltip={selection()?.hasLinks ? 'Remove Link' : 'Insert Link'}
disabled={buttonIsDisabled()}
>
@@ -806,10 +918,13 @@ export function FormatTools(props: { withinPopup?: boolean }) {
component={selection()?.hasLinks ? BrokenLinkIcon : LinkIcon}
/>
</Button>
+ <MoreInlineDropdown />
+ <Toolbar.Divider />
+ <TextBlockDropdown />
<Show when={selection()?.onMergableCells}>
<Button
variant="ghost"
- size="icon-sm"
+ size={buttonSize()}
class="rounded-md"
depth={3}
tooltip="Merge cells"
@@ -822,7 +937,7 @@ export function FormatTools(props: { withinPopup?: boolean }) {
<Show when={selection()?.onSplittableCells}>
<Button
variant="ghost"
- size="icon-sm"
+ size={buttonSize()}
class="rounded-md"
depth={3}
tooltip="Split cell"
@@ -833,23 +948,6 @@ export function FormatTools(props: { withinPopup?: boolean }) {
</Button>
</Show>
</Show>
- <Show when={ENABLE_MARKDOWN_COMMENTS && canComment()}>
- <Button
- variant="ghost"
- size="icon-sm"
- class="rounded-md"
- depth={3}
- tooltip="Comment"
- onClick={(e) => {
- e.preventDefault();
- e.stopPropagation();
- handleInsertComment();
- }}
- disabled={commentButtonIsDisabled()}
- >
- <ChatTeardrop />
- </Button>
- </Show>
</div>
);
} else {
diff --git a/apps/web/src/features/block-md/component/MarkdownPopup.tsx b/apps/web/src/features/block-md/component/MarkdownPopup.tsx
index 3ae799fc64..ef59a3ea35 100644
--- a/apps/web/src/features/block-md/component/MarkdownPopup.tsx
+++ b/apps/web/src/features/block-md/component/MarkdownPopup.tsx
@@ -5,12 +5,9 @@ import {
highlightedCommentThreadsSignal,
} from '@block-md/comments/commentStore';
import { MobileDrawer } from '@components/app/mobile/MobileDrawer';
-import { useSplitLayout } from '@components/app/split-layout/layout';
-import { useIsAuthenticated } from '@core/auth';
import { useBlockId } from '@core/block';
-import type { Completion } from '@core/client/completion';
-import { ChatMessageMarkdown } from '@core/component/AI/component/message/ChatMessageMarkdown';
import { GeneralizedPopup } from '@core/component/GeneralizedPopup/Popup';
+import { PopupPositioner } from '@core/component/GeneralizedPopup/PopupPositioner';
import { LocationHighlight } from '@core/component/LexicalMarkdown/component/core/Highlights';
import {
createMenuOpenSignal,
@@ -21,8 +18,10 @@ import {
$getConvertibleListFromSelection,
autoRegister,
type EnhancedSelection,
+ INSERT_LINK_COMMAND,
LIST_TO_TABLE_COMMAND,
NODE_TRANSFORM,
+ normalizeLinkUrl,
registerRootEventListener,
} from '@core/component/LexicalMarkdown/plugins';
import {
@@ -40,15 +39,15 @@ import {
type PersistentLocation,
} from '@core/component/LexicalMarkdown/plugins/location/locationPlugin';
import {
- HIGHLIGHT_SELECTED_NODES,
- POPUP_REPLACE_TEXT,
popupPlugin,
RECOMPUTE_SELECTION_RECT,
- REMOVE_HIGHLIGHT_SELECTED_NODES,
} from '@core/component/LexicalMarkdown/plugins/popup/popupPlugin';
import { ScopedPortal } from '@core/component/ScopedPortal';
import { toast } from '@core/component/Toast/Toast';
-import { enableInlineAiEditing } from '@core/constant/featureFlags';
+import {
+ ENABLE_MARKDOWN_COMMENTS,
+ enableInlineAiEditing,
+} from '@core/constant/featureFlags';
import { useUserId } from '@core/context/user';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import {
@@ -56,34 +55,26 @@ import {
setNativeEditMenuSuppressed,
} from '@core/mobile/nativeEditMenu';
import { useCanComment, useCanEdit } from '@core/signal/permissions';
-import { createMarkdownFile } from '@core/util/create';
-import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';
import { debouncedDependent } from '@core/util/debounce';
import { getScrollParentElement } from '@core/util/scrollParent';
-import MacroGridLoader from '@icon/macro-grid-noise-loader-4.svg';
import type { NodeIdMappings } from '@macro-inc/lexical-core';
import { $getId } from '@macro-inc/lexical-core/plugins/nodeIdPlugin';
+import ArrowUp from '@phosphor/arrow-up.svg';
+import ChatTeardrop from '@phosphor/chat-teardrop.svg';
import GridIcon from '@phosphor/grid-four.svg';
import CheckIcon from '@phosphor-icons/core/bold/check-bold.svg?component-solid';
-import ClipboardIcon from '@phosphor-icons/core/bold/clipboard-bold.svg?component-solid';
-import NotesIcon from '@phosphor-icons/core/bold/file-md-bold.svg?component-solid';
import SparkleIcon from '@phosphor-icons/core/bold/sparkle-bold.svg?component-solid';
import LoadingIcon from '@phosphor-icons/core/bold/spinner-gap-bold.svg?component-solid';
-import PaperPlaneRight from '@phosphor-icons/core/fill/paper-plane-right-fill.svg?component-solid';
import CheckSquareIcon from '@phosphor-icons/core/regular/check-square.svg?component-solid';
import LinkIcon from '@phosphor-icons/core/regular/link.svg?component-solid';
-import PencilIcon from '@phosphor-icons/core/regular/pencil.svg?component-solid';
import {
cancelAiEdit,
hasActiveAiEdit,
requestAiEdit,
} from '@service-ai-editing/client';
-import { generateTitle } from '@service-cognition/client';
import { makeResizeObserver } from '@solid-primitives/resize-observer';
-import { createCallback } from '@solid-primitives/rootless';
-import { Button, Layer } from '@ui';
+import { Button, Toolbar } from '@ui';
import {
- $getRoot,
$getSelection,
$isRangeSelection,
$setSelection,
@@ -205,16 +196,12 @@ export function MarkdownPopup(props: {
const highlightedCommentThreads = highlightedCommentThreadsSignal.get;
const setActiveCommentThread = activeCommentThreadSignal.set;
- const [copied, setCopied] = createSignal(false);
const [locationCopied, setLocationCopied] = createSignal(false);
- const [isLoading, setIsLoading] = createSignal<boolean>(false);
const [isConverting, setIsConverting] = createSignal(false);
const [hasCheckboxes, setHasCheckboxes] = createSignal(false);
const [convertibleListKey, setConvertibleListKey] = createSignal<
string | null
>(null);
- const { replaceOrInsertSplit } = useSplitLayout();
- let markdownRootRef!: HTMLDivElement;
const _selectedText = () => selection()?.text ?? undefined;
const _selectedNodesText = () => selection()?.nodeText ?? undefined;
@@ -335,20 +322,19 @@ export function MarkdownPopup(props: {
fallback={
<Button
size="icon-sm"
- class="rounded-md"
- depth={3}
- variant="ghost"
- tooltip="Ask Macro"
+ class="rounded-full"
+ variant="strong"
+ tooltip="Send"
disabled={!aiEditInput().trim()}
onClick={handleAiEditSubmit}
>
- <CheckIcon class="size-4" />
+ <ArrowUp class="size-4" />
</Button>
}
>
<Button
size="icon-sm"
- class="rounded-md"
+ class="rounded-full"
depth={3}
variant="ghost"
tooltip="Stop AI edit"
@@ -499,403 +485,210 @@ export function MarkdownPopup(props: {
};
const MarkdownPopupToolbar = () => {
- const _isAuthenticated = useIsAuthenticated();
- const [completion, _setCompletion] = createSignal<Completion | undefined>(
- undefined
- );
-
- const [completionType, _setCompletionType] = createSignal<
- 'explain' | 'bullet' | 'translate' | 'rewrite' | undefined
- >(undefined);
-
- const isGenerating = () => completion()?.status !== 'completed';
-
- const [inputVal, setInputVal] = createSignal('');
- const [rewriteInputRef, setRewriteInputRef] = createSignal<
- HTMLTextAreaElement | undefined
- >(undefined);
-
- const handleCopy = async () => {
- const cleanedText = completion()?.content;
- if (!cleanedText) {
- return;
- }
- const html = markdownRootRef?.outerHTML ?? null;
- if (!html) {
- try {
- await navigator.clipboard.writeText(cleanedText);
- setCopied(true);
- setTimeout(() => setCopied(false), 2000);
- } catch {}
- return;
- }
-
- const clipboardItem = new ClipboardItem({
- 'text/plain': new Blob([cleanedText], { type: 'text/plain' }),
- 'text/html': new Blob([html], { type: 'text/html' }),
- });
- let written = false;
- // try rich and plain first. Not avail in all browsers and contexts.
- try {
- await navigator.clipboard.write([clipboardItem]);
- written = true;
- setCopied(true);
- setTimeout(() => setCopied(false), 2000);
- } catch {}
-
- if (!written) {
- try {
- await navigator.clipboard.writeText(cleanedText);
- written = true;
- setCopied(true);
- setTimeout(() => setCopied(false), 2000);
- } catch {}
- }
+ let savedLinkSelection: RangeSelection | null = null;
+ const [activePrompt, setActivePrompt] = createSignal<
+ 'none' | 'ai' | 'link'
+ >('none');
+ const [linkInput, setLinkInput] = createSignal('');
+
+ // Track the toolbar's rendered width so a prompt that replaces it keeps the
+ // same footprint instead of snapping to its own content width.
+ const [toolbarWidth, setToolbarWidth] = createSignal<number>();
+ const measureToolbar = (el: HTMLDivElement) => {
+ const update = () => setToolbarWidth(el.getBoundingClientRect().width);
+ update();
+ const observer = new ResizeObserver(update);
+ observer.observe(el);
+ onCleanup(() => observer.disconnect());
};
- const handleReplaceText = createCallback(async (newText: string) => {
- editor.dispatchCommand(POPUP_REPLACE_TEXT, newText);
- setPopupVisible(false);
+ onCleanup(() => {
+ setHighlightLocation(null);
});
- const name = useBlockDocumentName();
- const handleEditInMarkdown = createCallback(async () => {
- setIsLoading(true);
- const content = completion()?.content;
- if (!content) {
- return;
- }
-
- const title = await generateTitle(content);
- const documentId = await createMarkdownFile({
- content,
- title: title ?? `${name()} - AI Explanation`,
- });
-
- if (!documentId) {
- console.error('Error opening AI message in Notes');
- setIsLoading(false);
- return;
- }
-
- replaceOrInsertSplit({
- type: 'md',
- id: documentId,
+ // Snapshot the selection before the link input steals focus so the URL can
+ // be applied to the original range on submit.
+ const handleRequestLink = () => {
+ savedLinkSelection = editor.read(() => {
+ const current = $getSelection();
+ return $isRangeSelection(current) ? current.clone() : null;
});
- setIsLoading(false);
- });
+ setActivePrompt('link');
+ };
- const _contentSize = () => {
- let charCount = 0;
- editor.getEditorState().read(() => {
- const root = $getRoot();
- const text = root.getTextContent();
- charCount = text.length;
+ const handleInsertLink = () => {
+ const input = linkInput().trim();
+ const url = normalizeLinkUrl(input);
+ if (!url) return;
+ const linkText = selection()?.text ?? input;
+ editor.update(() => {
+ if (savedLinkSelection) $setSelection(savedLinkSelection);
});
- return charCount;
+ editor.dispatchCommand(INSERT_LINK_COMMAND, { url, linkText });
+ setLinkInput('');
+ setActivePrompt('none');
+ setPopupVisible(false);
};
- const handleRewrite = (_instructions: string) => {};
-
- let aiInputRef: HTMLTextAreaElement | undefined;
-
- createEffect(
- on([completionType, rewriteInputRef], () => {
- if (highlightLocation()) {
- return;
- }
-
- const inputRef = rewriteInputRef();
- if (completionType() === 'rewrite' && inputRef) {
- const location = editor.read(() => $getSelectionLocation());
- if (!location) return;
-
- setHighlightLocation(location);
- inputRef.focus();
- }
- })
- );
-
- onCleanup(() => {
- setHighlightLocation(null);
- });
-
- // HACK (seamus) : Would be nice to have a better way to make the
- // width of the content follow the width of the buton row without width
- // queries, but for now this works.
- let buttonRowRef!: HTMLDivElement;
- const [maxInnerWidth, setMaxInnerWidth] = createSignal(300);
- onMount(() => {
- setMaxInnerWidth(buttonRowRef.getBoundingClientRect().width);
- const observer = new ResizeObserver(() => {
- setMaxInnerWidth(buttonRowRef.getBoundingClientRect().width);
- });
- observer.observe(buttonRowRef);
- onCleanup(() => {
- observer.disconnect();
- });
- });
+ // Escape dismisses the input and refocuses the editor so the selection is
+ // preserved (and never reaches lexical's own escape handling).
+ const dismissPrompt = () => {
+ setActivePrompt('none');
+ setLinkInput('');
+ setAiEditInput('');
+ editor.focus();
+ };
return (
- <>
- <div
- class="gap-1 flex flex-row items-center flex-nowrap p-0"
- ref={buttonRowRef}
- >
- {/*<Show
- when={
- ENABLE_MARKDOWN_AI_GENERATE &&
- isAuthenticated() &&
- !!selectedText() &&
- selectionType() === "range" &&
- blockId
- }
- >
- <AskAi
- attachmentId={blockId}
- blockName="md"
- setCompletion={setCompletion}
- setCompletionType={setCompletionType}
- selectedText={selectedText()!}
- canEdit={canEdit()}
- contentSize={contentSize}
- selectedNodesText={selectedNodesText()}
- registerRewriteMethod={(fn: (instructions: string) => void) => {
- handleRewrite = fn;
- }}
- />
- </Show>*/}
- <Show when={canEdit() || canComment()}>
- <FormatTools withinPopup />
- </Show>
- <Show when={shouldShowCheckboxToTaskButton()}>
- <Button
- size="sm"
- class="rounded-md"
+ <Show
+ when={activePrompt() !== 'none'}
+ fallback={
+ <Toolbar ref={measureToolbar}>
+ {/* Selection actions: AI edit + convert to tasks. */}
+ <Show when={shouldShowEditWithAiButton()}>
+ <Toolbar.Button
+ size="sm"
+ depth={3}
+ onClick={() => setActivePrompt('ai')}
+ >
+ AI edit
+ </Toolbar.Button>
+ </Show>
+ <Show when={shouldShowCheckboxToTaskButton()}>
+ <Toolbar.Button
+ size="sm"
+ depth={3}
+ onClick={handleConvertToTasks}
+ disabled={isConverting()}
+ >
+ <Dynamic
+ component={isConverting() ? LoadingIcon : CheckSquareIcon}
+ class="size-4"
+ />
+ {isConverting() ? 'Converting...' : 'Tasks'}
+ </Toolbar.Button>
+ </Show>
+ <Show
+ when={
+ shouldShowEditWithAiButton() || shouldShowCheckboxToTaskButton()
+ }
+ >
+ <Toolbar.Divider />
+ </Show>
+
+ <Show when={canEdit()}>
+ <FormatTools withinPopup onRequestLink={handleRequestLink} />
+ <Toolbar.Divider />
+ </Show>
+
+ <Show when={shouldShowTableButton()}>
+ <Toolbar.Button
+ size="sm"
+ depth={3}
+ tooltip="Convert list to table"
+ onClick={handleConvertListToTable}
+ >
+ <GridIcon class="size-4" />
+ Table
+ </Toolbar.Button>
+ <Toolbar.Divider />
+ </Show>
+ <Show when={ENABLE_MARKDOWN_COMMENTS && canComment()}>
+ <Toolbar.Button
+ size="icon-sm"
+ depth={3}
+ onClick={handleInsertComment}
+ tooltip="Comment"
+ label="Comment"
+ >
+ <ChatTeardrop />
+ </Toolbar.Button>
+ </Show>
+ <Toolbar.Button
+ size="icon-sm"
depth={3}
- variant="ghost"
- onClick={handleConvertToTasks}
- disabled={isConverting()}
+ onClick={() => void handleShare()}
+ tooltip="Copy link to snippet"
+ label="Copy link to snippet"
>
<Dynamic
- component={isConverting() ? LoadingIcon : CheckSquareIcon}
- class="size-4"
+ component={locationCopied() ? CheckIcon : LinkIcon}
+ class={locationCopied() ? 'text-success-ink size-4' : 'size-4'}
/>
- {isConverting() ? 'Converting...' : 'Tasks'}
- </Button>
- </Show>
- <Show when={shouldShowTableButton()}>
- <Button
- size="sm"
- class="rounded-md"
- depth={3}
- variant="ghost"
- tooltip="Convert list to table"
- onClick={handleConvertListToTable}
- >
- <GridIcon class="size-4" />
- Table
- </Button>
- </Show>
- <Button
- size="sm"
- class="px-2 text-xs rounded-md py-1.25"
- depth={3}
- variant="ghost"
- onClick={() => void handleShare()}
+ </Toolbar.Button>
+ </Toolbar>
+ }
+ >
+ <Toolbar
+ class="gap-2"
+ style={{
+ width: toolbarWidth() ? `${toolbarWidth()}px` : undefined,
+ }}
+ >
+ <Show
+ when={activePrompt() === 'link'}
+ fallback={
+ <textarea
+ class="grow resize-none overflow-hidden bg-transparent pl-2 text-sm placeholder:text-ink-placeholder focus:outline-none"
+ rows={1}
+ placeholder="Describe changes"
+ ref={(el) => {
+ requestAnimationFrame(() => el.focus());
+ }}
+ onFocus={() => setAiInputFocused(true)}
+ onBlur={() => setAiInputFocused(false)}
+ onInput={handleAiInput}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' && !e.shiftKey) {
+ e.preventDefault();
+ handleAiEditSubmit();
+ } else if (e.key === 'Escape') {
+ e.preventDefault();
+ e.stopPropagation();
+ dismissPrompt();
+ }
+ }}
+ />
+ }
>
- <Dynamic
- component={locationCopied() ? CheckIcon : LinkIcon}
- class={locationCopied() ? 'text-success-ink size-4' : 'size-4'}
- />
- Share
- </Button>
- </div>
-
- <Show when={shouldShowEditWithAiButton()}>
- <div class="mt-1 flex w-full min-w-72 items-center gap-1 border-t border-edge p-1 pt-1.5 pr-2">
- <SparkleIcon class="size-4 shrink-0 text-ink-extra-muted" />
- <textarea
- class="grow resize-none overflow-hidden bg-transparent text-sm placeholder:text-ink-placeholder focus:outline-none"
- rows={1}
- placeholder="Ask Macro to edit this selection"
+ <input
+ type="text"
+ class="h-6 grow bg-transparent pl-2 text-sm placeholder:text-ink-placeholder focus:outline-none"
+ placeholder="Paste or insert link"
+ value={linkInput()}
ref={(el) => {
- aiInputRef = el;
+ requestAnimationFrame(() => el.focus());
}}
- onFocus={() => setAiInputFocused(true)}
- onBlur={() => setAiInputFocused(false)}
- onInput={handleAiInput}
+ onInput={(e) => setLinkInput(e.currentTarget.value)}
onKeyDown={(e) => {
- if (e.key === 'Enter' && !e.shiftKey) {
+ if (e.key === 'Enter') {
e.preventDefault();
- handleAiEditSubmit();
+ handleInsertLink();
} else if (e.key === 'Escape') {
e.preventDefault();
e.stopPropagation();
- setAiEditInput('');
- aiInputRef?.blur();
+ dismissPrompt();
}
}}
/>
+ </Show>
+ <Show when={activePrompt() === 'ai'}>
<AiEditSubmitButton />
- </div>
- </Show>
-
- <Show when={!completion() && completionType() === 'rewrite'}>
- <div class="flex flex-col border-t border-edge mt-1 pt-2 w-full">
- <p class="text-ink-muted font-medium pt-1 pl-3 text-sm">
- How would you like this text rewritten?
- </p>
- <div class="flex flex-row items-center space-x-2 w-full px-2">
- <textarea
- class="resize-none rounded-xs w-full p-2 my-3 text-sm max-h-[800px] overflow-hidden border border-edge bg-hover"
- ref={setRewriteInputRef}
- rows={1}
- onSubmit={(e) => e.preventDefault()}
- placeholder={'Check for spelling and grammar errors'}
- onInput={(e) => {
- setInputVal(e.currentTarget.value);
- e.target.style.height = 'auto';
- e.target.style.height = `${e.target.scrollHeight}px`;
- }}
- onKeyDown={(e) => {
- if (e.key === 'Enter' && !e.shiftKey) {
- e.preventDefault();
- handleRewrite(inputVal());
- }
- }}
- />
- <button
- class="bg-transparent rounded-full hover:scale-110! transition ease-in-out delay-150 flex flex-col justify-center items-center py-1"
- onClick={() => {
- handleRewrite(inputVal());
- }}
- >
- <PaperPlaneRight
- width={20}
- height={20}
- color="var(--color-accent)"
- class="text-accent fill-accent!"
- />
- </button>
- </div>
- </div>
- </Show>
-
- <Show when={completion()}>
- {(completion) => (
- <div
- class="rounded-xs p-1 mt-1"
- style={{
- 'overflow-wrap': 'break-word',
- width: `${maxInnerWidth()}px`,
- }}
+ </Show>
+ <Show when={activePrompt() === 'link'}>
+ <Button
+ size="icon-sm"
+ class="rounded-full"
+ variant="strong"
+ tooltip="Insert link"
+ disabled={!linkInput().trim()}
+ onClick={handleInsertLink}
>
- <Show
- when={
- completion().status !== 'loading' &&
- completion().content.length > 0
- }
- fallback={
- <div class="p-2 font-mono text-sm flex items-center gap-2">
- <MacroGridLoader
- width={20}
- height={20}
- class="text-accent"
- />
- </div>
- }
- >
- <div class="wrap-break-word p-2">
- <ChatMessageMarkdown
- text={completion().content}
- generating={isGenerating}
- rootRef={(ref: HTMLDivElement) => {
- markdownRootRef = ref;
- }}
- />
- </div>
- <div class="border-t border-edge">
- <div class="flex flex-row justify-end text-ink-muted mt-1">
- <Show when={completionType() === 'rewrite'}>
- {' '}
- <div class="w-fit mr-2">
- {' '}
- <button
- class="flex flex-row items-center space-x-1 hover:bg-hover hover-transition-bg rounded-md p-1 text-xs font-sans"
- onClick={() => {
- !isLoading() &&
- handleReplaceText(completion().content);
- }}
- onMouseEnter={() => {
- editor.dispatchCommand(
- HIGHLIGHT_SELECTED_NODES,
- undefined
- );
- }}
- onMouseLeave={() => {
- editor.dispatchCommand(
- REMOVE_HIGHLIGHT_SELECTED_NODES,
- undefined
- );
- }}
- >
- {' '}
- <Show
- when={!isLoading() && !isGenerating()}
- fallback={
- <LoadingIcon class="size-3 animate-spin" />
- }
- >
- {' '}
- <PencilIcon class="size-3" />{' '}
- </Show>{' '}
- <p>Accept Changes</p>{' '}
- </button>{' '}
- </div>
- </Show>
- <div class="w-fit mr-2">
- <button
- class="flex flex-row items-center space-x-1 hover:bg-hover hover-transition-bg rounded-md p-1 text-xs font-sans"
- onClick={() => {
- !isLoading() && handleEditInMarkdown();
- }}
- >
- <Show
- when={!isLoading() && !isGenerating()}
- fallback={<LoadingIcon class="size-3 animate-spin" />}
- >
- <NotesIcon class="size-3 text-note" />
- </Show>
- <p>Edit in Notes</p>
- </button>
- </div>
- <div class="w-fit">
- <button
- class="flex flex-row items-center space-x-1 hover:bg-hover hover-transition-bg rounded-md p-1 text-xs font-sans"
- onClick={handleCopy}
- >
- <Show
- when={!isGenerating()}
- fallback={<LoadingIcon class="size-3 animate-spin" />}
- >
- <Show
- when={!copied()}
- fallback={<CheckIcon class="size-3 text-success" />}
- >
- <ClipboardIcon class="size-3" />
- </Show>
- </Show>
- <p>{copied() ? 'Copied!' : 'Copy'}</p>
- </button>
- </div>
- </div>
- </div>
- </Show>
- </div>
- )}
- </Show>
- </>
+ <CheckIcon class="size-4" />
+ </Button>
+ </Show>
+ </Toolbar>
+ </Show>
);
};
@@ -907,26 +700,47 @@ export function MarkdownPopup(props: {
if (!aiEditRunning() && !aiEditDrawerOpen()) setAiEditLocation(null);
});
return (
- <Show when={isTouchDevice()} fallback={<MarkdownPopupToolbar />}>
- <TouchSelectionToolbar
- canEdit={canEdit()}
- canComment={canComment()}
- isConverting={isConverting()}
- hasSelection={(selection()?.text ?? '') !== ''}
- showTasksOption={shouldShowCheckboxToTaskButton()}
- showTableOption={shouldShowTableButton()}
- showEditWithAiOption={shouldShowEditWithAiButton()}
- showOpenCommentOption={highlightedCommentThreads().length > 0}
- locationCopied={locationCopied()}
- setPopupVisible={setPopupVisible}
- onConvertToTasks={handleConvertToTasks}
- onConvertListToTable={handleConvertListToTable}
- onOpenComment={handleShowComment}
- onShare={() => void handleShare()}
- onInsertComment={handleInsertComment}
- onPaste={() => void handlePaste()}
- onEditWithAi={handleOpenAiEditDrawer}
- />
+ <Show
+ when={isTouchDevice()}
+ fallback={
+ <PopupPositioner
+ anchor={anchorRef()!}
+ useBlockBoundary
+ ref={setMenuRef}
+ >
+ <MarkdownPopupToolbar />
+ </PopupPositioner>
+ }
+ >
+ <GeneralizedPopup
+ anchor={{
+ ref: anchorRef()!,
+ blockId: `${blockId}`,
+ blockType: 'md',
+ }}
+ useBlockBoundary={true}
+ ref={setMenuRef}
+ >
+ <TouchSelectionToolbar
+ canEdit={canEdit()}
+ canComment={canComment()}
+ isConverting={isConverting()}
+ hasSelection={(selection()?.text ?? '') !== ''}
+ showTasksOption={shouldShowCheckboxToTaskButton()}
+ showTableOption={shouldShowTableButton()}
+ showEditWithAiOption={shouldShowEditWithAiButton()}
+ showOpenCommentOption={highlightedCommentThreads().length > 0}
+ locationCopied={locationCopied()}
+ setPopupVisible={setPopupVisible}
+ onConvertToTasks={handleConvertToTasks}
+ onConvertListToTable={handleConvertListToTable}
+ onOpenComment={handleShowComment}
+ onShare={() => void handleShare()}
+ onInsertComment={handleInsertComment}
+ onPaste={() => void handlePaste()}
+ onEditWithAi={handleOpenAiEditDrawer}
+ />
+ </GeneralizedPopup>
</Show>
);
};
@@ -980,18 +794,7 @@ export function MarkdownPopup(props: {
</Show>
<Show when={showPopup() && anchorRef()}>
<ScopedPortal scope="local">
- <Layer depth={2}>
- <GeneralizedPopup
- PopupComponents={PopupToolbar}
- anchor={{
- ref: anchorRef()!,
- blockId: `${blockId}`,
- blockType: 'md',
- }}
- useBlockBoundary={true}
- ref={setMenuRef}
- />
- </Layer>
+ <PopupToolbar />
</ScopedPortal>
</Show>
<Show when={highlightLocation()}>
@@ -1013,16 +816,23 @@ export function MarkdownPopup(props: {
>
<style>{`
.ai-edit-highlight {
- background: var(--color-accent);
- opacity: 0.25;
+ background-color: color-mix(in oklab, var(--color-ink) 5%, transparent);
border-radius: 3px;
}
- @keyframes ai-edit-pulse {
- 0%, 100% { opacity: 0.2; }
- 50% { opacity: 0.6; }
+ @keyframes ai-edit-swipe {
+ 0% { background-position: 150% 0; }
+ 100% { background-position: -50% 0; }
}
.ai-edit-highlight-running {
- animation: ai-edit-pulse 1.4s ease-in-out infinite;
+ background-image: linear-gradient(
+ 100deg,
+ transparent 40%,
+ color-mix(in oklab, var(--color-ink) 9%, transparent) 50%,
+ transparent 60%
+ );
+ background-size: 250% 100%;
+ background-repeat: no-repeat;
+ animation: ai-edit-swipe 1.6s ease-in-out infinite;
}
`}</style>
<LocationHighlight
@@ -1060,7 +870,7 @@ export function MarkdownPopup(props: {
<textarea
class="grow resize-none bg-transparent py-1.5 text-sm placeholder:text-ink-placeholder focus:outline-none"
rows={1}
- placeholder="Ask Macro to edit this selection"
+ placeholder="Describe changes"
value={aiEditInput()}
ref={(el) => {
requestAnimationFrame(() => el.focus());
diff --git a/apps/web/src/features/block-pdf/component/PDFPopup.tsx b/apps/web/src/features/block-pdf/component/PDFPopup.tsx
index 3a0b38beb1..79f40dc8c6 100644
--- a/apps/web/src/features/block-pdf/component/PDFPopup.tsx
+++ b/apps/web/src/features/block-pdf/component/PDFPopup.tsx
@@ -372,12 +372,13 @@ export function PDFPopup(props: PDFPopupProps) {
return (
<GeneralizedPopup
- PopupComponents={PDFPopupToolbar}
anchor={{
ref: props.anchorRef,
blockId: `${blockId}`,
blockType: 'pdf',
}}
- />
+ >
+ <PDFPopupToolbar />
+ </GeneralizedPopup>
);
}
diff --git a/apps/web/src/features/channel/Input/TaskComposer.tsx b/apps/web/src/features/channel/Input/TaskComposer.tsx
index 6c2ae60a6f..f513ba819a 100644
--- a/apps/web/src/features/channel/Input/TaskComposer.tsx
+++ b/apps/web/src/features/channel/Input/TaskComposer.tsx
@@ -251,6 +251,7 @@ export function TaskComposer(props: {
.withCode()
.withMedia({ fileDrop: true })
.withSelectionData()
+ .withFloatingFormatMenu()
.withHistory()
.onChange(setContent)
.onEscape(() => {
diff --git a/apps/web/src/features/channel/Message/ActionMenu.tsx b/apps/web/src/features/channel/Message/ActionMenu.tsx
index 8865885d9c..7b49666dd3 100644
--- a/apps/web/src/features/channel/Message/ActionMenu.tsx
+++ b/apps/web/src/features/channel/Message/ActionMenu.tsx
@@ -8,7 +8,7 @@ import LinkIcon from '@phosphor/link.svg';
import EditIcon from '@phosphor/pencil-simple.svg';
import AddEmojiIcon from '@phosphor/smiley.svg';
import TrashIcon from '@phosphor/trash.svg';
-import { Button, cn, Layer } from '@ui';
+import { cn, Toolbar } from '@ui';
import {
type Component,
createSignal,
@@ -68,21 +68,19 @@ function ActionButton(props: {
onPointerDown?: JSX.EventHandlerUnion<HTMLButtonElement, PointerEvent>;
}) {
return (
- <Button
+ <Toolbar.Button
aria-label={props.action.label}
data-message-action={props.action.id}
onClick={props.onClick}
onPointerDown={props.onPointerDown}
tooltip={props.action.label}
- size="icon-sm"
- variant="ghost"
class={props.action.class}
>
{renderIcon(
props.action.icon,
cn(props.action.iconClass, props.action.class)
)}
- </Button>
+ </Toolbar.Button>
);
}
@@ -178,32 +176,26 @@ function ActionMenuContent(props: ActionMenuProps) {
// the very top; float the toolbar fully above so it never covers it.
position={props.showTimestamp ? 'above' : 'straddle'}
>
- <Layer depth={2}>
- <div
- class="flex flex-row bg-surface ring-1 ring-ink/10 p-1 shadow-md items-center rounded-lg"
- onClick={(e) => e.stopPropagation()}
- >
- <Show when={props.showTimestamp}>
- <Timestamp format="time" class="px-1.5 whitespace-nowrap" />
- <div class="w-px self-stretch bg-ink/10 mx-1" />
- </Show>
- <Show when={hasReactAction()}>
+ <Toolbar size="icon-sm" onClick={(event) => event.stopPropagation()}>
+ <Show when={props.showTimestamp}>
+ <Timestamp format="time" class="px-1.5 whitespace-nowrap" />
+ <Toolbar.Divider />
+ </Show>
+ <Show when={hasReactAction()}>
+ <Toolbar.Group>
<For each={QUICK_REACTION_EMOJIS}>
{(emoji) => (
- <Button
- size="icon-sm"
- variant="ghost"
+ <Toolbar.Button
onClick={(event) => {
recordEmojiUsage(emoji);
handleReaction(emoji, event);
}}
- tooltip={`React ${emoji}`}
aria-label={`React ${emoji}`}
data-message-action="react-quick"
data-emoji={emoji}
>
<span class="text-base my-0">{emoji}</span>
- </Button>
+ </Toolbar.Button>
)}
</For>
@@ -216,77 +208,83 @@ function ActionMenuContent(props: ActionMenuProps) {
}}
trigger={renderIcon(AddEmojiIcon, 'size-4')}
triggerProps={{
- title: 'More reactions',
'aria-label': 'More reactions',
- tooltip: 'More reactions',
variant: 'ghost',
size: 'icon-sm',
}}
/>
- <Show when={visibleActions.length > 0}>
- <div class="w-px self-stretch bg-ink/10 mx-1" />
- </Show>
+ </Toolbar.Group>
+ <Show when={visibleActions.length > 0}>
+ <Toolbar.Divider />
</Show>
+ </Show>
- <For each={visibleCompose}>
- {(action) => (
- <ActionButton
- action={action}
- onClick={(event) => {
- void action.onClick?.({ message: message(), event });
- }}
- />
- )}
- </For>
- <Show when={visibleCompose.length > 0 && visibleOther.length > 0}>
- <div class="w-px self-stretch bg-ink/10 mx-1" />
- </Show>
- <For each={visibleOther}>
- {(action) => (
- <ActionButton
- action={action}
- onPointerDown={(event) => {
- if (action.id !== 'reply') return;
- selectedReplyText = getSelectedMessageText(
- event.currentTarget,
- message().id
- );
- renderedReplyText = getRenderedMessageReplyText(
- event.currentTarget,
- message().id
- );
- }}
- onClick={(event) => {
- const selectedText =
- action.id === 'reply'
- ? (selectedReplyText ??
- getSelectedMessageText(
- event.currentTarget,
- message().id
- ))
- : undefined;
- selectedReplyText = undefined;
- const renderedText =
- action.id === 'reply'
- ? (renderedReplyText ??
- getRenderedMessageReplyText(
- event.currentTarget,
- message().id
- ))
- : undefined;
- renderedReplyText = undefined;
- void action.onClick?.({
- message: message(),
- event,
- selectedText,
- renderedText,
- });
- }}
- />
- )}
- </For>
- </div>
- </Layer>
+ <Show when={visibleCompose.length > 0}>
+ <Toolbar.Group>
+ <For each={visibleCompose}>
+ {(action) => (
+ <ActionButton
+ action={action}
+ onClick={(event) => {
+ void action.onClick?.({ message: message(), event });
+ }}
+ />
+ )}
+ </For>
+ </Toolbar.Group>
+ </Show>
+ <Show when={visibleCompose.length > 0 && visibleOther.length > 0}>
+ <Toolbar.Divider />
+ </Show>
+ <Show when={visibleOther.length > 0}>
+ <Toolbar.Group>
+ <For each={visibleOther}>
+ {(action) => (
+ <ActionButton
+ action={action}
+ onPointerDown={(event) => {
+ if (action.id !== 'reply') return;
+ selectedReplyText = getSelectedMessageText(
+ event.currentTarget,
+ message().id
+ );
+ renderedReplyText = getRenderedMessageReplyText(
+ event.currentTarget,
+ message().id
+ );
+ }}
+ onClick={(event) => {
+ const selectedText =
+ action.id === 'reply'
+ ? (selectedReplyText ??
+ getSelectedMessageText(
+ event.currentTarget,
+ message().id
+ ))
+ : undefined;
+ selectedReplyText = undefined;
+ const renderedText =
+ action.id === 'reply'
+ ? (renderedReplyText ??
+ getRenderedMessageReplyText(
+ event.currentTarget,
+ message().id
+ ))
+ : undefined;
+ renderedReplyText = undefined;
+ void action.onClick?.({
+ message: message(),
+ event,
+ selectedText,
+ renderedText,
+ });
+ }}
+ />
+ )}
+ </For>
+ </Toolbar.Group>
+ </Show>
+ </Toolbar>
</HoverActions>
</Show>
);
diff --git a/apps/web/src/features/channel/Message/tests/action-menu.test.tsx b/apps/web/src/features/channel/Message/tests/action-menu.test.tsx
index 3187807c73..5205dcf101 100644
--- a/apps/web/src/features/channel/Message/tests/action-menu.test.tsx
+++ b/apps/web/src/features/channel/Message/tests/action-menu.test.tsx
@@ -41,6 +41,7 @@ describe('ActionMenu', () => {
expect(
container.querySelector('[data-message-hover-actions]')
).not.toBeNull();
+ expect(container.querySelector('[data-slot="toolbar"]')).not.toBeNull();
fireEvent.pointerLeave(root!);
diff --git a/apps/web/src/index.css b/apps/web/src/index.css
index 979706124d..ca51a327ec 100644
--- a/apps/web/src/index.css
+++ b/apps/web/src/index.css
@@ -131,7 +131,7 @@
--layer-inset: var(--color-surface-0);
::selection {
- background-color: oklch(from var(--color-accent) l c h / 0.5);
+ background-color: oklch(from var(--color-ink) l c h / 0.1);
}
}
diff --git a/apps/web/src/lib/core/comments/discussion/configured-discussion-markdown-editor.ts b/apps/web/src/lib/core/comments/discussion/configured-discussion-markdown-editor.ts
index c2bdc41fba..a2e698a13c 100644
--- a/apps/web/src/lib/core/comments/discussion/configured-discussion-markdown-editor.ts
+++ b/apps/web/src/lib/core/comments/discussion/configured-discussion-markdown-editor.ts
@@ -50,7 +50,8 @@ export function createConfiguredDiscussionMarkdownEditor(
.withHistory({ timeGap: 400 })
.withCode()
.withRestoreFocus()
- .withSelectionData();
+ .withSelectionData()
+ .withFloatingFormatMenu();
editor
.use(
diff --git a/apps/web/src/lib/core/component/GeneralizedPopup/Popup.tsx b/apps/web/src/lib/core/component/GeneralizedPopup/Popup.tsx
index 57f5de0170..a198c89cb4 100644
--- a/apps/web/src/lib/core/component/GeneralizedPopup/Popup.tsx
+++ b/apps/web/src/lib/core/component/GeneralizedPopup/Popup.tsx
@@ -1,25 +1,8 @@
-import { type BlockName, isInBlock } from '@core/block';
-import { blockElementSignal } from '@core/signal/blockElement';
-import {
- autoUpdate,
- type Boundary,
- computePosition,
- flip,
- offset,
- shift,
-} from '@floating-ui/dom';
-import { mergeRefs } from '@solid-primitives/refs';
-import { Layer } from '@ui';
-import {
- type Component,
- createEffect,
- createSignal,
- onCleanup,
- type Ref,
-} from 'solid-js';
+import type { BlockName } from '@core/block';
+import type { ParentProps, Ref } from 'solid-js';
+import { PopupPositioner } from './PopupPositioner';
-type GeneralizedPopupProps = {
- PopupComponents: Component;
+type GeneralizedPopupProps = ParentProps<{
anchor: {
ref: HTMLElement;
blockId: string;
@@ -27,58 +10,26 @@ type GeneralizedPopupProps = {
};
useBlockBoundary?: boolean;
ref?: Ref<HTMLDivElement>;
-};
+}>;
+/**
+ * Anchored popup with the legacy surface chrome. Positioning lives in
+ * `PopupPositioner`; new surfaces should prefer the opinionated `Toolbar`
+ * component instead of this container.
+ */
export function GeneralizedPopup(props: GeneralizedPopupProps) {
- const [popupRef, setPopupRef] = createSignal<HTMLDivElement>();
- const [position, setPosition] = createSignal({ x: 0, y: 0 });
-
- let boundary: Boundary = 'clippingAncestors';
- if (props.useBlockBoundary && isInBlock()) {
- const blockEl = blockElementSignal.get;
- boundary = blockEl() ?? 'clippingAncestors';
- }
-
- const updatePosition = async () => {
- const ref = popupRef();
- if (!ref) return;
- const { x, y } = await computePosition(props.anchor.ref, ref, {
- placement: 'bottom',
- middleware: [
- offset(12),
- flip({
- fallbackStrategy: 'initialPlacement',
- boundary,
- }),
- shift({ padding: 8, boundary }),
- ],
- });
-
- setPosition({ x, y });
- };
-
- createEffect(() => {
- const ref = popupRef();
- if (!ref) return;
-
- const cleanup = autoUpdate(props.anchor.ref, ref, updatePosition);
- onCleanup(() => cleanup());
- });
-
return (
- <Layer depth={2}>
+ <PopupPositioner
+ anchor={props.anchor.ref}
+ useBlockBoundary={props.useBlockBoundary}
+ >
<div
- ref={mergeRefs(setPopupRef, props.ref)}
+ ref={props.ref}
id="generalized-popup"
- class="absolute border border-edge bg-surface shadow-xl rounded-lg z-highlight-menu inline-flex items-start flex-col p-1"
- style={{
- left: `${position().x}px`,
- top: `${position().y}px`,
- 'transform-origin': 'top',
- }}
+ class="border border-edge bg-surface shadow-xl rounded-lg z-highlight-menu inline-flex items-start flex-col p-1"
>
- <props.PopupComponents />
+ {props.children}
</div>
- </Layer>
+ </PopupPositioner>
);
}
diff --git a/apps/web/src/lib/core/component/GeneralizedPopup/PopupPositioner.tsx b/apps/web/src/lib/core/component/GeneralizedPopup/PopupPositioner.tsx
new file mode 100644
index 0000000000..a7c275a440
--- /dev/null
+++ b/apps/web/src/lib/core/component/GeneralizedPopup/PopupPositioner.tsx
@@ -0,0 +1,100 @@
+import { isInBlock } from '@core/block';
+import { blockElementSignal } from '@core/signal/blockElement';
+import {
+ autoUpdate,
+ type Boundary,
+ computePosition,
+ flip,
+ offset as offsetMiddleware,
+ type Placement,
+ shift,
+} from '@floating-ui/dom';
+import { mergeRefs } from '@solid-primitives/refs';
+import { Layer } from '@ui';
+import {
+ createEffect,
+ createSignal,
+ type JSX,
+ onCleanup,
+ type Ref,
+} from 'solid-js';
+
+type PopupPositionerProps = {
+ /** Reference element the popup is positioned against. */
+ anchor: HTMLElement;
+ children: JSX.Element;
+ /** Preferred placement relative to the anchor. Defaults to `bottom`. */
+ placement?: Placement;
+ /** Gap between the anchor and the popup, in pixels. Defaults to 12. */
+ offset?: number;
+ /** Padding kept between the popup and the boundary when shifting. Defaults to 8. */
+ shiftPadding?: number;
+ /**
+ * Clip the popup to the surrounding block element rather than the default
+ * clipping ancestors. Only takes effect inside a block context.
+ */
+ useBlockBoundary?: boolean;
+ /** Stacking depth for the floating layer. Defaults to 2. */
+ layerDepth?: 0 | 1 | 2 | 3 | 4;
+ /** Forwarded to the positioned container element. */
+ ref?: Ref<HTMLDivElement>;
+};
+
+/**
+ * Headless positioning wrapper. Anchors its children to a reference element
+ * using floating-ui and keeps them positioned on scroll/resize. It renders no
+ * visual chrome of its own — wrap the children in `Toolbar` (or any other
+ * component) for styling.
+ */
+export function PopupPositioner(props: PopupPositionerProps) {
+ const [popupRef, setPopupRef] = createSignal<HTMLDivElement>();
+ const [position, setPosition] = createSignal({ x: 0, y: 0 });
+
+ let boundary: Boundary = 'clippingAncestors';
+ if (props.useBlockBoundary && isInBlock()) {
+ const blockEl = blockElementSignal.get;
+ boundary = blockEl() ?? 'clippingAncestors';
+ }
+
+ const updatePosition = async () => {
+ const ref = popupRef();
+ if (!ref) return;
+ const { x, y } = await computePosition(props.anchor, ref, {
+ placement: props.placement ?? 'bottom',
+ middleware: [
+ offsetMiddleware(props.offset ?? 12),
+ flip({
+ fallbackStrategy: 'initialPlacement',
+ boundary,
+ }),
+ shift({ padding: props.shiftPadding ?? 8, boundary }),
+ ],
+ });
+
+ setPosition({ x, y });
+ };
+
+ createEffect(() => {
+ const ref = popupRef();
+ if (!ref) return;
+
+ const cleanup = autoUpdate(props.anchor, ref, updatePosition);
+ onCleanup(() => cleanup());
+ });
+
+ return (
+ <Layer depth={props.layerDepth ?? 2}>
+ <div
+ ref={mergeRefs(setPopupRef, props.ref)}
+ class="absolute"
+ style={{
+ left: `${position().x}px`,
+ top: `${position().y}px`,
+ 'transform-origin': 'top',
+ }}
+ >
+ {props.children}
+ </div>
+ </Layer>
+ );
+}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownConfigBuilder.ts b/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownConfigBuilder.ts
index d519d8d92b..c656f0eee9 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownConfigBuilder.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownConfigBuilder.ts
@@ -126,8 +126,8 @@ export class EditorConfigBuilder implements EditorBuilder {
* Implies `.withSelectionData()`. The link button is only shown when
* `.withLinks({ floatingMenu: true })` is also enabled.
*/
- withFloatingFormatMenu(): this {
- this.state.floatingFormatMenu = true;
+ withFloatingFormatMenu(options?: { extendedInlineFormats?: boolean }): this {
+ this.state.floatingFormatMenu = options ?? true;
this.state.selectionData = true;
return this;
}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownShell.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownShell.tsx
index 960b37cc7e..dddd841a32 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownShell.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/builder/MarkdownShell.tsx
@@ -378,6 +378,10 @@ export const MarkdownShell: Component<
<FloatingFormatMenu
portalScope={props.portalScope}
showLinkButton={!!builderConfig.links?.floatingMenu}
+ extendedInlineFormats={
+ typeof builderConfig.floatingFormatMenu === 'object' &&
+ builderConfig.floatingFormatMenu.extendedInlineFormats
+ }
/>
</Show>
</FloatingMenuGroup>
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/builder/types.ts b/apps/web/src/lib/core/component/LexicalMarkdown/builder/types.ts
index d61b49f5f9..aad3a3848d 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/builder/types.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/builder/types.ts
@@ -175,8 +175,12 @@ export interface EditorConfig {
focusLeave?: FocusLeaveCallbacks;
withIds: boolean;
selectionData: boolean;
- /** Show a floating format toolbar over the current text selection. */
- floatingFormatMenu: boolean;
+ /**
+ * Show a floating format toolbar over the current text selection. Pass
+ * `{ extendedInlineFormats: true }` to also offer underline/super/subscript
+ * (only for non-Markdown-backed editors).
+ */
+ floatingFormatMenu: boolean | { extendedInlineFormats?: boolean };
actions: ActionsOptions | false;
/** When true, decorator components skip backend fetches (e.g. preview API). */
skipPreviewFetch: boolean;
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx
index fe9a809a81..c0706f5a53 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx
@@ -131,9 +131,10 @@ interface MarkdownTextareaProps {
autoLinkMatchMode?: AutoLinkMatchMode;
/**
* Show a floating format toolbar (headings, lists, inline styles, links)
- * over the current text selection, like the markdown block's popup.
+ * over the current text selection, like the markdown block's popup. Pass
+ * `{ extendedInlineFormats: true }` to also offer underline/super/subscript.
*/
- floatingFormatMenu?: boolean;
+ floatingFormatMenu?: boolean | { extendedInlineFormats?: boolean };
}
export function MarkdownTextarea(props: MarkdownTextareaProps) {
@@ -413,7 +414,13 @@ export function MarkdownTextarea(props: MarkdownTextareaProps) {
<FloatingMenuGroup>
<FloatingLinkMenu autoLinkMatchMode={props.autoLinkMatchMode} />
<Show when={props.floatingFormatMenu}>
- <FloatingFormatMenu portalScope={props.portalScope} />
+ <FloatingFormatMenu
+ portalScope={props.portalScope}
+ extendedInlineFormats={
+ typeof props.floatingFormatMenu === 'object' &&
+ props.floatingFormatMenu.extendedInlineFormats
+ }
+ />
</Show>
</FloatingMenuGroup>
</div>
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MentionTooltip.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MentionTooltip.test.tsx
new file mode 100644
index 0000000000..3076869ce3
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MentionTooltip.test.tsx
@@ -0,0 +1,29 @@
+/**
+ * @vitest-environment jsdom
+ */
+
+import { render, screen } from '@solidjs/testing-library';
+import { describe, expect, it } from 'vitest';
+import { MentionTooltip } from './MentionTooltip';
+
+describe('MentionTooltip', () => {
+ it('uses the shared tooltip surface and Hotkey rendering', () => {
+ const { container } = render(() => <MentionTooltip show text="Open" />);
+
+ expect(screen.getByText('Open')).toBeTruthy();
+ expect(screen.getByText('↵')).toBeTruthy();
+
+ const surface = container.querySelector('.bg-tooltip');
+ expect(surface?.classList.contains('rounded-lg')).toBe(true);
+ expect(surface?.classList.contains('p-2')).toBe(true);
+ expect(surface?.classList.contains('text-xs')).toBe(true);
+ });
+
+ it('renders nothing when hidden', () => {
+ const { container } = render(() => (
+ <MentionTooltip show={false} text="Open" />
+ ));
+
+ expect(container.innerHTML).toBe('');
+ });
+});
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MentionTooltip.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MentionTooltip.tsx
index ff2dd1841d..1a0526027f 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MentionTooltip.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MentionTooltip.tsx
@@ -1,14 +1,16 @@
-import KeyReturn from '@phosphor/arrow-elbow-down-left.svg';
+import { Hotkey, Surface, tooltipClasses } from '@ui';
import { Show } from 'solid-js';
export function MentionTooltip(props: { show: boolean; text: string }) {
return (
<Show when={props.show}>
- <div class="select-none pointer-events-none absolute z-action-menu top-full flex gap-1 left-0 mt-2 p-1 w-fit whitespace-pre text-surface bg-ink text-xs rounded-xs font-mono">
- <div class="h-4 w-6 text-surface flex flex-row">
- [<KeyReturn />]
- </div>
- {props.text}
+ <div class="pointer-events-none absolute top-full left-0 z-tool-tip mt-1 w-fit whitespace-pre select-none">
+ <Surface class={tooltipClasses({ class: 'h-auto w-fit' })} depth={3}>
+ <div class="flex flex-row items-center gap-2">
+ <div class="text-xs">{props.text}</div>
+ <Hotkey shortcut="enter" theme="subtle" />
+ </div>
+ </Surface>
</div>
</Show>
);
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/FloatingFormatMenu.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/FloatingFormatMenu.tsx
index 4af21f414b..4f8c58e3f8 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/FloatingFormatMenu.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/FloatingFormatMenu.tsx
@@ -8,6 +8,8 @@
import { type PortalScope, ScopedPortal } from '@core/component/ScopedPortal';
import { isMobile } from '@core/mobile/isMobile';
import { debouncedDependent } from '@core/util/debounce';
+import DotsThreeLarge from '@icon/dots-three-large.svg';
+import CaretDown from '@phosphor/caret-down.svg';
import TextCode from '@phosphor/code.svg';
import CodeBlock from '@phosphor/code-block.svg';
import BrokenLinkIcon from '@phosphor/link-break.svg';
@@ -17,9 +19,7 @@ import ListChecks from '@phosphor/list-checks.svg';
import ListNumbers from '@phosphor/list-numbers.svg';
import TextHighlight from '@phosphor/paint-roller.svg';
import Quote from '@phosphor/quotes.svg';
-import TextAA from '@phosphor/text-aa.svg';
import TextBold from '@phosphor/text-b.svg';
-import TextH from '@phosphor/text-h.svg';
import TextH1 from '@phosphor/text-h-one.svg';
import TextH3 from '@phosphor/text-h-three.svg';
import TextH2 from '@phosphor/text-h-two.svg';
@@ -29,7 +29,7 @@ import TextSub from '@phosphor/text-subscript.svg';
import TextSuper from '@phosphor/text-superscript.svg';
import TextT from '@phosphor/text-t.svg';
import TextUnderline from '@phosphor/text-underline.svg';
-import { Button, Dropdown, Layer, SingleSelectCheck } from '@ui';
+import { Button, Dropdown, SingleSelectCheck, Toolbar } from '@ui';
import {
COMMAND_PRIORITY_HIGH,
FORMAT_TEXT_COMMAND,
@@ -79,25 +79,46 @@ type InlineFormat =
| 'superscript'
| 'subscript';
-// Only cmd+b/i/u are registered by Lexical's rich text in MarkdownTextarea,
-// so only those shortcuts are advertised here.
-const InlineFormatOptions: Array<{
+type InlineOption = {
format: InlineFormat;
icon: SvgIcon;
label: string;
shortcut?: string;
-}> = [
+};
+
+// Bold/italic always get their own buttons (cmd+b/i via Lexical rich text).
+const PrimaryInlineOptions: InlineOption[] = [
{ format: 'bold', icon: TextBold, label: 'Bold', shortcut: 'cmd+b' },
{ format: 'italic', icon: TextItalic, label: 'Italic', shortcut: 'cmd+i' },
+];
+
+// Markdown-safe inline formats, shown in the "..." menu. Shortcuts mirror the
+// DefaultShortcuts registered by these editors' keyboardShortcutsPlugin.
+const MoreInlineOptions: InlineOption[] = [
+ {
+ format: 'strikethrough',
+ icon: TextStriketrough,
+ label: 'Strikethrough',
+ shortcut: 'shift+cmd+x',
+ },
+ { format: 'code', icon: TextCode, label: 'Inline code', shortcut: 'cmd+e' },
+ {
+ format: 'highlight',
+ icon: TextHighlight,
+ label: 'Highlight',
+ shortcut: 'shift+cmd+h',
+ },
+];
+
+// Not representable in Markdown; appended to the "..." menu only when the host
+// opts in via `extendedInlineFormats` (e.g. non-Markdown-backed editors).
+const ExtendedInlineOptions: InlineOption[] = [
{
format: 'underline',
icon: TextUnderline,
label: 'Underline',
shortcut: 'cmd+u',
},
- { format: 'strikethrough', icon: TextStriketrough, label: 'Strikethrough' },
- { format: 'code', icon: TextCode, label: 'Inline code' },
- { format: 'highlight', icon: TextHighlight, label: 'Highlight' },
{ format: 'superscript', icon: TextSuper, label: 'Superscript' },
{ format: 'subscript', icon: TextSub, label: 'Subscript' },
];
@@ -120,6 +141,15 @@ const ListOptions: ElementOption[] = [
{ format: 'list-check', icon: ListChecks, label: 'Checklist' },
];
+// The full block-style list, surfaced through the single "Text" dropdown.
+const BlockOptions: ElementOption[] = [
+ { format: 'paragraph', icon: TextT, label: 'Body' },
+ ...HeadingOptions,
+ ...ListOptions,
+ { format: 'code', icon: CodeBlock, label: 'Code' },
+ { format: 'quote', icon: Quote, label: 'Quote' },
+];
+
export function FloatingFormatMenu(props: {
portalScope?: PortalScope;
/**
@@ -128,6 +158,11 @@ export function FloatingFormatMenu(props: {
* mounted alongside this menu. Defaults to true.
*/
showLinkButton?: boolean;
+ /**
+ * Include underline / super / subscript in the "..." menu. These can't be
+ * represented in Markdown, so leave off for Markdown-backed editors.
+ */
+ extendedInlineFormats?: boolean;
}) {
const lexicalWrapper = useContext(LexicalWrapperContext);
if (!lexicalWrapper) {
@@ -224,64 +259,129 @@ export function FloatingFormatMenu(props: {
return info?.type === 'range' ? info.domSelection : undefined;
};
+ const moreInlineOptions = () =>
+ props.extendedInlineFormats
+ ? [...MoreInlineOptions, ...ExtendedInlineOptions]
+ : MoreInlineOptions;
+
+ const InlineButton = (buttonProps: { item: InlineOption }) => (
+ <Button
+ label={buttonProps.item.label}
+ shortcut={buttonProps.item.shortcut}
+ size="icon-sm"
+ class="rounded-md"
+ depth={3}
+ variant={selection()?.[buttonProps.item.format] ? 'accent' : 'ghost'}
+ onPointerDown={(e: PointerEvent) => e.preventDefault()}
+ onClick={(e: MouseEvent | KeyboardEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ inlineFormat(buttonProps.item.format);
+ }}
+ >
+ <Dynamic component={buttonProps.item.icon} />
+ </Button>
+ );
+
+ // The remaining inline formats, opened as a horizontal row of buttons.
+ const MoreInlineDropdown = () => {
+ const [open, setOpen] = createSignal(false);
+ return (
+ <Dropdown open={open()} onOpenChange={setOpen}>
+ <Dropdown.Trigger
+ variant="ghost"
+ size="icon-sm"
+ class="rounded-md"
+ depth={3}
+ tooltip="More formatting"
+ tabIndex={-1}
+ >
+ <DotsThreeLarge />
+ </Dropdown.Trigger>
+ <Dropdown.Content onCloseAutoFocus={refocusEditor}>
+ <Dropdown.Group>
+ <div class="flex items-center gap-1">
+ <For each={moreInlineOptions()}>
+ {(item) => <InlineButton item={item} />}
+ </For>
+ </div>
+ </Dropdown.Group>
+ </Dropdown.Content>
+ </Dropdown>
+ );
+ };
+
+ // A single "Text" trigger that reflects the selected block and opens the
+ // block-style menu.
+ const TextBlockDropdown = () => {
+ const [open, setOpen] = createSignal(false);
+ const currentLabel = () => {
+ const active = BlockOptions.filter((option) =>
+ selection()?.elementsInRange?.has(option.format)
+ );
+ return active.length === 1 ? active[0].label : 'Text';
+ };
+ return (
+ <Dropdown open={open()} onOpenChange={setOpen}>
+ <Dropdown.Trigger
+ variant="ghost"
+ size="sm"
+ class="gap-1 rounded-md"
+ depth={3}
+ tooltip="Text style"
+ tabIndex={-1}
+ >
+ {currentLabel()}
+ <CaretDown class="size-3" />
+ </Dropdown.Trigger>
+ <Dropdown.Content class="text-xs" onCloseAutoFocus={refocusEditor}>
+ <Dropdown.Group>
+ <For each={BlockOptions}>
+ {(item) => {
+ const isActive = () =>
+ !!selection()?.elementsInRange?.has(item.format);
+ return (
+ <Dropdown.Item
+ onSelect={() => {
+ nodeFormat(item.format);
+ setOpen(false);
+ }}
+ class={isActive() ? 'text-ink' : ''}
+ role="menuitemradio"
+ aria-checked={isActive()}
+ >
+ <Dynamic component={item.icon} class="size-4 shrink-0" />
+ <span class="flex-1 truncate">{item.label}</span>
+ <SingleSelectCheck active={isActive()} />
+ </Dropdown.Item>
+ );
+ }}
+ </For>
+ </Dropdown.Group>
+ </Dropdown.Content>
+ </Dropdown>
+ );
+ };
+
return (
<Show
when={showMenu() && lexicalWrapper.isInteractable() && domSelection()}
>
<ScopedPortal scope={props.portalScope}>
- <Layer depth={2}>
- <div
- ref={setMenuRef}
- class="fixed top-0 left-0 z-highlight-menu border border-edge bg-surface shadow-xl rounded-lg p-1 flex flex-row items-center gap-1"
- use:floatWithSelection={{
- selection: domSelection(),
- reactiveOnContainer: editor.getRootElement(),
- useBlockBoundary: true,
- moveWithSelection: true,
- }}
- >
- <ElementFormatButton
- format="paragraph"
- icon={TextT}
- label="Body"
- selection={selection}
- onFormat={nodeFormat}
- />
- <ElementFormatMenu
- items={HeadingOptions}
- icon={TextH}
- label="Headings"
- selection={selection}
- onFormat={nodeFormat}
- onCloseAutoFocus={refocusEditor}
- />
- <ElementFormatMenu
- items={ListOptions}
- icon={ListBullets}
- label="Lists"
- selection={selection}
- onFormat={nodeFormat}
- onCloseAutoFocus={refocusEditor}
- />
- <ElementFormatButton
- format="code"
- icon={CodeBlock}
- label="Code"
- selection={selection}
- onFormat={nodeFormat}
- />
- <ElementFormatButton
- format="quote"
- icon={Quote}
- label="Quote"
- selection={selection}
- onFormat={nodeFormat}
- />
- <InlineFormatMenu
- selection={selection}
- onFormat={inlineFormat}
- onCloseAutoFocus={refocusEditor}
- />
+ <div
+ ref={setMenuRef}
+ class="fixed top-0 left-0 z-highlight-menu w-fit"
+ use:floatWithSelection={{
+ selection: domSelection(),
+ reactiveOnContainer: editor.getRootElement(),
+ useBlockBoundary: true,
+ moveWithSelection: true,
+ }}
+ >
+ <Toolbar>
+ <For each={PrimaryInlineOptions}>
+ {(item) => <InlineButton item={item} />}
+ </For>
<Show when={props.showLinkButton ?? true}>
<Button
variant="ghost"
@@ -297,139 +397,12 @@ export function FloatingFormatMenu(props: {
/>
</Button>
</Show>
- </div>
- </Layer>
+ <MoreInlineDropdown />
+ <Toolbar.Divider />
+ <TextBlockDropdown />
+ </Toolbar>
+ </div>
</ScopedPortal>
</Show>
);
}
-
-function ElementFormatButton(props: {
- format: NodeTransformType;
- icon: SvgIcon;
- label: string;
- selection: () => SelectionData | undefined;
- onFormat: (format: NodeTransformType) => void;
-}) {
- const isActive = () =>
- !!props.selection()?.elementsInRange?.has(props.format);
- return (
- <Button
- tooltip={props.label}
- size="icon-sm"
- class="rounded-md"
- depth={3}
- variant={isActive() ? 'accent' : 'ghost'}
- onPointerDown={(e: PointerEvent) => e.preventDefault()}
- onClick={(e: MouseEvent | KeyboardEvent) => {
- e.preventDefault();
- e.stopPropagation();
- props.onFormat(props.format);
- }}
- >
- <Dynamic component={props.icon} />
- </Button>
- );
-}
-
-function ElementFormatMenu(props: {
- items: ElementOption[];
- icon: SvgIcon;
- label: string;
- selection: () => SelectionData | undefined;
- onFormat: (format: NodeTransformType) => void;
- onCloseAutoFocus: () => void;
-}) {
- const isAnyActive = () =>
- props.items.some((item) =>
- props.selection()?.elementsInRange?.has(item.format)
- );
- return (
- <Dropdown>
- <Dropdown.Trigger
- variant={isAnyActive() ? 'accent' : 'ghost'}
- size="icon-sm"
- class="rounded-md"
- depth={3}
- tooltip={props.label}
- tabIndex={-1}
- >
- <Dynamic component={props.icon} />
- </Dropdown.Trigger>
- <Dropdown.Content onCloseAutoFocus={props.onCloseAutoFocus}>
- <Dropdown.Group>
- <For each={props.items}>
- {(item) => {
- const isActive = () =>
- !!props.selection()?.elementsInRange?.has(item.format);
- return (
- <Dropdown.Item
- onSelect={() => props.onFormat(item.format)}
- class={isActive() ? 'text-ink' : ''}
- role="menuitemradio"
- aria-checked={isActive()}
- >
- <Dynamic component={item.icon} class="size-4 shrink-0" />
- <span class="flex-1 truncate">{item.label}</span>
- <SingleSelectCheck active={isActive()} />
- </Dropdown.Item>
- );
- }}
- </For>
- </Dropdown.Group>
- </Dropdown.Content>
- </Dropdown>
- );
-}
-
-function InlineFormatMenu(props: {
- selection: () => SelectionData | undefined;
- onFormat: (format: InlineFormat) => void;
- onCloseAutoFocus: () => void;
-}) {
- const [open, setOpen] = createSignal(false);
- const isAnyActive = () =>
- InlineFormatOptions.some((item) => props.selection()?.[item.format]);
- return (
- <Dropdown open={open()} onOpenChange={setOpen}>
- <Dropdown.Trigger
- variant={isAnyActive() ? 'accent' : 'ghost'}
- size="icon-sm"
- class="rounded-md"
- depth={3}
- tooltip="Text Styles"
- tabIndex={-1}
- >
- <TextAA />
- </Dropdown.Trigger>
- <Dropdown.Content onCloseAutoFocus={props.onCloseAutoFocus}>
- <Dropdown.Group>
- <div class="w-full flex gap-1 justify-center items-center">
- <For each={InlineFormatOptions}>
- {(item) => (
- <Button
- label={item.label}
- shortcut={item.shortcut}
- size="icon-sm"
- variant={
- props.selection()?.[item.format] ? 'accent' : 'ghost'
- }
- class="rounded-md"
- depth={3}
- onClick={(e: MouseEvent | KeyboardEvent) => {
- e.preventDefault();
- e.stopPropagation();
- props.onFormat(item.format);
- setOpen(false);
- }}
- >
- <Dynamic component={item.icon} />
- </Button>
- )}
- </For>
- </div>
- </Dropdown.Group>
- </Dropdown.Content>
- </Dropdown>
- );
-}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/linksPlugin.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/linksPlugin.test.ts
index 14d31fdd2f..3a24e8ec66 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/linksPlugin.test.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/linksPlugin.test.ts
@@ -1,6 +1,42 @@
import { describe, expect, it } from 'vitest';
-import { findNextAutoLinkMatch } from './linksPlugin';
+import { findNextAutoLinkMatch, normalizeLinkUrl } from './linksPlugin';
+
+describe('normalizeLinkUrl', () => {
+ it('normalizes bare hosts to HTTPS', () => {
+ expect(normalizeLinkUrl(' example.com/path with spaces ')).toBe(
+ 'https://example.com/path%20with%20spaces'
+ );
+ });
+
+ it('allows HTTP, HTTPS, and mailto links', () => {
+ expect(normalizeLinkUrl('http://example.com/path')).toBe(
+ 'http://example.com/path'
+ );
+ expect(normalizeLinkUrl('https://example.com/path')).toBe(
+ 'https://example.com/path'
+ );
+ expect(normalizeLinkUrl('mailto:[email protected]')).toBe(
+ );
+ });
+
+ it.each([
+ 'javascript://alert(1)',
+ 'javascript:alert(1)',
+ 'java\nscript:alert(1)',
+ 'data:text/html,unsafe',
+ 'file:///tmp/secret',
+ 'ftp://example.com',
+ ])('rejects a disallowed URL scheme: %s', (url) => {
+ expect(normalizeLinkUrl(url)).toBeNull();
+ });
+
+ it('rejects empty and malformed URLs', () => {
+ expect(normalizeLinkUrl('')).toBeNull();
+ expect(normalizeLinkUrl('https://')).toBeNull();
+ });
+});
describe('findNextAutoLinkMatch', () => {
it('requires a protocol in protocol mode', () => {
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/linksPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/linksPlugin.ts
index 98d6b6f8a0..698e79f27d 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/linksPlugin.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/linksPlugin.ts
@@ -82,27 +82,45 @@ function getAutoLinkifier(mode: AutoLinkMatchMode) {
}
}
-/*
- * Basic URL cleaning.
- */
-function cleanURL(input: string) {
- let url = input.trim();
-
- if (!url.match(/^[a-zA-Z]+:\/\//)) {
- url = 'https://' + url;
- }
+const ALLOWED_LINK_PROTOCOLS = new Set(['http:', 'https:', 'mailto:']);
+const URL_SCHEME_PATTERN = /^([a-z][a-z\d+.-]*):/i;
- const [basePath, ...queryParts] = url.split(/([#?])/);
-
- const encodedBase = basePath
- .split('/')
- .map((segment) => (segment.includes(':') ? segment : encodeURI(segment)))
- .join('/');
-
- if (queryParts.length) {
+/**
+ * Normalize user-entered links and reject protocols that links must not open.
+ * Bare hosts retain the existing behavior of defaulting to HTTPS.
+ */
+export function normalizeLinkUrl(input: string): string | null {
+ const trimmed = input.trim();
+ if (!trimmed) return null;
+
+ // The URL parser ignores ASCII tabs and newlines in protocols. Use the same
+ // view when detecting a scheme so values such as `java\nscript:` cannot be
+ // mistaken for a bare host and rewritten as HTTPS.
+ const schemeProbe = trimmed.replace(/[\t\n\r]/g, '');
+ const schemeMatch = URL_SCHEME_PATTERN.exec(schemeProbe);
+ const scheme = schemeMatch?.[1]?.toLowerCase();
+ const remainder = schemeMatch ? schemeProbe.slice(schemeMatch[0].length) : '';
+ const isHostWithPort =
+ scheme !== undefined &&
+ (scheme === 'localhost' || scheme.includes('.')) &&
+ /^\d+(?:[/?#]|$)/.test(remainder);
+ const candidate = scheme && !isHostWithPort ? trimmed : `https://${trimmed}`;
+
+ try {
+ const parsed = new URL(candidate);
+ if (!ALLOWED_LINK_PROTOCOLS.has(parsed.protocol)) return null;
+
+ if (parsed.protocol === 'mailto:') return trimmed;
+
+ const [basePath, ...queryParts] = candidate.split(/([#?])/);
+ const encodedBase = basePath
+ .split('/')
+ .map((segment) => (segment.includes(':') ? segment : encodeURI(segment)))
+ .join('/');
return encodedBase + queryParts.join('');
+ } catch {
+ return null;
}
- return encodedBase;
}
/**
@@ -174,9 +192,11 @@ export function findNextAutoLinkMatch(
const match = linkifier.match(text);
if (!match) return null;
const firstMatch = match[0];
- if (firstMatch.schema === '') {
- firstMatch.url = cleanURL(firstMatch.raw);
- }
+ const url = normalizeLinkUrl(
+ firstMatch.schema === '' ? firstMatch.raw : firstMatch.url
+ );
+ if (!url) return null;
+ firstMatch.url = url;
return firstMatch;
}
@@ -509,10 +529,12 @@ function registerLinksPlugin(editor: LexicalEditor, props: LinkPluginProps) {
const clipboardText = e.clipboardData?.getData('text/plain');
if (!clipboardText || !strictLinkifier.matchAtStart(clipboardText))
return false;
+ const url = normalizeLinkUrl(clipboardText);
+ if (!url) return false;
const selection = $getSelection();
if (!$isRangeSelection(selection) || selection.isCollapsed())
return false;
- $toggleLink(clipboardText);
+ $toggleLink(url);
return true;
},
COMMAND_PRIORITY_NORMAL
@@ -534,8 +556,8 @@ function registerLinksPlugin(editor: LexicalEditor, props: LinkPluginProps) {
UPDATE_LINK_URL_COMMAND,
(payload) => {
if (payload === null) return false;
- if (!fuzzyLinkifier.test(payload)) return false;
- const url = cleanURL(payload);
+ const url = normalizeLinkUrl(payload);
+ if (!url) return false;
const selection = $getSelection();
if (!$isRangeSelection(selection)) return false;
@@ -561,10 +583,8 @@ function registerLinksPlugin(editor: LexicalEditor, props: LinkPluginProps) {
if (payload.url === undefined || payload.linkText === undefined) {
return false;
}
- const url = cleanURL(payload.url);
- if (!strictLinkifier.test(url)) {
- return false;
- }
+ const url = normalizeLinkUrl(payload.url);
+ if (!url) return false;
const selection = $getSelection();
if (!$isRangeSelection(selection)) return false;
@@ -613,7 +633,8 @@ function registerLinksPlugin(editor: LexicalEditor, props: LinkPluginProps) {
editor.registerCommand(
INSERT_LINK_COMMAND,
(payload) => {
- const url = cleanURL(payload.url);
+ const url = normalizeLinkUrl(payload.url);
+ if (!url) return false;
const linkNode = $createLinkNode(url);
linkNode.append($createTextNode(payload.linkText));
$insertNodes([linkNode]);
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/styles.css b/apps/web/src/lib/core/component/LexicalMarkdown/styles.css
index 2b913b2086..01b0e6bebf 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/styles.css
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/styles.css
@@ -228,6 +228,33 @@ ol.static-md.depth-6 > li:not(.list-none)::before {
text-decoration-thickness: max(0.1em, 1px);
}
+.md-subscript,
+.md-superscript {
+ font-size: 75%;
+ line-height: 0;
+ position: relative;
+ vertical-align: baseline;
+}
+
+.md-subscript {
+ bottom: -0.25em;
+}
+
+.md-superscript {
+ top: -0.5em;
+}
+
+/* Active editors already get semantic sub/sup wrappers from Lexical. */
+sub > .md-subscript,
+sup > .md-superscript {
+ bottom: auto;
+ font-size: inherit;
+ line-height: inherit;
+ position: static;
+ top: auto;
+ vertical-align: inherit;
+}
+
.md-inline-mention > div {
display: contents;
}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/theme.ts b/apps/web/src/lib/core/component/LexicalMarkdown/theme.ts
index a1acdcfd03..34c6a12cfc 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/theme.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/theme.ts
@@ -45,6 +45,8 @@ export const theme: EditorThemeClasses = {
code: 'bg-code-buffer font-mono rounded-xs md-inline-code p-0.5',
strikethrough: 'md-strike',
underline: 'md-underline',
+ subscript: 'md-subscript',
+ superscript: 'md-superscript',
highlight: 'text-accent font-semibold',
},
paragraph: `${VERTICAL_GAP} md-p text-[1em]`,
diff --git a/packages/lexical-core/tests/html-text-formats.test.ts b/packages/lexical-core/tests/html-text-formats.test.ts
new file mode 100644
index 0000000000..78d7f442c8
--- /dev/null
+++ b/packages/lexical-core/tests/html-text-formats.test.ts
@@ -0,0 +1,179 @@
+import { createHeadlessEditor } from '@lexical/headless';
+import {
+ $convertFromMarkdownString,
+ $convertSelectionToMarkdownString,
+ $convertToMarkdownString,
+ type Transformer,
+} from '@lexical/markdown';
+import {
+ $createParagraphNode,
+ $createTextNode,
+ $getRoot,
+ $getSelection,
+ type TextFormatType,
+} from 'lexical';
+import { describe, expect, it } from 'vitest';
+import { SupportedNodeTypes } from '../node-list';
+import {
+ ALL_TRANSFORMERS,
+ EXTERNAL_TRANSFORMERS,
+ INTERNAL_TRANSFORMERS,
+} from '../transformers';
+
+type TextSpec = {
+ formats: TextFormatType[];
+ text: string;
+};
+
+function createEditorFromText(specs: TextSpec[]) {
+ const editor = createHeadlessEditor({ nodes: [...SupportedNodeTypes] });
+ editor.update(
+ () => {
+ const paragraph = $createParagraphNode();
+ for (const { formats, text } of specs) {
+ const textNode = $createTextNode(text);
+ for (const format of formats) {
+ textNode.toggleFormat(format);
+ }
+ paragraph.append(textNode);
+ }
+ $getRoot().append(paragraph);
+ },
+ { discrete: true }
+ );
+ return editor;
+}
+
+function importMarkdown(markdown: string, transformers: Transformer[]) {
+ const editor = createHeadlessEditor({ nodes: [...SupportedNodeTypes] });
+ editor.update(() => $convertFromMarkdownString(markdown, transformers), {
+ discrete: true,
+ });
+ return editor;
+}
+
+function exportMarkdown(
+ editor: ReturnType<typeof createHeadlessEditor>,
+ transformers: Transformer[]
+) {
+ return editor
+ .getEditorState()
+ .read(() => $convertToMarkdownString(transformers));
+}
+
+function readTextSpecs(editor: ReturnType<typeof createHeadlessEditor>) {
+ return editor.getEditorState().read(() =>
+ $getRoot()
+ .getAllTextNodes()
+ .map((node) => ({
+ formats: [
+ 'bold',
+ 'italic',
+ 'underline',
+ 'superscript',
+ 'subscript',
+ ].filter((format): format is TextFormatType => node.hasFormat(format)),
+ text: node.getTextContent(),
+ }))
+ );
+}
+
+function readNonWhitespaceTextSpecs(
+ editor: ReturnType<typeof createHeadlessEditor>
+) {
+ return readTextSpecs(editor)
+ .map(({ formats, text }) => ({ formats, text: text.trim() }))
+ .filter(({ text }) => text !== '');
+}
+
+describe('HTML text format Markdown transformers', () => {
+ it.each([
+ ['underline', '<u>underline</u>'],
+ ['superscript', '<sup>superscript</sup>'],
+ ['subscript', '<sub>subscript</sub>'],
+ ] as const)('serializes %s with paired HTML tags', (format, markdown) => {
+ const editor = createEditorFromText([{ formats: [format], text: format }]);
+
+ expect(exportMarkdown(editor, INTERNAL_TRANSFORMERS)).toBe(markdown);
+ expect(exportMarkdown(editor, EXTERNAL_TRANSFORMERS)).toBe(markdown);
+ });
+
+ it('imports paired HTML tags as Lexical formats', () => {
+ const markdown =
+ '<u>underlined</u> <sup>superscript</sup> <sub>subscript</sub>';
+ const editor = importMarkdown(markdown, ALL_TRANSFORMERS);
+
+ expect(readTextSpecs(editor)).toEqual([
+ { formats: ['underline'], text: 'underlined' },
+ { formats: [], text: ' ' },
+ { formats: ['superscript'], text: 'superscript' },
+ { formats: [], text: ' ' },
+ { formats: ['subscript'], text: 'subscript' },
+ ]);
+ });
+
+ it('round-trips nested HTML and standard Markdown formats', () => {
+ const markdown = '<u>plain **bold <sup>and raised</sup>**</u>';
+ const imported = importMarkdown(markdown, ALL_TRANSFORMERS);
+ const serialized = exportMarkdown(imported, INTERNAL_TRANSFORMERS);
+ const roundTripped = importMarkdown(serialized, ALL_TRANSFORMERS);
+
+ expect(
+ roundTripped.getEditorState().read(() => $getRoot().getTextContent())
+ ).toBe(imported.getEditorState().read(() => $getRoot().getTextContent()));
+ expect(readNonWhitespaceTextSpecs(roundTripped)).toEqual(
+ readNonWhitespaceTextSpecs(imported)
+ );
+ });
+
+ it('keeps Markdown delimiters within HTML format boundaries', () => {
+ const editor = createEditorFromText([
+ { formats: ['bold'], text: 'bold ' },
+ { formats: ['bold', 'underline'], text: 'and underlined' },
+ { formats: ['italic', 'superscript'], text: ' raised' },
+ { formats: ['italic'], text: ' and italic' },
+ ]);
+ const serialized = exportMarkdown(editor, INTERNAL_TRANSFORMERS);
+ const roundTripped = importMarkdown(serialized, ALL_TRANSFORMERS);
+
+ expect(serialized).toContain('**bold <u>and underlined</u>**');
+ expect(serialized).toContain('*<sup>raised</sup> and italic*');
+ expect(readNonWhitespaceTextSpecs(roundTripped)).toEqual(
+ readNonWhitespaceTextSpecs(editor)
+ );
+ });
+
+ it('round-trips HTML text formats inside external Markdown tables', () => {
+ const markdown = '| <u>underlined</u> |\n| --- |';
+ const imported = importMarkdown(markdown, EXTERNAL_TRANSFORMERS);
+
+ expect(exportMarkdown(imported, EXTERNAL_TRANSFORMERS)).toContain(
+ '<u>underlined</u>'
+ );
+ });
+
+ it('serializes only the selected part of formatted text', () => {
+ const editor = createEditorFromText([
+ { formats: [], text: 'before ' },
+ { formats: ['underline'], text: 'underlined' },
+ { formats: [], text: ' after' },
+ ]);
+
+ editor.update(
+ () => {
+ $getRoot().getAllTextNodes()[1].select(2, 6);
+ },
+ { discrete: true }
+ );
+
+ expect(
+ editor.read(() => {
+ const selection = $getSelection();
+ return $convertSelectionToMarkdownString(
+ INTERNAL_TRANSFORMERS,
+ selection
+ );
+ })
+ ).toBe('<u>derl</u>');
+ });
+});
diff --git a/packages/lexical-core/transformers/customTransformers.ts b/packages/lexical-core/transformers/customTransformers.ts
index 3ecc9087ce..3bff6664e0 100644
--- a/packages/lexical-core/transformers/customTransformers.ts
+++ b/packages/lexical-core/transformers/customTransformers.ts
@@ -9,6 +9,7 @@ import {
} from '@lexical/markdown';
import { $isHeadingNode } from '@lexical/rich-text';
import { $isElementNode, type ElementNode, type LexicalNode } from 'lexical';
+import { HTML_TEXT_FORMAT_TRANSFORMERS } from './htmlTextFormats';
const customTransformer = (
original: ElementTransformer
@@ -46,6 +47,7 @@ const customTransformer = (
};
export const CUSTOM_TRANSFORMERS: Transformer[] = [
+ ...HTML_TEXT_FORMAT_TRANSFORMERS,
...TRANSFORMERS.filter((t) => {
return t !== CHECK_LIST && t !== ORDERED_LIST && t !== UNORDERED_LIST;
}),
diff --git a/packages/lexical-core/transformers/htmlTextFormats.ts b/packages/lexical-core/transformers/htmlTextFormats.ts
new file mode 100644
index 0000000000..e2a5d53f31
--- /dev/null
+++ b/packages/lexical-core/transformers/htmlTextFormats.ts
@@ -0,0 +1,123 @@
+import {
+ TEXT_FORMAT_TRANSFORMERS,
+ type TextMatchTransformer,
+} from '@lexical/markdown';
+import {
+ $isTextNode,
+ type LexicalNode,
+ type TextFormatType,
+ type TextNode,
+} from 'lexical';
+
+type HtmlTextFormat = {
+ format: TextFormatType;
+ closeTag: string;
+ openTag: string;
+};
+
+const HTML_TEXT_FORMATS: HtmlTextFormat[] = [
+ { closeTag: '</u>', format: 'underline', openTag: '<u>' },
+ { closeTag: '</sup>', format: 'superscript', openTag: '<sup>' },
+ { closeTag: '</sub>', format: 'subscript', openTag: '<sub>' },
+];
+
+const MARKDOWN_TEXT_TAGS = [
+ ...new Set(
+ TEXT_FORMAT_TRANSFORMERS.filter(({ format }) => format.length === 1).map(
+ ({ tag }) => tag
+ )
+ ),
+].sort((left, right) => right.length - left.length);
+
+function wrapInsideMarkdownTags(content: string, node: TextNode): string {
+ let inner = content;
+ let prefix = '';
+ let suffix = '';
+
+ while (inner !== '') {
+ const whitespace = inner.match(/^\s+/)?.[0];
+ const tag = MARKDOWN_TEXT_TAGS.find((candidate) =>
+ inner.startsWith(candidate)
+ );
+ const boundary = whitespace ?? tag;
+ if (!boundary) break;
+ prefix += boundary;
+ inner = inner.slice(boundary.length);
+ }
+
+ while (inner !== '') {
+ const whitespace = inner.match(/\s+$/)?.[0];
+ const tag = MARKDOWN_TEXT_TAGS.find((candidate) =>
+ inner.endsWith(candidate)
+ );
+ const boundary = whitespace ?? tag;
+ if (!boundary) break;
+ suffix = boundary + suffix;
+ inner = inner.slice(0, -boundary.length);
+ }
+
+ const formats = HTML_TEXT_FORMATS.filter(({ format }) =>
+ node.hasFormat(format)
+ );
+ const openingTags = formats.map(({ openTag }) => openTag).join('');
+ const closingTags = formats
+ .toReversed()
+ .map(({ closeTag }) => closeTag)
+ .join('');
+
+ return `${prefix}${openingTags}${inner}${closingTags}${suffix}`;
+}
+
+function createHtmlTextFormatImporter({
+ format,
+ openTag,
+}: HtmlTextFormat): TextMatchTransformer {
+ const tag = openTag.slice(1, -1);
+ const regExp = new RegExp(`<${tag}>(.*?)</${tag}>`, 'i');
+
+ return {
+ dependencies: [],
+ importRegExp: regExp,
+ regExp,
+ replace: (textNode: TextNode, match: RegExpMatchArray) => {
+ textNode.setTextContent(match[1]);
+ if (!textNode.hasFormat(format)) {
+ textNode.toggleFormat(format);
+ }
+ return textNode;
+ },
+ type: 'text-match',
+ };
+}
+
+/** Imports paired HTML tags into their corresponding Lexical text formats. */
+export const HTML_TEXT_FORMAT_IMPORTERS = HTML_TEXT_FORMATS.map(
+ createHtmlTextFormatImporter
+);
+
+/**
+ * Serializes Lexical formats whose Markdown representation uses paired HTML
+ * tags. Lexical's text-format transformers only support symmetric delimiters,
+ * so these formats must be handled as a text-match export instead.
+ */
+export const HTML_TEXT_FORMAT_EXPORTER: TextMatchTransformer = {
+ dependencies: [],
+ export: (node: LexicalNode, _exportChildren, exportFormat): string | null => {
+ if (!$isTextNode(node)) return null;
+ if (!HTML_TEXT_FORMATS.some(({ format }) => node.hasFormat(format))) {
+ return null;
+ }
+
+ return wrapInsideMarkdownTags(
+ exportFormat(node, node.getTextContent()),
+ node
+ );
+ },
+ regExp: /$a/,
+ type: 'text-match',
+};
+
+export const HTML_TEXT_FORMAT_TRANSFORMERS = [
+ HTML_TEXT_FORMAT_EXPORTER,
+ ...HTML_TEXT_FORMAT_IMPORTERS,
+];
diff --git a/packages/lexical-core/transformers/tables.ts b/packages/lexical-core/transformers/tables.ts
index 41e7c5114e..48f7b959e5 100644
--- a/packages/lexical-core/transformers/tables.ts
+++ b/packages/lexical-core/transformers/tables.ts
@@ -21,6 +21,7 @@ import {
import { $isParagraphNode, $isTextNode, type LexicalNode } from "lexical";
import { z } from "zod";
import { CUSTOM_TRANSFORMERS } from "./customTransformers";
+import { HTML_TEXT_FORMAT_TRANSFORMERS } from "./htmlTextFormats";
import { I_IMAGE_CONSTRAINED, IMAGE } from "./image";
import { E_BLOCK_EQUATION_NODE, I_EQUATION_NODE } from "./katex";
import {
@@ -102,6 +103,7 @@ const internalTransformersWithinTables: Transformer[] = [
I_IMAGE_CONSTRAINED,
IMAGE,
I_VIDEO,
+ ...HTML_TEXT_FORMAT_TRANSFORMERS,
...TRANSFORMERS,
];
@@ -251,6 +253,7 @@ const externalTransformersWithinTables: Transformer[] = [
IMAGE,
I_VIDEO,
...HTML_ENTITY_TRANSFORMERS,
+ ...HTML_TEXT_FORMAT_TRANSFORMERS,
...TRANSFORMERS,
];