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.

23.1 KB
Raw Blame
import ArrowClockwise from '@icon/system/regular/arrow-clockwise.svg';
import ArrowCounterClockwise from '@icon/system/regular/arrow-counter-clockwise.svg';
import ArrowsDownUp from '@icon/system/regular/arrows-down-up.svg';
import AsteriskSimple from '@icon/system/regular/asterisk-simple.svg';
import ChatCircleText from '@icon/system/regular/chat-circle-text.svg';
import Check from '@icon/system/regular/check.svg';
import Checks from '@icon/system/regular/checks.svg';
import Eye from '@icon/system/regular/eye.svg';
import EyeSlash from '@icon/system/regular/eye-slash.svg';
import GitDiff from '@icon/system/regular/git-diff.svg';
import Highlighter from '@icon/system/regular/highlighter.svg';
import ListBullets from '@icon/system/regular/list-bullets.svg';
import ListNumbers from '@icon/system/regular/list-numbers.svg';
import MagnifyingGlass from '@icon/system/regular/magnifying-glass.svg';
import RowsPlusBottom from '@icon/system/regular/rows-plus-bottom.svg';
import Table from '@icon/system/regular/table.svg';
import TextAUnderline from '@icon/system/regular/text-a-underline.svg';
import TextAlignCenter from '@icon/system/regular/text-align-center.svg';
import TextAlignJustify from '@icon/system/regular/text-align-justify.svg';
import TextAlignLeft from '@icon/system/regular/text-align-left.svg';
import TextAlignRight from '@icon/system/regular/text-align-right.svg';
import TextB from '@icon/system/regular/text-b.svg';
import TextIndent from '@icon/system/regular/text-indent.svg';
import TextItalic from '@icon/system/regular/text-italic.svg';
import TextOutdent from '@icon/system/regular/text-outdent.svg';
import TextStrikethrough from '@icon/system/regular/text-strikethrough.svg';
import TextSubscript from '@icon/system/regular/text-subscript.svg';
import TextSuperscript from '@icon/system/regular/text-superscript.svg';
import TextTSlash from '@icon/system/regular/text-t-slash.svg';
import TextUnderline from '@icon/system/regular/text-underline.svg';
import X from '@icon/system/regular/x.svg';
import XCircle from '@icon/system/regular/x-circle.svg';
import { Dropdown } from '@ui/components/Dropdown';
import { Toolbar } from '@ui/components/Toolbar';
import { For, type JSX, Show } from 'solid-js';

export type DocxInlineFormat =
  | 'bold'
  | 'italic'
  | 'underline'
  | 'strike'
  | 'superscript'
  | 'subscript';
/** Table row and column commands. */
export type DocxTableOp =
  | 'rowAbove'
  | 'rowBelow'
  | 'columnLeft'
  | 'columnRight'
  | 'deleteRow'
  | 'deleteColumn'
  | 'deleteTable';
export type DocxAlignment = 'left' | 'center' | 'right' | 'justify';
export type DocxParagraphStyle = { id: string; name: string };

/** Font sizes offered in the size picker (points). */
const FONT_SIZES = [8, 9, 10, 10.5, 11, 12, 14, 16, 18, 20, 24, 28, 36, 48, 72];

/** Font families offered in the font picker. */
const FONT_FAMILIES = [
  'Arial',
  'Calibri',
  'Cambria',
  'Courier New',
  'Garamond',
  'Georgia',
  'Segoe UI',
  'Tahoma',
  'Times New Roman',
  'Verdana',
];

/** Word's standard text colors (`RRGGBB`). */
const TEXT_COLORS: Array<{ name: string; hex: string }> = [
  { name: 'Black', hex: '000000' },
  { name: 'Dark red', hex: 'C00000' },
  { name: 'Red', hex: 'FF0000' },
  { name: 'Orange', hex: 'FFC000' },
  { name: 'Yellow', hex: 'FFFF00' },
  { name: 'Light green', hex: '92D050' },
  { name: 'Green', hex: '00B050' },
  { name: 'Light blue', hex: '00B0F0' },
  { name: 'Blue', hex: '0070C0' },
  { name: 'Dark blue', hex: '002060' },
  { name: 'Purple', hex: '7030A0' },
];

