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.

chore(channels): remove old unused deprecated components (#2752)

teoeaacc6b8a7c7
diff --git a/js/app/packages/block-channel/component/DeprecatedChannelInput/AttachMenu.tsx b/js/app/packages/block-channel/component/DeprecatedChannelInput/AttachMenu.tsx
deleted file mode 100644
index 330eed74a1..0000000000
--- a/js/app/packages/block-channel/component/DeprecatedChannelInput/AttachMenu.tsx
+++ /dev/null
@@ -1,213 +0,0 @@
-import { handleFileUpload } from '@block-channel/component/DeprecatedChannelInput/inputAttachments';
-import { EntityIcon } from '@core/component/EntityIcon';
-import { OldMenu, OldMenuItem } from '@core/component/OldMenu';
-import { blockAcceptedFileExtensions } from '@core/constant/allBlocks';
-import clickOutside from '@core/directive/clickOutside';
-import { fileSelector } from '@core/directive/fileSelector';
-import { isTouchDevice } from '@core/mobile/isTouchDevice';
-import type { InputAttachment } from '@core/store/cacheChannelInput';
-import { fuzzyFilter } from '@core/util/fuzzy';
-import { getItemBlockName } from '@core/util/getItemBlockName';
-import {
- autoUpdate,
- computePosition,
- flip,
- limitShift,
- offset,
- shift,
-} from '@floating-ui/dom';
-import DeviceMobileIcon from '@icon/regular/device-mobile-speaker.svg';
-import LaptopIcon from '@icon/regular/laptop.svg';
-import SearchIcon from '@icon/regular/magnifying-glass.svg';
-import { useHistoryQuery } from '@queries/history/history';
-import {
- createEffect,
- createMemo,
- createSignal,
- onCleanup,
- Show,
-} from 'solid-js';
-import type { SetStoreFunction } from 'solid-js/store';
-import { VList } from 'virtua/solid';
-
-// NOTE: solid directives
-false && fileSelector;
-false && clickOutside;
-
-type AttachMenuProps = {
- open: boolean;
- close: () => void;
- anchorRef: HTMLDivElement;
- containerRef: HTMLElement;
- onAttach: (attachment: InputAttachment) => void;
- inputAttachmentsStore: {
- store: Record<string, InputAttachment[]>;
- setStore: SetStoreFunction<Record<string, InputAttachment[]>>;
- key: string;
- };
-};
-
-function truncate(str: string, maxLength: number = 30) {
- if (str.length <= maxLength) return str;
- return str.slice(0, maxLength) + '...';
-}
-
-export function AttachMenu(props: AttachMenuProps) {
- const [position, setPosition] = createSignal({ x: 0, y: 0 });
- const [popupRef, setPopupRef] = createSignal<HTMLDivElement>();
- const historyQuery = useHistoryQuery();
- const inputAttachments = () =>
- props.inputAttachmentsStore.store[props.inputAttachmentsStore.key] ?? [];
-
- const [input, setInput] = createSignal('');
-
- const updatePosition = async () => {
- const popupRef_ = popupRef();
- if (!popupRef_) return;
- const { x, y } = await computePosition(props.anchorRef, popupRef_, {
- placement: 'bottom-start',
- middleware: [
- offset(8),
- flip({
- fallbackStrategy: 'bestFit',
- boundary: props.containerRef,
- }),
- shift({
- padding: 8,
- boundary: props.containerRef,
- limiter: limitShift(),
- }),
- ],
- });
- setPosition({ x, y });
- };
-
- const baseHistory = createMemo(() => {
- return [...(historyQuery.data ?? [])].filter(
- (item) => !inputAttachments().find((a) => a.id === item.id)
- );
- });
-
- const rankedHistory = createMemo(() => {
- const searchQuery = input();
- return fuzzyFilter(searchQuery, baseHistory(), (item) => item.name);
- });
-
- createEffect(() => {
- const popupRef_ = popupRef();
- if (!popupRef_) return;
-
- document.body.style.overflow = 'hidden';
- const cleanup = autoUpdate(props.anchorRef, popupRef_, updatePosition);
-
- onCleanup(() => {
- cleanup();
- document.body.style.overflow = '';
- });
- });
-
- const handleOverlayClick = (e: MouseEvent) => {
- if (e.target === e.currentTarget) {
- e.preventDefault();
- e.stopPropagation();
- props.close();
- }
- };
-
- return (
- <Show when={props.open}>
- <div
- class="ph-no-capture fixed inset-0 bg-transparent z-item-options-menu"
- onPointerDown={handleOverlayClick}
- >
- <div
- class="absolute z-item-options-menu"
- ref={setPopupRef}
- use:clickOutside={(e) => {
- e.preventDefault();
- e.stopPropagation();
- props.close();
- }}
- style={{
- left: `${position().x}px`,
- top: `${position().y}px`,
- 'transform-origin': 'top',
- }}
- >
- <OldMenu>
- <div class="flex flex-row items-center w-full p-2 gap-2 text-sm border-b border-edge-muted text-ink mb-1">
- <SearchIcon class="w-3 h-3" />
- <input
- value={input()}
- onInput={(e) => setInput(e.target.value)}
- class="w-full"
- placeholder="Search Attachments"
- />
- </div>
- <div class="flex flex-col gap-1 max-h-[250px] w-[300px] overflow-y-auto">
- <Show
- when={rankedHistory().length > 0}
- fallback={
- <div class="p-2 w-full flex-col justify-center items-center">
- <p class="text-sm text-ink-muted">No results</p>
- </div>
- }
- >
- <VList
- data={rankedHistory()}
- bufferSize={10 * 40}
- itemSize={40}
- style={{ height: '100%', contain: 'content' }}
- >
- {(item) => (
- <OldMenuItem
- text={truncate(item.name)}
- icon={() => (
- <EntityIcon
- targetType={getItemBlockName(item, true)}
- size="xs"
- />
- )}
- onClick={() => {
- const blockName = getItemBlockName(item, true);
- if (!blockName) return;
-
- props.onAttach({
- id: item.id,
- name: item.name,
- blockName,
- });
- props.close();
- }}
- />
- )}
- </VList>
- </Show>
- </div>
- <div class="w-full h-px bg-edge mt-[1px]" />
- <div
- class="w-full"
- use:fileSelector={{
- acceptedFileExtensions: blockAcceptedFileExtensions,
- multiple: true,
- onSelect: (files) => {
- handleFileUpload(files, props.inputAttachmentsStore);
- props.close();
- },
- }}
- >
- <OldMenuItem
- text={
- isTouchDevice()
- ? 'Upload from your device'
- : 'Upload from your computer'
- }
- icon={isTouchDevice() ? DeviceMobileIcon : LaptopIcon}
- />
- </div>
- </OldMenu>
- </div>
- </div>
- </Show>
- );
-}
diff --git a/js/app/packages/block-channel/component/DeprecatedChannelInput/Attachment.tsx b/js/app/packages/block-channel/component/DeprecatedChannelInput/Attachment.tsx
deleted file mode 100644
index 85b226c2c0..0000000000
--- a/js/app/packages/block-channel/component/DeprecatedChannelInput/Attachment.tsx
+++ /dev/null
@@ -1,110 +0,0 @@
-import { ImagePreview } from '@core/component/ImagePreview';
-import { ItemPreview } from '@core/component/ItemPreview';
-import { VideoPreview } from '@core/component/VideoPreview';
-import {
- type InputAttachment,
- isStaticAttachmentType,
- STATIC_IMAGE,
- STATIC_VIDEO,
-} from '@core/store/cacheChannelInput';
-import { matches } from '@core/util/match';
-import Close from '@phosphor-icons/core/regular/x.svg?component-solid';
-import Spinner from '@phosphor-icons/core/bold/spinner-gap-bold.svg?component-solid';
-import { blockNameToItemType } from '@service-storage/client';
-import { createSignal, Match, Show, Switch } from 'solid-js';
-
-type AttachmentProps = {
- attachment: InputAttachment;
- remove?: (attachment: InputAttachment) => void;
- onClick?: (attachment: InputAttachment) => void;
-};
-
-export function Attachment(props: AttachmentProps) {
- const [hover, setHover] = createSignal(false);
-
- const isStaticMedia = () =>
- props.attachment.blockName === STATIC_IMAGE ||
- props.attachment.blockName === STATIC_VIDEO;
-
- return (
- <Switch>
- <Match when={isStaticMedia()}>
- <div
- class="relative"
- onMouseEnter={() => setHover(true)}
- onMouseLeave={() => setHover(false)}
- >
- <Show when={hover() && props.remove}>
- <Close
- width={24}
- height={24}
- class="text-ink absolute -top-2 -right-2 rounded-full bg-menu p-1 border border-edge-muted z-[10] cursor-pointer"
- onClick={() => props.remove?.(props.attachment)}
- />
- </Show>
- <Show when={props.attachment.pending}>
- <div class="flex flex-col items-center justify-center gap-2 w-[60px] h-[60px] border border-edge-muted rounded-md bg-menu">
- <Spinner class="w-4 h-4 animate-spin" />
- </div>
- </Show>
- <Show
- when={
- !props.attachment.pending &&
- props.attachment.blockName === STATIC_IMAGE
- }
- >
- <ImagePreview
- image={{
- id: props.attachment.id,
- }}
- variant="small"
- />
- </Show>
- <Show
- when={
- !props.attachment.pending &&
- props.attachment.blockName === STATIC_VIDEO
- }
- >
- <VideoPreview id={props.attachment.id} variant="small" />
- </Show>
- </div>
- </Match>
- <Match
- when={matches(
- props.attachment.blockName,
- (bn) => !isStaticAttachmentType(bn)
- )}
- >
- {(blockName) => (
- <div class="flex items-center px-1 space-x-1 hover:bg-hover hover-transition-bg cursor-default text-sm border border-edge-muted rounded-xs">
- <Show when={props.attachment.pending}>
- <Spinner class="w-4 h-4 animate-spin" />
- </Show>
- <Show when={!props.attachment.pending}>
- <ItemPreview
- id={props.attachment.id}
- type={blockNameToItemType(blockName())}
- class="flex items-center gap-1 text-sm ring-0"
- textClass="truncate"
- iconSize="xs"
- disableHoverCard
- />
- </Show>
- <Show when={props.remove}>
- <div
- class="hover:bg-hover hover-transition-bg rounded-md p-1 items-center flex"
- onClick={(e) => {
- e.stopPropagation();
- props.remove?.(props.attachment);
- }}
- >
- <Close class="text-ink-muted group-hover:text-failure size-3" />
- </div>
- </Show>
- </div>
- )}
- </Match>
- </Switch>
- );
-}
diff --git a/js/app/packages/block-channel/component/DeprecatedChannelInput/BaseInput.tsx b/js/app/packages/block-channel/component/DeprecatedChannelInput/BaseInput.tsx
deleted file mode 100644
index 1a8f4572e9..0000000000
--- a/js/app/packages/block-channel/component/DeprecatedChannelInput/BaseInput.tsx
+++ /dev/null
@@ -1,657 +0,0 @@
-import { handleFileUpload } from '@block-channel/component/DeprecatedChannelInput/inputAttachments';
-import {
- $convertSingleMentionToCard,
- expandGroupParticipants,
- toSimpleMention,
-} from '@block-channel/component/DeprecatedChannelInput/mentionExpansion';
-import {
- createTasksFromPotential,
- replaceCheckboxesWithMentions,
-} from '@block-channel/component/DeprecatedChannelInput/taskModeConversion';
-import { useTaskMode } from '@block-channel/component/DeprecatedChannelInput/taskmode';
-import { LabelAndHotKey } from '@core/component/Tooltip';
-import { FileDropOverlay } from '@core/component/FileDropOverlay';
-import {
- pendingEditorState,
- editorStateAsMarkdown,
- setEditorStateFromMarkdown,
-} from '@core/component/LexicalMarkdown/utils';
-import { fileFolderDrop } from '@core/directive/fileFolderDrop';
-import { TOKENS } from '@core/hotkey/tokens';
-import { isTouchDevice } from '@core/mobile/isTouchDevice';
-import {
- type InputAttachment,
- isStaticAttachmentType,
- STATIC_IMAGE,
- STATIC_VIDEO,
-} from '@core/store/cacheChannelInput';
-import type { IUser } from '@core/user';
-import type { UploadInput } from '@core/util/upload';
-import { handleFileFolderDrop } from '@core/util/upload';
-import ArrowUp from '@icon/bold/arrow-up-bold.svg';
-import Spinner from '@icon/bold/spinner-gap-bold.svg';
-import CheckSquareIcon from '@icon/regular/check-square.svg';
-import PlusIcon from '@icon/regular/plus.svg';
-import FormatIcon from '@icon/regular/text-aa.svg';
-import Trash from '@icon/regular/trash.svg';
-import XIcon from '@icon/regular/x.svg';
-import { $getRoot } from 'lexical';
-import { logger } from '@observability';
-import type { SimpleMention } from '@service-comms/generated/models/simpleMention';
-import { staticFileClient } from '@service-static-files/client';
-import { leading, throttle } from '@solid-primitives/scheduled';
-import { Button } from '@ui/components/Button';
-import { activeElement } from 'app/signal/focus';
-import { toast } from 'core/component/Toast/Toast';
-import { registerHotkey, useHotkeyDOMScope } from 'core/hotkey/hotkeys';
-import {
- type Accessor,
- createEffect,
- createRenderEffect,
- createSignal,
- For,
- onCleanup,
- onMount,
- Show,
- Suspense,
-} from 'solid-js';
-import type { SetStoreFunction } from 'solid-js/store';
-import { tabbable } from 'tabbable';
-import { AttachMenu } from './AttachMenu';
-import { Attachment } from './Attachment';
-import { FormatRibbon } from './FormatRibbon';
-import { useChannelMarkdownArea } from './MarkdownArea';
-import { TaskPreviewPanel } from './TaskPreviewPanel';
-import { useUserId } from '@core/context/user';
-import { isMobile } from '@core/mobile/isMobile';
-import { ENABLE_STATIC_DOCUMENT_CARDS } from '@core/constant/featureFlags';
-import type { SendMessageArgs } from '@block-channel/component/DeprecatedChannelInput/message';
-
-false && fileFolderDrop;
-
-type InputAttachmentsStore = {
- store: Record<string, InputAttachment[]>;
- setStore: SetStoreFunction<Record<string, InputAttachment[]>>;
- key: string;
-};
-
-type BaseInputProps = {
- /** callback to be executed when the user clicks the send button
- * or presses enter */
- onSend: (args: SendMessageArgs) => Promise<void>;
- /** callback to be executed when the user changes the input */
- onChange: (content: string) => void;
- /** initial value of the input */
- initialValue?: Accessor<string>;
- /** placeholder text to be displayed */
- placeholder: string;
- /** callback when the user start typing */
- onStartTyping: () => void;
- /** callback when the user stops typing and becomes idle */
- onStopTyping: () => void;
- /** keyed store for input attachments */
- inputAttachments: InputAttachmentsStore;
- /** when true, focus on mount (respecting viewport and device checks) */
- autoFocusOnMount?: boolean;
- /** external focus trigger: if getter returns true, focus then call clearer */
- shouldFocus?: boolean;
- clearShouldFocus?: () => void;
- onFocus?: () => void;
- onBlur?: () => void;
- /** called after onSend resolves and after BaseInput cleanup */
-
- afterSend?: () => void | Promise<void>;
- /** called when the user uses the up arrow or shift + tab to leave the first line of input */
- onFocusLeaveStart?: (e: KeyboardEvent) => void;
- /** optional setter to reflect local typing state with 500ms debounce for gating UI updates */
- setLocalTyping?: (isTyping: boolean) => void;
- /** the list of users in the channel */
- channelUsers?: () => IUser[];
- domRef?: (ref: HTMLDivElement) => void | HTMLDivElement;
- /** method to delete and close the draft */
- closeDraft?: () => void;
- /** whether this input is for a reply (affects styling) */
- isReplyInput?: boolean;
- /** whether a file is being dragged over the parent channel container */
- isDraggingOverChannel?: Accessor<boolean>;
- /** whether the dragged file is a valid channel attachment */
- isValidChannelDrag?: Accessor<boolean>;
-};
-
-/** the time after a user stops typing before we consider them idle. we want smooth remote changes, but local changes should happen more immediately. */
-const REMOTE_ACTIVITY_TIMEOUT_MS = 2000;
-const LOCAL_ACTIVITY_TIMEOUT_MS = 500;
-
-export function BaseInput(props: BaseInputProps) {
- const userId = useUserId();
- let containerRef!: HTMLDivElement;
- const key = props.inputAttachments.key;
- const [showFormatRibbon, setShowFormatRibbon] = createSignal(false);
- const [isDraggedOver, setIsDraggedOver] = createSignal(false);
- const isDraggingOverChannel = props.isDraggingOverChannel ?? (() => false);
- const isValidChannelDrag = props.isValidChannelDrag ?? (() => true);
-
- const attachments = () => props.inputAttachments.store[key] ?? [];
-
- const hasPendingAttachments = () =>
- attachments().some((item) => item.pending);
-
- const [typing, setTyping] = createSignal(false);
- let remoteInactivityTimeout: ReturnType<typeof setTimeout> | undefined;
- let localInactivityTimeout: ReturnType<typeof setTimeout> | undefined;
- let viewportObserver: IntersectionObserver | undefined;
-
- const [showAttachMenu, setShowAttachMenu] = createSignal(false);
- const [attachMenuAnchorRef, setAttachMenuAnchorRef] =
- createSignal<HTMLDivElement>();
-
- function resetInactivityTimeout() {
- if (remoteInactivityTimeout) {
- clearTimeout(remoteInactivityTimeout);
- }
- if (localInactivityTimeout) {
- clearTimeout(localInactivityTimeout);
- }
- remoteInactivityTimeout = setTimeout(
- () => stopRemoteTyping(),
- REMOTE_ACTIVITY_TIMEOUT_MS
- );
- localInactivityTimeout = setTimeout(
- () => stopLocalTyping(),
- LOCAL_ACTIVITY_TIMEOUT_MS
- );
- }
-
- function stopRemoteTyping() {
- if (typing()) {
- setTyping(false);
- props.onStopTyping();
- }
- }
-
- function stopLocalTyping() {
- props.setLocalTyping?.(false);
- }
-
- function stopTyping() {
- stopRemoteTyping();
- stopLocalTyping();
- }
-
- const startTyping = leading(
- throttle,
- () => {
- if (!typing()) {
- setTyping(true);
- props.onStartTyping();
- }
- props.setLocalTyping?.(true);
- },
- 1000
- );
-
- const {
- focus: focusMarkdownArea,
- blur: blurMarkdownArea,
- clear: clearMarkdownArea,
- state: markdownState,
- formatState: markdownFormatState,
- setInlineFormat,
- setNodeFormat,
- mentions,
- MarkdownArea,
- editor,
- ref,
- } = useChannelMarkdownArea();
-
- const {
- taskModeEnabled,
- toggleTaskMode,
- potentialTasks,
- updateTaskPropertyValue,
- resetTaskProperties,
- } = useTaskMode(markdownState);
-
- createRenderEffect(() => {
- const currentRef = ref();
- if (currentRef) props.domRef?.(currentRef);
- });
-
- const allMentions: Accessor<SimpleMention[]> = () => {
- const result: SimpleMention[] = [];
- const seenUserIds = new Set<string>();
- const channelUserIds = props.channelUsers?.().map((u) => u.id) ?? [];
-
- for (const m of mentions()) {
- if (m.itemType === 'group') {
- result.push(...expandGroupParticipants(channelUserIds, seenUserIds));
- } else {
- const mention = toSimpleMention(m, seenUserIds);
- if (mention) result.push(mention);
- }
- }
-
- return result;
- };
-
- const [attachFn, scopeId] = useHotkeyDOMScope('channel.baseInput');
-
- onMount(() => {
- attachFn(containerRef);
-
- if (!isTouchDevice()) {
- setTimeout(() => {
- if (
- props.autoFocusOnMount === true ||
- props.autoFocusOnMount === undefined
- ) {
- focusMarkdownArea();
- }
- }, 0);
- }
-
- if (ref() && props.onFocus) {
- const markdownElement = ref()!;
- const handleFocusIn = () => {
- props.onFocus?.();
- };
-
- markdownElement.addEventListener('focusin', handleFocusIn);
-
- onCleanup(() => {
- markdownElement.removeEventListener('focusin', handleFocusIn);
- });
- }
- });
-
- const onFocusLeaveEnd = (e: KeyboardEvent) => {
- e.preventDefault();
- e.stopPropagation();
- const tabbableElements = tabbable(containerRef);
- if (!tabbableElements.length) {
- return;
- }
- const inputElIndex = tabbableElements.findIndex(
- (el) => el.classList.contains('md') && el.tagName === 'DIV'
- );
- if (inputElIndex === -1) {
- return;
- }
- const nextEl = tabbableElements[inputElIndex + 1];
- if (!nextEl) {
- return;
- }
- nextEl.focus();
- };
-
- registerHotkey({
- hotkey: ['enter'],
- scopeId: scopeId,
- description: 'Send message',
- condition: () => {
- return (
- (activeElement()?.classList.contains('md') &&
- activeElement()?.tagName === 'DIV') ??
- false
- );
- },
- keyDownHandler: () => {
- return true;
- },
- hotkeyToken: TOKENS.channel.sendMessage,
- });
-
- // Focus when external shouldFocus signal is set to true
- createEffect(() => {
- if (props.shouldFocus) {
- if (!isMobile()) {
- requestAnimationFrame(() => {
- focusMarkdownArea();
- props.clearShouldFocus?.();
- });
- } else {
- props.clearShouldFocus?.();
- }
- }
- });
-
- onCleanup(() => {
- if (remoteInactivityTimeout) {
- clearTimeout(remoteInactivityTimeout);
- }
- stopTyping();
- viewportObserver?.disconnect();
- if (markdownState().trim() === '') {
- props.closeDraft?.();
- }
- });
-
- function onAttach(attachment: InputAttachment) {
- // prevent duplicate attachments
- const list = attachments();
- if (list.find((a) => a.id === attachment.id)) return;
- if (list.length >= 10) {
- toast.failure('You can only attach up to 10 files at a time');
- return;
- }
- props.inputAttachments.setStore(key, (prev = []) => [...prev, attachment]);
- focusMarkdownArea();
- props.onChange(markdownState());
- }
-
- function removeAttachment(attachment: InputAttachment) {
- if (attachment.blockName === STATIC_IMAGE) {
- staticFileClient
- .deleteFile({
- file_id: attachment.id,
- })
- .catch((err) => {
- console.error('error in deleting file', err);
- });
- }
- props.inputAttachments.setStore(key, (prev = []) =>
- prev.filter((a) => a.id !== attachment.id)
- );
- focusMarkdownArea();
- props.onChange(markdownState());
- }
-
- async function handleSend() {
- const statePromise = pendingEditorState(editor);
- editor.update(
- () => {
- $getRoot().markDirty();
- if (ENABLE_STATIC_DOCUMENT_CARDS) {
- $convertSingleMentionToCard();
- }
- },
- { discrete: true }
- );
-
- const state = await statePromise;
- let content = editorStateAsMarkdown(state);
- const originalContent = content;
-
- if (taskModeEnabled() && potentialTasks().length > 0) {
- const results = await createTasksFromPotential(potentialTasks(), {
- currentUserId: userId(),
- });
-
- if (results.successes.length > 0) {
- content = replaceCheckboxesWithMentions(content, results.successes);
- toast.success(`Created ${results.successes.length} task(s)`);
- }
- }
-
- const args = {
- content: content,
- attachments: props.inputAttachments.store[key] ?? [],
- mentions: allMentions(),
- };
-
- clearMarkdownArea();
- resetTaskProperties();
- focusMarkdownArea();
-
- props
- .onSend(args)
- .then(() => {
- props.inputAttachments.setStore(key, []);
- stopTyping();
- return props.afterSend?.();
- })
- .catch((_) => {
- // Restore the stashed editor state
- clearMarkdownArea();
- try {
- setEditorStateFromMarkdown(editor, originalContent);
- } catch (e) {
- logger.error('Failed to restore editor state after send error', {
- error: e,
- });
- }
- focusMarkdownArea();
- });
-
- return true;
- }
-
- function handleChange(input: string) {
- if (input.trim() === '') {
- stopTyping();
- } else {
- startTyping();
- resetInactivityTimeout();
- props.onChange(input);
- }
- }
-
- async function onMarkdownAreaPasteFilesAndDirs(
- files: FileSystemFileEntry[],
- directories: FileSystemDirectoryEntry[]
- ) {
- const onFilesReady = (uploadEntries: UploadInput[]) => {
- handleFileUpload(uploadEntries, props.inputAttachments, (_attachment) => {
- props.onChange(markdownState());
- });
- };
- return handleFileFolderDrop(files, directories, onFilesReady);
- }
-
- const videoAttachments = () =>
- attachments().filter((a) => a.blockName === STATIC_VIDEO);
-
- const imageAttachments = () =>
- attachments().filter((a) => a.blockName === STATIC_IMAGE);
-
- const documentAttachments = () =>
- attachments().filter((a) => !isStaticAttachmentType(a.blockName));
-
- return (
- <div
- class="relative flex flex-col flex-1 items-center justify-between bg-input border-t border-x border-edge-muted rounded-t-[5px] -mb-[7px]"
- classList={{
- 'rounded-b-[5px] border-b mb-4': props.isReplyInput,
- }}
- ref={containerRef}
- use:fileFolderDrop={{
- onDrop: (files, folders) => {
- handleFileFolderDrop(files, folders, (uploadEntries) =>
- handleFileUpload(uploadEntries, {
- store: props.inputAttachments.store,
- setStore: props.inputAttachments.setStore,
- key: key,
- })
- );
- },
- onDragStart: () => {
- setIsDraggedOver(true);
- },
- onDragEnd: () => {
- setIsDraggedOver(false);
- },
- }}
- >
- <Show
- when={
- isDraggedOver() || (isDraggingOverChannel() && !props.isReplyInput)
- }
- >
- <FileDropOverlay valid={isValidChannelDrag()}>
- <Show when={!isValidChannelDrag()}>
- <div class="font-mono text-failure">
- [!] Invalid attachment file
- </div>
- </Show>
- <div class="font-mono">
- Drop any file here to add it to the conversation
- </div>
- </FileDropOverlay>
- </Show>
- <Show when={showFormatRibbon()}>
- <FormatRibbon
- state={markdownFormatState}
- inlineFormat={setInlineFormat}
- nodeFormat={setNodeFormat}
- />
- </Show>
- <div
- class="ph-no-capture transition-all duration-150 px-3 pt-2 pb-2 @min-[40rem]:pb-4 overflow-y-auto placeholder:text-ink-placeholder text-ink w-full text-sm mobile:text-base"
- onClick={(e) => {
- e.stopPropagation();
- focusMarkdownArea();
- }}
- >
- {/* Disable enter to submit on mobile */}
- <MarkdownArea
- placeholder={props.placeholder}
- onEnter={
- isMobile()
- ? (_e) => false
- : (_e) => {
- if (hasPendingAttachments()) {
- return true;
- }
- handleSend();
- return true;
- }
- }
- onBlur={() => {
- props.onBlur?.();
- stopTyping();
- blurMarkdownArea();
- }}
- users={props.channelUsers}
- onChange={handleChange}
- onPasteFilesAndDirs={onMarkdownAreaPasteFilesAndDirs}
- initialValue={props.initialValue?.()}
- useBlockBoundary={true}
- onEscape={() => {
- blurMarkdownArea();
- if (markdownState().trim() === '') {
- props.closeDraft?.();
- }
- return true;
- }}
- dontFocusOnMount
- onFocusLeaveStart={props.onFocusLeaveStart}
- onFocusLeaveEnd={onFocusLeaveEnd}
- />
- </div>
- <Show when={videoAttachments()?.length > 0}>
- <div class="ph-no-capture flex flex-row w-full px-2 py-1 gap-2 flex-wrap">
- <For each={videoAttachments()}>
- {(attachment) => (
- <Attachment attachment={attachment} remove={removeAttachment} />
- )}
- </For>
- </div>
- </Show>
- <Show when={imageAttachments()?.length > 0}>
- <div class="ph-no-capture flex flex-row w-full px-2 py-1 gap-2 flex-wrap">
- <For each={imageAttachments()}>
- {(attachment) => (
- <Attachment attachment={attachment} remove={removeAttachment} />
- )}
- </For>
- </div>
- </Show>
- <Show when={documentAttachments()?.length > 0}>
- <div class="ph-no-capture flex flex-row w-full px-2 py-1 gap-2 flex-wrap">
- <For each={documentAttachments()}>
- {(attachment) => (
- <Attachment attachment={attachment} remove={removeAttachment} />
- )}
- </For>
- </div>
- </Show>
- <Show when={taskModeEnabled() && potentialTasks().length > 0}>
- <Suspense>
- <TaskPreviewPanel
- tasks={potentialTasks()}
- onUpdatePropertyValue={updateTaskPropertyValue}
- />
- </Suspense>
- </Show>
- <div class="flex flex-row w-full h-8 justify-between items-center p-2 mb-2 space-x-2 allow-css-brackets">
- <Show when={showAttachMenu()}>
- <AttachMenu
- anchorRef={attachMenuAnchorRef()!}
- close={() => setShowAttachMenu(false)}
- containerRef={containerRef!}
- open={showAttachMenu()}
- onAttach={onAttach}
- inputAttachmentsStore={props.inputAttachments}
- />
- </Show>
- <div class="flex flex-row items-center gap-2">
- <Button
- ref={setAttachMenuAnchorRef}
- // We use onPointerDown here to integrate correctly with attach menu onMouseDown behavior.
- onPointerDown={(e: PointerEvent) => {
- e.preventDefault();
- e.stopPropagation();
- setShowAttachMenu((prev) => !prev);
- }}
- >
- <Show
- when={showAttachMenu()}
- fallback={<PlusIcon width={20} height={20} />}
- >
- <XIcon width={20} height={20} />
- </Show>
- </Button>
-
- <Button
- tooltip={<LabelAndHotKey label="Format" />}
- onClick={(e) => {
- e.preventDefault();
- setShowFormatRibbon((prev) => !prev);
- }}
- classList={{ 'bg-active': showFormatRibbon() }}
- >
- <FormatIcon width={20} height={20} />
- </Button>
- <Button
- tooltip={<LabelAndHotKey label="Task Mode" />}
- onClick={(e) => {
- e.preventDefault();
- toggleTaskMode();
- }}
- classList={{ 'bg-active': taskModeEnabled() }}
- >
- <CheckSquareIcon width={20} height={20} />
- </Button>
- <Show when={props.isReplyInput && props.closeDraft}>
- <Button
- tooltip={<LabelAndHotKey label="Delete reply" />}
- onClick={(e) => {
- e.preventDefault();
- props.closeDraft?.();
- }}
- >
- <Trash width={20} height={20} />
- </Button>
- </Show>
- </div>
- <Button
- disabled={hasPendingAttachments()}
- onPointerDown={(e) => {
- e.preventDefault();
- handleSend();
- }}
- class="group transition ease-in-out hover:bg-transparent"
- >
- <Show
- when={!hasPendingAttachments()}
- fallback={<Spinner class="size-6 animate-spin cursor-disabled" />}
- >
- <div class="group-hover:scale-115 group-hover:bg-accent transition ease-in-out size-6 touch:size-8 border border-accent rounded-full flex items-center justify-center">
- <ArrowUp class="group-hover:!text-input group-hover:!fill-input !text-accent-ink !fill-accent size-4 transition ease-in-out" />
- </div>
- </Show>
- </Button>
- </div>
- </div>
- );
-}
diff --git a/js/app/packages/block-channel/component/DeprecatedChannelInput/ChannelInput.tsx b/js/app/packages/block-channel/component/DeprecatedChannelInput/ChannelInput.tsx
deleted file mode 100644
index dc65fd1acf..0000000000
--- a/js/app/packages/block-channel/component/DeprecatedChannelInput/ChannelInput.tsx
+++ /dev/null
@@ -1,94 +0,0 @@
-import {
- clearDraftMessage,
- loadDraftMessage,
- saveDraftMessage,
-} from '@block-channel/component/DeprecatedChannelInput/draftMessages';
-import type {
- DraftMessage,
- InputAttachment,
-} from '@core/store/cacheChannelInput';
-import type { IUser } from '@core/user';
-import { channelParticipantInfo } from '@core/user/util';
-import { usePostTypingUpdateMutation } from '@queries/channel/typing';
-import type { ChannelParticipant } from '@queries/channel/types';
-import { type Accessor, createMemo, createSignal, onMount } from 'solid-js';
-import type { SetStoreFunction } from 'solid-js/store';
-import { BaseInput } from './BaseInput';
-import { useSendChannelMessage } from '@block-channel/component/DeprecatedChannelInput/message';
-
-export type ChannelInputProps = {
- channelId: string;
- inputAttachmentsStore: Record<string, InputAttachment[]>;
- setInputAttachmentsStore: SetStoreFunction<Record<string, InputAttachment[]>>;
- inputAttachmentsKey: string;
- channelName: string;
- participants: ChannelParticipant[];
- onFocusLeaveStart?: (e: KeyboardEvent) => void;
- autoFocusOnMount?: boolean;
- domRef?: (ref: HTMLDivElement) => void | HTMLDivElement;
- isDraggingOverChannel?: Accessor<boolean>;
- isValidChannelDrag?: Accessor<boolean>;
-};
-
-export function ChannelInput(props: ChannelInputProps) {
- const sendMessage = useSendChannelMessage(() => props.channelId);
- const typingMutation = usePostTypingUpdateMutation();
-
- const channelUsers = createMemo<IUser[]>(() => {
- return props.participants.map(channelParticipantInfo);
- });
-
- const handleChange = (content: string) => {
- if (!props.channelId) return;
- saveDraftMessage(props.channelId, {
- content,
- attachments: props.inputAttachmentsStore[props.inputAttachmentsKey] ?? [],
- });
- };
-
- const [draftMessage, setDraftMessage] = createSignal<DraftMessage | null>(
- null
- );
-
- onMount(() => {
- if (!props.channelId) return;
- const draft = loadDraftMessage(props.channelId);
- if (draft) {
- setDraftMessage(draft);
- props.setInputAttachmentsStore(
- props.inputAttachmentsKey,
- draft.attachments
- );
- }
- });
-
- return (
- <BaseInput
- placeholder={`Message ${props.channelName} — @mention to share`}
- onStartTyping={() =>
- typingMutation.mutate({ channelId: props.channelId, action: 'start' })
- }
- onStopTyping={() =>
- typingMutation.mutate({ channelId: props.channelId, action: 'stop' })
- }
- onSend={sendMessage}
- afterSend={() => clearDraftMessage(props.channelId)}
- onChange={handleChange}
- initialValue={() => draftMessage()?.content ?? ''}
- inputAttachments={{
- store: props.inputAttachmentsStore,
- setStore: props.setInputAttachmentsStore,
- key: props.inputAttachmentsKey,
- }}
- onFocusLeaveStart={props.onFocusLeaveStart}
- closeDraft={() => clearDraftMessage(props.channelId)}
- channelUsers={channelUsers}
- autoFocusOnMount={props.autoFocusOnMount}
- domRef={props.domRef}
- isDraggingOverChannel={props.isDraggingOverChannel}
- isValidChannelDrag={props.isValidChannelDrag}
- />
- );
-}
-
-export { DraftChannelInput } from './DraftChannelInput';
diff --git a/js/app/packages/block-channel/component/DeprecatedChannelInput/DraftChannelInput.tsx b/js/app/packages/block-channel/component/DeprecatedChannelInput/DraftChannelInput.tsx
deleted file mode 100644
index 7c438886bf..0000000000
--- a/js/app/packages/block-channel/component/DeprecatedChannelInput/DraftChannelInput.tsx
+++ /dev/null
@@ -1,133 +0,0 @@
-import { mapAttachmentsForSend } from '@block-channel/component/DeprecatedChannelInput/inputAttachments';
-import { getDestinationFromOptions } from '@core/component/NewMessage';
-import type { InputAttachment } from '@core/store/cacheChannelInput';
-import type { WithCustomUserInput } from '@core/user';
-import { useSendMessageToPeople } from '@core/util/channels';
-import { isErr } from '@core/util/maybeResult';
-import { commsServiceClient } from '@service-comms/client';
-import type { SimpleMention } from '@service-comms/generated/models/simpleMention';
-import { createSignal, Show } from 'solid-js';
-import { BaseInput } from './BaseInput';
-
-export function DraftChannelInput(props: {
- selectedRecipients: () => WithCustomUserInput<'user' | 'contact'>[];
- channelName: () => string;
- inputAttachments?: {
- store: Record<string, InputAttachment[]>;
- setStore: any;
- key: string;
- };
-}) {
- const [content, setContent] = createSignal('');
-
- const [error, setError] = createSignal(false);
- const [errorMsg, setErrorMsg] = createSignal('');
-
- function failure(msg: string) {
- setError(true);
- setErrorMsg(msg);
- }
-
- const { sendToUsers, sendToChannel } = useSendMessageToPeople();
-
- const handleSend = async (args: {
- content: string | undefined;
- attachments: InputAttachment[];
- threadId?: string;
- mentions?: SimpleMention[];
- }) => {
- setError(false);
- const recipients = props?.selectedRecipients?.();
-
- if (!recipients || recipients.length === 0) {
- const e = 'Please select at least one recipient';
- failure(e);
- throw new Error(e);
- }
-
- if (!args.content?.trim()) {
- const e = 'Please enter a message';
- failure(e);
- throw new Error(e);
- }
-
- const destination = getDestinationFromOptions(recipients);
- if (!destination) {
- const e = 'Invalid destination';
- failure(e);
- throw new Error(e);
- }
- try {
- if (
- destination.type === 'users' &&
- props.channelName() &&
- destination.users.length > 1
- ) {
- const res = await commsServiceClient.createChannel({
- channel_type: 'private',
- name: props.channelName() ?? null,
- participants: destination.users,
- });
- if (isErr(res)) {
- const e = 'Could not create channel';
- failure(e);
- throw new Error(e);
- }
- const [, { id }] = res;
- await sendToChannel({
- channelId: id,
- content: args.content || '',
- mentions: args.mentions || [],
- navigate: { navigate: true, mergeHistory: true },
- attachments: mapAttachmentsForSend(args.attachments),
- });
- } else if (destination.type === 'users') {
- await sendToUsers({
- users: destination.users,
- content: args.content || '',
- mentions: args.mentions || [],
- navigate: { navigate: true, mergeHistory: true },
- attachments: mapAttachmentsForSend(args.attachments),
- });
- } else if (destination.type === 'channel') {
- await sendToChannel({
- channelId: (destination as any).id,
- content: args.content || '',
- mentions: args.mentions || [],
- navigate: { navigate: true, mergeHistory: true },
- attachments: mapAttachmentsForSend(args.attachments),
- });
- }
- setContent('');
- } catch (error) {
- failure('Failed to send message');
- throw error;
- }
- };
-
- return (
- <>
- <Show when={error()}>
- <div class="text-sm font-mono text-failure-ink">{errorMsg()}</div>
- </Show>
- <BaseInput
- autoFocusOnMount={false}
- placeholder={`Send message${props?.channelName?.() ? ` to ${props.channelName()}` : ''}`}
- onStartTyping={() => {}}
- onStopTyping={() => {}}
- onSend={handleSend}
- onChange={setContent}
- closeDraft={() => setContent('')}
- initialValue={() => content()}
- inputAttachments={
- props.inputAttachments || {
- store: {},
- setStore: () => {},
- key: 'draft',
- }
- }
- onFocusLeaveStart={() => {}}
- />
- </>
- );
-}
diff --git a/js/app/packages/block-channel/component/DeprecatedChannelInput/TaskPreviewPanel.tsx b/js/app/packages/block-channel/component/DeprecatedChannelInput/TaskPreviewPanel.tsx
deleted file mode 100644
index 8dcc0821b3..0000000000
--- a/js/app/packages/block-channel/component/DeprecatedChannelInput/TaskPreviewPanel.tsx
+++ /dev/null
@@ -1,46 +0,0 @@
-import type { PropertyApiValues } from '@core/component/Properties/types';
-import type { TaskWithProperties } from '@block-channel/component/DeprecatedChannelInput/taskmode';
-import { For } from 'solid-js';
-import { TaskPreviewRow } from './TaskPreviewRow';
-
-type TaskPreviewPanelProps = {
- tasks: TaskWithProperties[];
- onUpdatePropertyValue: (
- lineIndex: number,
- propertyDefinitionId: string,
- value: PropertyApiValues
- ) => void;
-};
-
-/**
- * Preview panel displaying tasks that will be created when sending a message
- * with Task Mode enabled. Shows task titles with editable property pills.
- */
-export function TaskPreviewPanel(props: TaskPreviewPanelProps) {
- return (
- <div class="w-full border-t border-edge-muted bg-surface-secondary px-3 py-2">
- <div class="flex items-center gap-2 text-xs text-ink-muted mb-2">
- <span>Tasks</span>
- <span class="bg-surface px-1.5 py-0.5 rounded text-xs font-medium">
- {props.tasks.length}
- </span>
- </div>
- <div class="flex flex-col gap-0.5 max-h-32 overflow-y-auto">
- <For each={props.tasks}>
- {(task) => (
- <TaskPreviewRow
- task={task}
- onUpdatePropertyValue={(propertyDefinitionId, value) =>
- props.onUpdatePropertyValue(
- task.lineIndex,
- propertyDefinitionId,
- value
- )
- }
- />
- )}
- </For>
- </div>
- </div>
- );
-}
diff --git a/js/app/packages/block-channel/component/DeprecatedChannelInput/TaskPreviewRow.tsx b/js/app/packages/block-channel/component/DeprecatedChannelInput/TaskPreviewRow.tsx
deleted file mode 100644
index f7dc637593..0000000000
--- a/js/app/packages/block-channel/component/DeprecatedChannelInput/TaskPreviewRow.tsx
+++ /dev/null
@@ -1,221 +0,0 @@
-import type { TaskWithProperties } from '@block-channel/component/DeprecatedChannelInput/taskmode';
-import { EntityIcon } from '@core/component/EntityIcon';
-import { propertyApiValuesToNormalized } from '@core/component/Properties/api/converters';
-import { Modals } from '@core/component/Properties/component/modal';
-import { PropertyValue } from '@core/component/Properties/component/propertyValue/PropertyValue';
-import { SYSTEM_PROPERTY_IDS } from '@core/component/Properties/constants';
-import {
- PropertiesProvider,
- usePropertiesContext,
- type PropertySaveHandler,
-} from '@core/component/Properties/context/PropertiesContext';
-import type {
- Property,
- PropertyApiValues,
- PropertyOption,
-} from '@core/component/Properties/types';
-import { filterMap } from '@core/util/list';
-import type { PropertyDefinition } from '@service-properties/generated/schemas/propertyDefinition';
-import { useListPropertiesQuery } from '@queries/properties/definitions';
-import { queryReadyGate } from '@queries/gate';
-import { createMemo, For, Show } from 'solid-js';
-
-const PREVIEW_PROPERTIES = [
- SYSTEM_PROPERTY_IDS.STATUS,
- SYSTEM_PROPERTY_IDS.PRIORITY,
- SYSTEM_PROPERTY_IDS.DUE_DATE,
- SYSTEM_PROPERTY_IDS.ASSIGNEES,
-];
-
-type TaskPreviewRowProps = {
- task: TaskWithProperties;
- onUpdatePropertyValue: (
- propertyDefinitionId: string,
- value: PropertyApiValues
- ) => void;
-};
-
-function extractPropertyValue(
- definition: PropertyDefinition,
- savedValues: Record<string, PropertyApiValues>,
- options: Map<string, PropertyOption[]>
-) {
- const { type, value } = propertyApiValuesToNormalized(
- savedValues[definition.id]
- );
- if (type === 'EMPTY') return null;
- if (
- definition.data_type === 'SELECT_NUMBER' ||
- definition.data_type === 'SELECT_STRING'
- ) {
- const opts = options.get(definition.id);
- if (!opts) return null;
- if (Array.isArray(value)) {
- return filterMap(value as string[], (id) => {
- const opt = opts.find((opt) => opt.id === id);
- return opt ? opt.id : undefined;
- });
- }
- } else {
- return value;
- }
-}
-
-function TaskPropertyRow(props: {
- task: TaskWithProperties;
- properties: Property[];
-}) {
- const { openDatePicker, openPropertyEditor } = usePropertiesContext();
-
- const handleEdit = (property: Property, anchor?: HTMLElement) => {
- if (property.valueType === 'DATE') {
- openDatePicker(property as Property & { valueType: 'DATE' }, anchor);
- } else {
- openPropertyEditor(property, anchor);
- }
- };
-
- return (
- <div class="flex items-center gap-2 text-sm py-1">
- <EntityIcon targetType="task" size="sm" class="flex-shrink-0" />
- <span class="ph-no-capture truncate flex-1 text-ink min-w-0">
- {props.task.title || '(empty)'}
- </span>
- <div class="ph-no-capture flex items-center gap-0.5 flex-shrink-0">
- <For each={props.properties}>
- {(property) => (
- <PropertyValue
- property={property}
- condensed={property.valueType !== 'DATE'}
- onEdit={handleEdit}
- />
- )}
- </For>
- </div>
- </div>
- );
-}
-
-export function TaskPreviewRow(props: TaskPreviewRowProps) {
- const systemPropertiesQuery = useListPropertiesQuery(
- () => ({
- scope: 'system',
- includeOptions: true,
- forEntityType: 'TASK',
- }),
- () => true
- );
-
- const definitions = createMemo(() => {
- if (!queryReadyGate(systemPropertiesQuery))
- return new Map<string, PropertyDefinition>();
- return new Map(
- systemPropertiesQuery.data.map((p) => {
- const definition = 'definition' in p ? p.definition : p;
- return [definition.id, definition];
- })
- );
- });
-
- const options = createMemo(() => {
- if (!queryReadyGate(systemPropertiesQuery))
- return new Map<string, PropertyOption[]>();
- return new Map(
- systemPropertiesQuery.data.map((p) => {
- const definition = 'definition' in p ? p.definition : p;
- const opts = 'property_options' in p ? p.property_options : [];
- return [definition.id, opts];
- })
- );
- });
-
- const mergedPropertyValues = createMemo(
- (): Record<string, PropertyApiValues> => {
- const values: Record<string, PropertyApiValues> = {};
-
- if (props.task.assigneeUserIds.length > 0) {
- values[SYSTEM_PROPERTY_IDS.ASSIGNEES] = {
- valueType: 'ENTITY',
- refs: props.task.assigneeUserIds.map((id) => ({
- entity_id: id,
- entity_type: 'USER' as const,
- })),
- };
- }
-
- if (props.task.dueDate) {
- values[SYSTEM_PROPERTY_IDS.DUE_DATE] = {
- valueType: 'DATE',
- value: props.task.dueDate,
- };
- }
-
- return { ...values, ...props.task.propertyValues };
- }
- );
-
- // Cast needed: Property is a discriminated union, but we build it dynamically
- // from definition.data_type which TypeScript can't narrow statically
- const properties = createMemo((): Property[] => {
- return filterMap(PREVIEW_PROPERTIES, (id) => {
- const definition = definitions().get(id);
- if (!definition) return;
- return {
- propertyId: `preview-${props.task.lineIndex}-${definition.id}`,
- propertyDefinitionId: definition.id,
- displayName: definition.display_name,
- isMultiSelect: definition.is_multi_select,
- owner: definition.owner,
- specificEntityType: definition.specific_entity_type ?? null,
- updatedAt: new Date(0),
- createdAt: new Date(0),
- valueType: definition.data_type,
- value: extractPropertyValue(
- definition,
- mergedPropertyValues(),
- options()
- ),
- options: options().get(definition.id),
- } as Property;
- });
- });
-
- const saveHandler: PropertySaveHandler = {
- saveProperty: async (property: Property, value: PropertyApiValues) => {
- props.onUpdatePropertyValue(property.propertyDefinitionId, value);
- },
- saveDate: async (property: Property, date: Date) => {
- props.onUpdatePropertyValue(property.propertyDefinitionId, {
- valueType: 'DATE',
- value: date,
- });
- },
- };
-
- return (
- <Show
- when={queryReadyGate(systemPropertiesQuery)}
- fallback={
- <div class="flex items-center gap-2 text-sm py-1 text-ink-muted">
- <EntityIcon targetType="task" size="sm" class="flex-shrink-0" />
- <span class="ph-no-capture truncate flex-1">
- {props.task.title || '(empty)'}
- </span>
- </div>
- }
- >
- <PropertiesProvider
- entityType="TASK"
- canEdit={true}
- properties={properties}
- onRefresh={() => {}}
- onPropertyAdded={() => {}}
- onPropertyDeleted={() => {}}
- saveHandler={saveHandler}
- >
- <TaskPropertyRow task={props.task} properties={properties()} />
- <Modals />
- </PropertiesProvider>
- </Show>
- );
-}
diff --git a/js/app/packages/block-channel/component/DeprecatedChannelInput/draftMessages.ts b/js/app/packages/block-channel/component/DeprecatedChannelInput/draftMessages.ts
deleted file mode 100644
index 5aad083f2d..0000000000
--- a/js/app/packages/block-channel/component/DeprecatedChannelInput/draftMessages.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-import type { DraftMessage } from '@core/store/cacheChannelInput';
-import {
- cachedChannelInputStore,
- setCachedChannelInputStore,
-} from '@core/store/cacheChannelInput';
-
-export function getDraftKey(channelId: string, threadId?: string) {
- return threadId ? `${channelId}_${threadId}` : channelId;
-}
-
-// Debounced per-key save so we can cancel on clear to avoid races
-const pendingSaves = new Map<string, ReturnType<typeof setTimeout>>();
-
-function scheduleSave(
- draftKey: string,
- draft: Omit<DraftMessage, 'lastModified'>
-) {
- const existing = pendingSaves.get(draftKey);
- if (existing) clearTimeout(existing);
- const handle = setTimeout(() => {
- setCachedChannelInputStore(draftKey, {
- ...draft,
- lastModified: Date.now(),
- });
- pendingSaves.delete(draftKey);
- }, 500);
- pendingSaves.set(draftKey, handle);
-}
-
-export function saveDraftMessage(
- channelId: string,
- draft: Omit<DraftMessage, 'lastModified'>
-) {
- const draftKey = getDraftKey(channelId, draft.threadId);
- scheduleSave(draftKey, draft);
-}
-
-export function loadDraftMessage(
- channelId: string,
- threadId?: string
-): DraftMessage | undefined {
- const draftKey = getDraftKey(channelId, threadId);
- return cachedChannelInputStore[draftKey];
-}
-
-export function clearDraftMessage(channelId: string, threadId?: string) {
- const draftKey = getDraftKey(channelId, threadId);
- const pending = pendingSaves.get(draftKey);
- if (pending) {
- clearTimeout(pending);
- pendingSaves.delete(draftKey);
- }
- setCachedChannelInputStore(draftKey, undefined);
-}
-
-export function checkHasDraft(channelId: string, threadId?: string): boolean {
- const draftKey = getDraftKey(channelId, threadId);
- return cachedChannelInputStore[draftKey] !== undefined;
-}
diff --git a/js/app/packages/block-channel/component/DeprecatedChannelInput/inputAttachments.ts b/js/app/packages/block-channel/component/DeprecatedChannelInput/inputAttachments.ts
deleted file mode 100644
index 5fbff40d3e..0000000000
--- a/js/app/packages/block-channel/component/DeprecatedChannelInput/inputAttachments.ts
+++ /dev/null
@@ -1,153 +0,0 @@
-import type { BlockName } from '@core/block';
-import { fileTypeToBlockName } from '@core/constant/allBlocks';
-import type {
- AttachmentType,
- InputAttachment,
-} from '@core/store/cacheChannelInput';
-import {
- isStaticAttachmentType,
- STATIC_IMAGE,
- STATIC_VIDEO,
-} from '@core/store/cacheChannelInput';
-import type { UploadInput } from '@core/util/upload';
-import { chatRuleset, isFileUploadEntry, uploadFile } from '@core/util/upload';
-import type { NewAttachment } from '@service-comms/generated/models';
-import { waitBulkUploadStatus } from '@service-connection/bulkUpload';
-import { blockNameToItemType } from '@service-storage/client';
-import { filenameWithoutExtension } from '@service-storage/util/filename';
-import { toast } from 'core/component/Toast/Toast';
-import type { SetStoreFunction } from 'solid-js/store';
-
-type InputAttachmentsStore = {
- store: Record<string, InputAttachment[]>;
- setStore: SetStoreFunction<Record<string, InputAttachment[]>>;
- key: string;
-};
-
-// Simplified attachment type matching for indicating pending attachment state before upload
-// For example, heic image conversion can be slow so this will show a correct pending state
-function getAttachmentType(fileType?: string): AttachmentType | undefined {
- if (!fileType) return;
-
- if (fileType.startsWith('image/')) {
- return STATIC_IMAGE;
- }
- if (fileType.startsWith('video/')) {
- return STATIC_VIDEO;
- }
-
- // For other files, we'll determine the type after upload
- return undefined;
-}
-
-export function mapAttachmentsForSend(
- attachments: InputAttachment[]
-): NewAttachment[] {
- return attachments
- .map((a) => ({
- entity_id: a.id,
- entity_type: isStaticAttachmentType(a.blockName)
- ? a.blockName
- : blockNameToItemType(a.blockName as BlockName),
- }))
- .filter((a) => a.entity_type !== undefined) as NewAttachment[];
-}
-
-export async function handleFileUpload(
- files: UploadInput[],
- inputAttachmentsStore: InputAttachmentsStore,
- onUploaded?: (attachment: InputAttachment) => void
-) {
- const key = inputAttachmentsStore.key;
-
- for (const entry of files) {
- const file = isFileUploadEntry(entry) ? entry.file : entry;
- const pendingId = crypto.randomUUID();
- const initialAttachmentType = getAttachmentType(file.type);
-
- // Add pending attachment to UI immediately
- const pendingAttachment: InputAttachment = {
- id: pendingId,
- name: file.name,
- blockName: initialAttachmentType || 'unknown',
- pending: true,
- file,
- };
-
- const existingAttachments = inputAttachmentsStore.store[key] ?? [];
- const newAttachments = [...existingAttachments, pendingAttachment];
- inputAttachmentsStore.setStore(key, newAttachments);
-
- try {
- const result = await uploadFile(file, chatRuleset, {
- hideProgressIndicator: true,
- unzipFolder: isFileUploadEntry(entry) && entry.isFolder,
- });
-
- if (!result.failed) {
- // Determine final attachment based on upload destination
- let finalAttachment: InputAttachment;
-
- if (result.destination === 'static') {
- finalAttachment = {
- id: result.id,
- name: file.name,
- blockName: initialAttachmentType || 'unknown',
- pending: false,
- file,
- };
- } else if (result.destination === 'dss' && result.type === 'document') {
- finalAttachment = {
- id: result.documentId,
- name: filenameWithoutExtension(file.name) || file.name,
- blockName: fileTypeToBlockName(result.fileType, true) ?? 'unknown',
- pending: false,
- };
- } else if (result.destination === 'dss' && result.type === 'folder') {
- // Wait for the websocket event to get the projectId
- const projectId = await waitBulkUploadStatus(result.requestId);
- if (!projectId) {
- throw new Error('Folder upload failed or timed out');
- }
-
- finalAttachment = {
- id: projectId,
- name: result.name,
- blockName: 'project',
- pending: false,
- };
- } else {
- throw new Error('Unexpected upload result');
- }
-
- // Update the attachment in place
- inputAttachmentsStore.setStore(key, (prev = []) => {
- const index = prev.findIndex((a) => a.id === pendingId);
- if (index < 0) return prev;
- return [
- ...prev.slice(0, index),
- finalAttachment,
- ...prev.slice(index + 1),
- ];
- });
-
- onUploaded?.(finalAttachment);
- } else {
- // Remove failed attachment
- inputAttachmentsStore.setStore(key, (prev = []) =>
- prev.filter((a) => a.id !== pendingId)
- );
- if (result.error) {
- toast.failure(`Failed to upload ${file.name}: ${result.error}`);
- }
- }
- } catch (error) {
- console.error('File upload error:', error);
- toast.failure(`Failed to upload file: ${file.name}`);
- // Remove failed attachment
- inputAttachmentsStore.setStore(key, (prev = []) =>
- prev.filter((a) => a.id !== pendingId)
- );
- }
- }
-}
diff --git a/js/app/packages/block-channel/component/DeprecatedChannelInput/mentionExpansion.ts b/js/app/packages/block-channel/component/DeprecatedChannelInput/mentionExpansion.ts
deleted file mode 100644
index 131f2d88bb..0000000000
--- a/js/app/packages/block-channel/component/DeprecatedChannelInput/mentionExpansion.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-import { $isSingleDocumentMention } from '@core/component/LexicalMarkdown/utils';
-import { $convertMentionToCard, $isDocumentMentionNode } from '@lexical-core';
-import type { SimpleMention } from '@service-comms/generated/models/simpleMention';
-import { $getRoot, $isParagraphNode } from 'lexical';
-
-export type MentionItem = {
- itemType: string;
- itemId: string;
-};
-
-/**
- * Expands group participants to individual user mentions, deduplicating against seen users.
- */
-export function expandGroupParticipants(
- participants: string[],
- seenUserIds: Set<string>
-): SimpleMention[] {
- const result: SimpleMention[] = [];
- for (const userId of participants) {
- if (!seenUserIds.has(userId)) {
- seenUserIds.add(userId);
- result.push({ entity_type: 'user', entity_id: userId });
- }
- }
- return result;
-}
-
-/**
- * Converts a mention to SimpleMention format, deduplicating user mentions against seen users.
- * Returns null if the mention is a duplicate user.
- */
-export function toSimpleMention(
- mention: MentionItem,
- seenUserIds: Set<string>
-): SimpleMention | null {
- if (mention.itemType === 'user') {
- if (seenUserIds.has(mention.itemId)) return null;
- seenUserIds.add(mention.itemId);
- }
- return { entity_type: mention.itemType, entity_id: mention.itemId };
-}
-
-export function $convertSingleMentionToCard() {
- if ($isSingleDocumentMention()) {
- const root = $getRoot();
- const rootChildren = root.getChildren();
- if (rootChildren.length > 0) {
- const firstChild = rootChildren[0];
- if ($isParagraphNode(firstChild)) {
- const paragraphChildren = firstChild.getChildren();
- if (paragraphChildren.length > 0) {
- const mention = paragraphChildren[0];
- console.log({ mention });
- if ($isDocumentMentionNode(mention)) {
- $convertMentionToCard(mention);
- }
- }
- }
- }
- }
-}
diff --git a/js/app/packages/block-channel/component/DeprecatedChannelInput/message.tsx b/js/app/packages/block-channel/component/DeprecatedChannelInput/message.tsx
deleted file mode 100644
index 1dafcc75ab..0000000000
--- a/js/app/packages/block-channel/component/DeprecatedChannelInput/message.tsx
+++ /dev/null
@@ -1,100 +0,0 @@
-import {
- type InputAttachment,
- isStaticAttachmentType,
-} from '@core/store/cacheChannelInput';
-import { getImageDimensions, getVideoDimensions } from '@core/util/media';
-import { useSendMessageMutation } from '@queries/channel/message';
-import { invalidateListChannels } from '@queries/channel/channels';
-import type { NewAttachment } from '@service-comms/generated/models';
-import type { SimpleMention } from '@service-comms/generated/models/simpleMention';
-import { useUserId } from '@core/context/user';
-import { blockNameToItemType } from '@service-storage/client';
-import type { Accessor } from 'solid-js';
-
-function isMessageSendable(
- content: string | undefined,
- attachments: InputAttachment[]
-): boolean {
- return (content && content.trim().length > 0) || attachments.length > 0;
-}
-
-export type SendMessageArgs = {
- content: string | undefined;
- attachments: InputAttachment[];
- threadId?: string;
- mentions?: SimpleMention[];
-};
-
-export function useSendChannelMessage(channelID: Accessor<string>) {
- const userId = useUserId();
-
- const mutation = useSendMessageMutation({
- onSettled() {
- invalidateListChannels();
- },
- });
-
- return async ({
- content,
- attachments,
- threadId,
- mentions,
- }: SendMessageArgs) => {
- if (!userId) return;
- if (!isMessageSendable(content, attachments)) return;
-
- const channelId = channelID();
- const senderId = userId()!;
- const optimisticId = crypto.randomUUID();
-
- const attachmentsToSend = await Promise.allSettled(
- attachments.map(async (a) => {
- const attachmentType = isStaticAttachmentType(a.blockName)
- ? a.blockName
- : blockNameToItemType(a.blockName);
-
- if (!attachmentType) return;
-
- let attachment: NewAttachment = {
- entity_id: a.id,
- entity_type: attachmentType,
- };
-
- if (!a.file) return attachment;
-
- if (
- attachmentType !== 'static/image' &&
- attachmentType !== 'static/video'
- ) {
- return attachment;
- }
-
- const dimensions =
- attachmentType === 'static/image'
- ? await getImageDimensions(a.file)
- : await getVideoDimensions(a.file);
-
- attachment.width = dimensions.width;
- attachment.height = dimensions.height;
-
- return attachment;
- })
- );
-
- const filteredAttachements = attachmentsToSend
- .map((r) => (r.status === 'fulfilled' ? r.value : undefined))
- .filter((r) => r !== undefined);
-
- await mutation.mutateAsync({
- channelID: channelId,
- optimisticId,
- senderId,
- message: {
- attachments: filteredAttachements,
- content: content ?? '',
- thread_id: threadId,
- mentions: mentions ?? [],
- },
- });
- };
-}
diff --git a/js/app/packages/block-channel/component/DeprecatedChannelInput/taskModeConversion.ts b/js/app/packages/block-channel/component/DeprecatedChannelInput/taskModeConversion.ts
deleted file mode 100644
index 8399e83f5c..0000000000
--- a/js/app/packages/block-channel/component/DeprecatedChannelInput/taskModeConversion.ts
+++ /dev/null
@@ -1,181 +0,0 @@
-import type { TaskWithProperties } from './taskmode';
-import { propertyValueToApi } from '@core/component/Properties/api/converters';
-import {
- PROPERTY_OPTION_IDS,
- SYSTEM_PROPERTY_IDS,
-} from '@core/component/Properties/constants';
-import { createTask } from '@core/util/create';
-import type { PropertyInput } from '@service-storage/generated/schemas/propertyInput';
-import { err, ok, type Result } from 'neverthrow';
-
-export type TaskCreationSuccess = {
- lineIndex: number;
- documentId: string;
- title: string;
-};
-
-export type TaskCreationError = {
- lineIndex: number;
- error: string;
-};
-
-export type TaskCreationResults = {
- successes: TaskCreationSuccess[];
- errors: TaskCreationError[];
-};
-
-export type TaskCreationOptions = {
- currentUserId?: string;
-};
-
-function buildPropertyInputs(
- task: TaskWithProperties,
- options: TaskCreationOptions
-): PropertyInput[] {
- const properties: PropertyInput[] = [];
-
- for (const [propertyId, apiValue] of Object.entries(task.propertyValues)) {
- // Only ASSIGNEES is multi-select; STATUS and PRIORITY are single-select
- const isMultiSelect = propertyId === SYSTEM_PROPERTY_IDS.ASSIGNEES;
-
- const value = propertyValueToApi(apiValue, isMultiSelect);
- if (value !== null) {
- properties.push({ propertyId, value });
- }
- }
-
- if (
- task.assigneeUserIds.length > 0 &&
- !task.propertyValues[SYSTEM_PROPERTY_IDS.ASSIGNEES]
- ) {
- properties.push({
- propertyId: SYSTEM_PROPERTY_IDS.ASSIGNEES,
- value: {
- type: 'multi_entity_reference',
- references: task.assigneeUserIds.map((id) => ({
- entity_id: id,
- entity_type: 'USER' as const,
- })),
- },
- });
- } else if (
- !task.propertyValues[SYSTEM_PROPERTY_IDS.ASSIGNEES] &&
- options.currentUserId
- ) {
- properties.push({
- propertyId: SYSTEM_PROPERTY_IDS.ASSIGNEES,
- value: {
- type: 'multi_entity_reference',
- references: [
- { entity_id: options.currentUserId, entity_type: 'USER' as const },
- ],
- },
- });
- }
-
- if (!task.propertyValues[SYSTEM_PROPERTY_IDS.STATUS]) {
- properties.push({
- propertyId: SYSTEM_PROPERTY_IDS.STATUS,
- value: {
- type: 'select_option',
- option_id: PROPERTY_OPTION_IDS.STATUS.NOT_STARTED,
- },
- });
- }
-
- if (task.dueDate && !task.propertyValues[SYSTEM_PROPERTY_IDS.DUE_DATE]) {
- properties.push({
- propertyId: SYSTEM_PROPERTY_IDS.DUE_DATE,
- value: { type: 'date', value: task.dueDate.toISOString() },
- });
- }
-
- return properties;
-}
-
-async function createSingleTask(
- task: TaskWithProperties,
- options: TaskCreationOptions
-): Promise<Result<TaskCreationSuccess, TaskCreationError>> {
- if (!task.title.trim()) {
- return err({ lineIndex: task.lineIndex, error: 'Empty task title' });
- }
-
- try {
- const propertyValues = buildPropertyInputs(task, options);
-
- const documentId = await createTask({
- title: task.title,
- content: '',
- propertyValues: propertyValues.length > 0 ? propertyValues : undefined,
- });
-
- if (!documentId) {
- return err({ lineIndex: task.lineIndex, error: 'Failed to create task' });
- }
-
- return ok({
- lineIndex: task.lineIndex,
- documentId,
- title: task.title,
- });
- } catch (error) {
- return err({
- lineIndex: task.lineIndex,
- error: error instanceof Error ? error.message : 'Unknown error',
- });
- }
-}
-
-export async function createTasksFromPotential(
- tasks: TaskWithProperties[],
- options: TaskCreationOptions
-): Promise<TaskCreationResults> {
- const results = await Promise.all(
- tasks.map((task) => createSingleTask(task, options))
- );
-
- const successes: TaskCreationSuccess[] = [];
- const errors: TaskCreationError[] = [];
-
- for (const result of results) {
- if (result.isOk()) {
- successes.push(result.value);
- } else {
- errors.push(result.error);
- }
- }
-
- return { successes, errors };
-}
-
-function createTaskMentionMarkdown(documentId: string, title: string): string {
- const data = JSON.stringify({
- documentId,
- documentName: title,
- blockName: 'task',
- });
- return `<m-document-mention>${data}</m-document-mention>`;
-}
-
-export function replaceCheckboxesWithMentions(
- markdown: string,
- createdTasks: TaskCreationSuccess[]
-): string {
- const lines = markdown.split('\n');
-
- const taskByLine = new Map<number, TaskCreationSuccess>();
- for (const task of createdTasks) {
- taskByLine.set(task.lineIndex, task);
- }
-
- const resultLines = lines.map((line, index) => {
- const task = taskByLine.get(index);
- if (task) {
- return createTaskMentionMarkdown(task.documentId, task.title);
- }
- return line;
- });
-
- return resultLines.join('\n');
-}
diff --git a/js/app/packages/block-channel/component/DeprecatedChannelInput/taskmode.tsx b/js/app/packages/block-channel/component/DeprecatedChannelInput/taskmode.tsx
deleted file mode 100644
index 27cdeb6920..0000000000
--- a/js/app/packages/block-channel/component/DeprecatedChannelInput/taskmode.tsx
+++ /dev/null
@@ -1,124 +0,0 @@
-import type { PropertyApiValues } from '@core/component/Properties/types';
-import {
- extractCheckboxesFromMarkdown,
- type PotentialTask,
-} from '@core/util/taskExtraction';
-import { debounce } from '@solid-primitives/scheduled';
-import {
- type Accessor,
- createEffect,
- createMemo,
- createSignal,
- on,
-} from 'solid-js';
-import { createStore, reconcile } from 'solid-js/store';
-
-const DEBOUNCE_MS = 300;
-
-/** Extended task with property values in API format */
-export type TaskWithProperties = PotentialTask & {
- propertyValues: Record<string, PropertyApiValues>;
-};
-
-type UseTaskModeReturn = {
- /** Whether task mode is currently enabled */
- taskModeEnabled: Accessor<boolean>;
- /** Toggle task mode on/off */
- toggleTaskMode: () => void;
- /** Set task mode enabled state directly */
- setTaskModeEnabled: (enabled: boolean) => void;
- /** Potential tasks detected in current content (debounced) */
- potentialTasks: Accessor<TaskWithProperties[]>;
- /** Update a property value on a specific task */
- updateTaskPropertyValue: (
- lineIndex: number,
- propertyDefinitionId: string,
- value: PropertyApiValues
- ) => void;
- /** Clear all task property values (call after send) */
- resetTaskProperties: () => void;
-};
-
-/**
- * Hook for managing task mode state in the channel message input.
- * When task mode is enabled, continuously parses checkboxes from the
- * markdown content (debounced) to preview what tasks will be created on send.
- *
- * @param markdownState - Accessor for the current markdown content
- * @returns Task mode state and controls
- */
-export function useTaskMode(
- markdownState: Accessor<string>
-): UseTaskModeReturn {
- const [taskModeEnabled, setTaskModeEnabled] = createSignal(false);
- const [debouncedMarkdown, setDebouncedMarkdown] = createSignal('');
-
- // Store property values per task (keyed by lineIndex, then propertyDefinitionId)
- const [taskPropertyValues, setTaskPropertyValues] = createStore<
- Record<number, Record<string, PropertyApiValues>>
- >({});
-
- const updateDebouncedMarkdown = debounce(
- (content: string) => setDebouncedMarkdown(content),
- DEBOUNCE_MS
- );
-
- createEffect(
- on(
- () => (taskModeEnabled() ? markdownState() : null),
- (markdown) => {
- if (markdown !== null) {
- updateDebouncedMarkdown(markdown);
- }
- },
- { defer: true }
- )
- );
-
- const potentialTasks = createMemo<TaskWithProperties[]>(() => {
- if (!taskModeEnabled()) return [];
- const markdown = debouncedMarkdown();
- if (!markdown) return [];
-
- const extracted = extractCheckboxesFromMarkdown(markdown);
-
- return extracted.map((task) => ({
- ...task,
- propertyValues: taskPropertyValues[task.lineIndex] ?? {},
- }));
- });
-
- const toggleTaskMode = () => {
- const newState = !taskModeEnabled();
- setTaskModeEnabled(newState);
- if (newState) {
- setDebouncedMarkdown(markdownState());
- } else {
- setTaskPropertyValues(reconcile({}));
- }
- };
-
- const updateTaskPropertyValue = (
- lineIndex: number,
- propertyDefinitionId: string,
- value: PropertyApiValues
- ) => {
- setTaskPropertyValues(lineIndex, (prev) => ({
- ...prev,
- [propertyDefinitionId]: value,
- }));
- };
-
- const resetTaskProperties = () => {
- setTaskPropertyValues(reconcile({}));
- };
-
- return {
- taskModeEnabled,
- toggleTaskMode,
- setTaskModeEnabled,
- potentialTasks,
- updateTaskPropertyValue,
- resetTaskProperties,
- };
-}