/** Word's highlight colors: name in the file, label, swatch. */
const HIGHLIGHTS: Array<{ value: string; name: string; hex: string }> = [
  { value: 'yellow', name: 'Yellow', hex: 'FFFF00' },
  { value: 'green', name: 'Bright green', hex: '00FF00' },
  { value: 'cyan', name: 'Turquoise', hex: '00FFFF' },
  { value: 'magenta', name: 'Pink', hex: 'FF00FF' },
  { value: 'blue', name: 'Blue', hex: '0000FF' },
  { value: 'red', name: 'Red', hex: 'FF0000' },
  { value: 'darkBlue', name: 'Dark blue', hex: '000080' },
  { value: 'darkCyan', name: 'Teal', hex: '008080' },
  { value: 'darkGreen', name: 'Green', hex: '008000' },
  { value: 'darkMagenta', name: 'Violet', hex: '800080' },
  { value: 'darkRed', name: 'Dark red', hex: '800000' },
  { value: 'darkYellow', name: 'Dark yellow', hex: '808000' },
  { value: 'darkGray', name: 'Gray 50%', hex: '808080' },
  { value: 'lightGray', name: 'Gray 25%', hex: 'C0C0C0' },
];

/** Line spacing multiples offered. */
const LINE_SPACINGS = [1, 1.15, 1.5, 2, 2.5, 3];

const TABLE_OPS: Array<{ op: DocxTableOp; label: string }> = [
  { op: 'rowAbove', label: 'Insert row above' },
  { op: 'rowBelow', label: 'Insert row below' },
  { op: 'columnLeft', label: 'Insert column left' },
  { op: 'columnRight', label: 'Insert column right' },
  { op: 'deleteRow', label: 'Delete row' },
  { op: 'deleteColumn', label: 'Delete column' },
  { op: 'deleteTable', label: 'Delete table' },
];

export type DocxToolbarProps = {
  canEdit: boolean;
  canComment: boolean;
  format: Partial<Record<DocxInlineFormat, boolean>>;
  /** Font size at the selection (points). */
  fontSize: number | null;
  /** Font family at the selection. */
  fontFamily: string | null;
  /** Text color at the selection (`RRGGBB`, null for automatic). */
  color: string | null;
  /** Highlight at the selection (a Word highlight name). */
  highlight: string | null;
  /** Line spacing of the paragraph as a multiple, when it is one. */
  lineSpacing: number | null;
  /** The caret is in a table. */
  inTable: boolean;
  paragraphStyle: string | null;
  paragraphStyles: DocxParagraphStyle[];
  /** Tracked changes shown inline (else the document as if accepted). */
  showMarkup: boolean;
  /** The document records everyone's edits as tracked changes. */
  tracking: boolean;
  /** The selection (or the caret) is on a tracked change. */
  onRevision: boolean;
  onFormat: (format: DocxInlineFormat) => void;
  onFontSize: (size: number) => void;
  onFontFamily: (family: string) => void;
  /** Set the text color (`RRGGBB`), or null for automatic. */
  onColor: (color: string | null) => void;
  /** Set the highlight (a Word highlight name), or null to remove it. */
  onHighlight: (highlight: string | null) => void;
  onClearFormat: () => void;
  /** Indent (or outdent) the paragraphs. */
  onIndent: (forward: boolean) => void;
  onLineSpacing: (multiple: number) => void;
  onTable: (op: DocxTableOp) => void;
  /** Put focus back in the document (after a menu closes). */
  onRefocus?: () => void;
  onParagraphStyle: (styleId: string) => void;
  onList: (kind: 'bullet' | 'number') => void;
  onAlign: (alignment: DocxAlignment) => void;
  onUndo: () => void;
  onRedo: () => void;
  onInsertTable: () => void;
  /** Insert a footnote (or endnote) at the caret. */
  onInsertNote: (endnote: boolean) => void;
  /** The selection is in the body (notes are inserted from there). */
  inBody: boolean;
  onToggleMarkup: () => void;
  onToggleTracking: () => void;
  /** Accept the change at the selection, or every change. */
  onAccept: (all: boolean) => void;
  /** Reject the change at the selection, or every change. */
  onReject: (all: boolean) => void;
  onComment: () => void;
  /** Open find (and replace). */
  onFind: () => void;
};

const INLINE: Array<{
  format: DocxInlineFormat;
  label: string;
  icon: () => JSX.Element;
  shortcut?: string;
}> = [
  {
    format: 'bold',
    label: 'Bold',
    icon: () => <TextB class="size-4.5" />,
    shortcut: 'Mod+B',
  },
  {
    format: 'italic',
    label: 'Italic',
    icon: () => <TextItalic class="size-4.5" />,
    shortcut: 'Mod+I',
  },
  {
    format: 'underline',
    label: 'Underline',
    icon: () => <TextUnderline class="size-4.5" />,
    shortcut: 'Mod+U',
  },
  {
    format: 'strike',
    label: 'Strikethrough',
    icon: () => <TextStrikethrough class="size-4.5" />,
  },
  {
    format: 'superscript',
    label: 'Superscript',
    icon: () => <TextSuperscript class="size-4.5" />,
    shortcut: 'Mod+Shift+=',
  },
  {
    format: 'subscript',
    label: 'Subscript',
    icon: () => <TextSubscript class="size-4.5" />,
    shortcut: 'Mod+=',
  },
];

/** A square of a document color. */
function Swatch(props: { hex: string | null }) {
  return (
    <span
      class="inline-block size-3.5 shrink-0 rounded-[3px] border border-edge-muted"
      style={{ background: props.hex ? `#${props.hex}` : 'transparent' }}
    />
  );
}

/** A toolbar button opening a menu; closing it hands focus back to the
 * document through `onClose`. */
function ToolbarMenu(props: {
  label: string;
  icon: JSX.Element;
  children: JSX.Element;
  testId?: string;
  onClose?: () => void;
}) {
  return (
    <Dropdown placement="bottom-start" modal={false}>
      <Dropdown.Trigger
        aria-label={props.label}
        tooltip={props.label}
        variant="ghost"
        size="icon-sm"
        data-docx-menu={props.testId}
      >
        {props.icon}
      </Dropdown.Trigger>
      <Dropdown.Content
        class="min-w-44"
        onCloseAutoFocus={(event: Event) => {
          if (!props.onClose) return;
          event.preventDefault();
          props.onClose();
        }}
      >
        {props.children}
      </Dropdown.Content>
    </Dropdown>
  );
}

const ALIGNMENTS: Array<{
  alignment: DocxAlignment;
  label: string;
  icon: () => JSX.Element;
}> = [
  {
    alignment: 'left',
    label: 'Align left',
    icon: () => <TextAlignLeft class="size-4.5" />,
  },
  {
    alignment: 'center',
    label: 'Align center',
    icon: () => <TextAlignCenter class="size-4.5" />,
  },
  {
    alignment: 'right',
    label: 'Align right',
    icon: () => <TextAlignRight class="size-4.5" />,
  },
  {
    alignment: 'justify',
    label: 'Justify',
    icon: () => <TextAlignJustify class="size-4.5" />,
  },
];

/**
 * Keep the editor's selection: controls act on the caret the user left in
 * the document, so pressing one must not move focus out of it.
 */
const keepEditorFocus = (event: PointerEvent | MouseEvent) => {
  if (!(event.target as HTMLElement).closest('select')) event.preventDefault();
};

/** Formatting and document actions for the DOCX editor. */
export function DocxToolbar(props: DocxToolbarProps) {
  return (
    <div
      class="shrink-0 border-b border-edge-muted"
      onPointerDown={keepEditorFocus}
      onMouseDown={keepEditorFocus}
    >
      {/* Docked under the header like the spreadsheet toolbar, not floating. */}
      <Toolbar
        size="icon-sm"
        aria-label="Document formatting"
        class="flex h-10 w-full min-w-0 gap-0.5 overflow-x-auto overscroll-x-contain rounded-none border-0 bg-transparent px-3 py-0 touch:h-[48px] touch:touch-pan-x touch:px-1 [&_[data-button]]:size-7 [&_select]:h-7"
      >
        <Show when={props.canEdit}>
          <Toolbar.Group>
            <Toolbar.Button
              aria-label="Undo"
              tooltip={{ content: 'Undo', shortcut: 'Mod+Z' }}
              onClick={() => props.onUndo()}
            >
              <ArrowCounterClockwise class="size-4.5" />
            </Toolbar.Button>
            <Toolbar.Button
              aria-label="Redo"
              tooltip={{ content: 'Redo', shortcut: 'Mod+Shift+Z' }}
              onClick={() => props.onRedo()}
            >
              <ArrowClockwise class="size-4.5" />
            </Toolbar.Button>
          </Toolbar.Group>
          <Toolbar.Divider class="mx-1.5 my-2.5" />
          <select
            aria-label="Paragraph style"
            class="h-6 max-w-36 rounded-md border border-edge-muted bg-input px-1.5 text-xs text-ink"
            value={props.paragraphStyle ?? ''}
            onChange={(event) =>
              props.onParagraphStyle(event.currentTarget.value)
            }
          >
            <Show
              when={
                !props.paragraphStyles.some(
                  (style) => style.id === props.paragraphStyle
                )
              }
            >
              <option value="">
                {props.paragraphStyle ? 'Custom style' : 'Style'}
              </option>
            </Show>
            <For each={props.paragraphStyles}>
              {(style) => (
                <option
                  value={style.id}
                  selected={style.id === props.paragraphStyle}
                >
                  {style.name}
                </option>
              )}
            </For>
          </select>
          <select
            aria-label="Font"
            class="h-6 max-w-32 rounded-md border border-edge-muted bg-input px-1.5 text-xs text-ink"
            value={props.fontFamily ?? ''}
            onChange={(event) => props.onFontFamily(event.currentTarget.value)}
          >
            <Show
              when={
                props.fontFamily !== null &&
                !FONT_FAMILIES.includes(props.fontFamily)
              }
            >
              <option value={props.fontFamily ?? ''}>{props.fontFamily}</option>
            </Show>
            <For each={FONT_FAMILIES}>
              {(family) => (
                <option value={family} selected={family === props.fontFamily}>
                  {family}
                </option>
              )}
            </For>
          </select>
          <select
            aria-label="Font size"
            class="h-6 w-14 rounded-md border border-edge-muted bg-input px-1 text-xs text-ink"
            value={props.fontSize ?? ''}
            onChange={(event) =>
              props.onFontSize(Number(event.currentTarget.value))
            }
          >
            <Show
              when={
                props.fontSize !== null && !FONT_SIZES.includes(props.fontSize)
              }
            >
              <option value={props.fontSize ?? ''}>{props.fontSize}</option>
            </Show>
            <For each={FONT_SIZES}>
              {(size) => (
                <option value={size} selected={size === props.fontSize}>
                  {size}
                </option>
              )}
            </For>
          </select>
          <Toolbar.Divider class="mx-1.5 my-2.5" />
          <Toolbar.Group>
            <For each={INLINE}>
              {(item) => (
                <Toolbar.Button
                  aria-label={item.label}
                  tooltip={{ content: item.label, shortcut: item.shortcut }}
                  aria-pressed={!!props.format[item.format]}
                  onClick={() => props.onFormat(item.format)}
                >
                  {item.icon()}
                </Toolbar.Button>
              )}
            </For>
            <ToolbarMenu
              label="Text color"
              icon={<TextAUnderline class="size-4.5" />}
              testId="color"
              onClose={props.onRefocus}
            >
              <Dropdown.Item onSelect={() => props.onColor(null)}>
                <Swatch hex={null} />
                <span>Automatic</span>
              </Dropdown.Item>
              <For each={TEXT_COLORS}>
                {(c) => (
                  <Dropdown.Item onSelect={() => props.onColor(c.hex)}>
                    <Swatch hex={c.hex} />
                    <span>{c.name}</span>
                    <Show when={props.color === c.hex}>
                      <Check class="ml-auto size-3.5" />
                    </Show>
                  </Dropdown.Item>
                )}
              </For>
            </ToolbarMenu>
            <ToolbarMenu
              label="Highlight"
              icon={<Highlighter class="size-4.5" />}
              testId="highlight"
              onClose={props.onRefocus}
            >
              <Dropdown.Item onSelect={() => props.onHighlight(null)}>
                <Swatch hex={null} />
                <span>No highlight</span>
              </Dropdown.Item>
              <For each={HIGHLIGHTS}>
                {(h) => (
                  <Dropdown.Item onSelect={() => props.onHighlight(h.value)}>
                    <Swatch hex={h.hex} />
                    <span>{h.name}</span>
                    <Show when={props.highlight === h.value}>
                      <Check class="ml-auto size-3.5" />
                    </Show>
                  </Dropdown.Item>
                )}
              </For>
            </ToolbarMenu>
            <Toolbar.Button
              aria-label="Clear formatting"
              tooltip="Clear formatting"
              onClick={() => props.onClearFormat()}
            >
              <TextTSlash class="size-4.5" />
            </Toolbar.Button>
          </Toolbar.Group>
          <Toolbar.Divider class="mx-1.5 my-2.5" />
          <Toolbar.Group>
            <Toolbar.Button
              aria-label="Bulleted list"
              tooltip="Bulleted list"
              onClick={() => props.onList('bullet')}
            >
              <ListBullets class="size-4.5" />
            </Toolbar.Button>
            <Toolbar.Button
              aria-label="Numbered list"
              tooltip="Numbered list"
              onClick={() => props.onList('number')}
            >
              <ListNumbers class="size-4.5" />
            </Toolbar.Button>
          </Toolbar.Group>
          <Toolbar.Divider class="mx-1.5 my-2.5" />
          <Toolbar.Group>
            <For each={ALIGNMENTS}>
              {(item) => (
                <Toolbar.Button
                  aria-label={item.label}
                  tooltip={item.label}
                  onClick={() => props.onAlign(item.alignment)}
                >
                  {item.icon()}
                </Toolbar.Button>
              )}
            </For>
            <Toolbar.Button
              aria-label="Decrease indent"
              tooltip={{ content: 'Decrease indent', shortcut: 'Shift+Tab' }}
              onClick={() => props.onIndent(false)}
            >
              <TextOutdent class="size-4.5" />
            </Toolbar.Button>
            <Toolbar.Button
              aria-label="Increase indent"
              tooltip="Increase indent"
              onClick={() => props.onIndent(true)}
            >
              <TextIndent class="size-4.5" />
            </Toolbar.Button>
            <ToolbarMenu
              label="Line spacing"
              icon={<ArrowsDownUp class="size-4.5" />}
              testId="line-spacing"
              onClose={props.onRefocus}
            >
              <For each={LINE_SPACINGS}>
                {(m) => (
                  <Dropdown.Item onSelect={() => props.onLineSpacing(m)}>
                    <span>{m.toFixed(m === 1.15 ? 2 : 1)}</span>
                    <Show
                      when={
                        props.lineSpacing !== null &&
                        Math.abs(props.lineSpacing - m) < 0.01
                      }
                    >
                      <Check class="ml-auto size-3.5" />
                    </Show>
                  </Dropdown.Item>
                )}
              </For>
            </ToolbarMenu>
          </Toolbar.Group>
          <Toolbar.Divider class="mx-1.5 my-2.5" />
          <Toolbar.Button
            aria-label="Insert table"
            tooltip="Insert table"
            onClick={() => props.onInsertTable()}
          >
            <Table class="size-4.5" />
          </Toolbar.Button>
          <Show when={props.inBody}>
            <ToolbarMenu
              label="Insert footnote or endnote"
              icon={<AsteriskSimple class="size-4.5" />}
              testId="notes"
              onClose={props.onRefocus}
            >
              <Dropdown.Item onSelect={() => props.onInsertNote(false)}>
                <span>Footnote</span>
              </Dropdown.Item>
              <Dropdown.Item onSelect={() => props.onInsertNote(true)}>
                <span>Endnote</span>
              </Dropdown.Item>
            </ToolbarMenu>
          </Show>
          <Show when={props.inTable}>
            <ToolbarMenu
              label="Table rows and columns"
              icon={<RowsPlusBottom class="size-4.5" />}
              testId="table"
              onClose={props.onRefocus}
            >
              <For each={TABLE_OPS}>
                {(item) => (
                  <Dropdown.Item onSelect={() => props.onTable(item.op)}>
                    <span>{item.label}</span>
                  </Dropdown.Item>
                )}
              </For>
            </ToolbarMenu>
          </Show>
          <Toolbar.Divider class="mx-1.5 my-2.5" />
          <Toolbar.Group>
            <Toolbar.Button
              aria-label={
                props.tracking ? 'Stop tracking changes' : 'Track changes'
              }
              tooltip={
                props.tracking ? 'Stop tracking changes' : 'Track changes'
              }
              aria-pressed={props.tracking}
              data-docx-track-changes
              onClick={() => props.onToggleTracking()}
            >
              <GitDiff class="size-4.5" />
            </Toolbar.Button>
            <Toolbar.Button
              aria-label={
                props.showMarkup
                  ? 'Hide tracked changes'
                  : 'Show tracked changes'
              }
              tooltip={
                props.showMarkup
                  ? 'Hide tracked changes'
                  : 'Show tracked changes'
              }
              aria-pressed={props.showMarkup}
              onClick={() => props.onToggleMarkup()}
            >
              <Show
                when={props.showMarkup}
                fallback={<EyeSlash class="size-4.5" />}
              >
                <Eye class="size-4.5" />
              </Show>
            </Toolbar.Button>
            <Show when={props.tracking || props.onRevision}>
              <Toolbar.Button
                aria-label="Accept change"
                tooltip="Accept change"
                disabled={!props.onRevision}
                onClick={() => props.onAccept(false)}
              >
                <Check class="size-4.5" />
              </Toolbar.Button>
              <Toolbar.Button
                aria-label="Reject change"
                tooltip="Reject change"
                disabled={!props.onRevision}
                onClick={() => props.onReject(false)}
              >
                <X class="size-4.5" />
              </Toolbar.Button>
              <Toolbar.Button
                aria-label="Accept all changes"
                tooltip="Accept all changes"
                onClick={() => props.onAccept(true)}
              >
                <Checks class="size-4.5" />
              </Toolbar.Button>
              <Toolbar.Button
                aria-label="Reject all changes"
                tooltip="Reject all changes"
                onClick={() => props.onReject(true)}
              >
                <XCircle class="size-4.5" />
              </Toolbar.Button>
            </Show>
          </Toolbar.Group>
          <Toolbar.Divider class="mx-1.5 my-2.5" />
        </Show>
        <Show when={props.canComment}>
          <Toolbar.Button
            aria-label="Comment on selection"
            tooltip={{ content: 'Comment on selection', shortcut: 'Mod+Alt+M' }}
            onClick={() => props.onComment()}
          >
            <ChatCircleText class="size-4.5" />
          </Toolbar.Button>
        </Show>
        <Toolbar.Button
          aria-label="Find and replace"
          tooltip={{ content: 'Find and replace', shortcut: 'Mod+F' }}
          onClick={() => props.onFind()}
        >
          <MagnifyingGlass class="size-4.5" />
        </Toolbar.Button>
      </Toolbar>
    </div>
  );
}