Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(prop-panel): autocomplete src input against workspace assets (#1647)

Abrahambe07fb7473f4
diff --git a/packages/app/src/components/PageListContext.tsx b/packages/app/src/components/PageListContext.tsx
index 8304e4aa0..9522d4f27 100644
--- a/packages/app/src/components/PageListContext.tsx
+++ b/packages/app/src/components/PageListContext.tsx
@@ -263,3 +263,7 @@ export function usePageList(): PageListContextValue {
}
return ctx;
}
+
+export function useOptionalPageList(): PageListContextValue | null {
+ return use(PageListContext);
+}
diff --git a/packages/app/src/editor/components/PropPanel.tsx b/packages/app/src/editor/components/PropPanel.tsx
index 6c42cedce..ae209f630 100644
--- a/packages/app/src/editor/components/PropPanel.tsx
+++ b/packages/app/src/editor/components/PropPanel.tsx
@@ -18,6 +18,7 @@ import {
import { Switch } from '@/components/ui/switch';
import { ColorPickerInput } from '@/editor/components/ColorPickerInput.tsx';
import { IconPickerInput } from '@/editor/components/IconPickerInput.tsx';
+import { SrcAutocomplete } from '@/editor/components/SrcAutocomplete.tsx';
import { uploadFile } from '@/editor/image-upload/upload-file.ts';
import type { JsxComponentDescriptor } from '@/editor/registry/types.ts';
import { getAutoFocusedPropName, humanizePropName } from '@/editor/utils/editor-strings.ts';
@@ -310,25 +311,46 @@ function PropControl({
{humanizePropName(propDef.name)}
</label>
<div className="flex gap-1">
- <Input
- id={stringId}
- type="text"
- value={currentStringValue}
- placeholder={mediaPlaceholder}
- onChange={(e) => {
- const raw = e.target.value;
- if (raw === '' && treatEmptyAsUndefined) {
- onChange(undefined);
- return;
- }
- onChange(raw);
- }}
- autoFocus={isAutoFocused}
- data-prop-autofocus={isAutoFocused ? '' : undefined}
- aria-invalid={mediaErrorMessage !== null ? true : undefined}
- aria-describedby={mediaErrorMessage !== null ? `${stringId}-error` : undefined}
- className="h-7 text-sm"
- />
+ {accept !== undefined ? (
+ <SrcAutocomplete
+ id={stringId}
+ value={currentStringValue}
+ onChange={(raw) => {
+ if (raw === '' && treatEmptyAsUndefined) {
+ onChange(undefined);
+ return;
+ }
+ onChange(raw);
+ }}
+ accept={accept}
+ placeholder={mediaPlaceholder}
+ autoFocus={isAutoFocused}
+ dataPropAutofocus={isAutoFocused ? '' : undefined}
+ ariaInvalid={mediaErrorMessage !== null ? true : undefined}
+ ariaDescribedBy={mediaErrorMessage !== null ? `${stringId}-error` : undefined}
+ className="h-7 text-sm"
+ />
+ ) : (
+ <Input
+ id={stringId}
+ type="text"
+ value={currentStringValue}
+ placeholder={mediaPlaceholder}
+ onChange={(e) => {
+ const raw = e.target.value;
+ if (raw === '' && treatEmptyAsUndefined) {
+ onChange(undefined);
+ return;
+ }
+ onChange(raw);
+ }}
+ autoFocus={isAutoFocused}
+ data-prop-autofocus={isAutoFocused ? '' : undefined}
+ aria-invalid={mediaErrorMessage !== null ? true : undefined}
+ aria-describedby={mediaErrorMessage !== null ? `${stringId}-error` : undefined}
+ className="h-7 text-sm"
+ />
+ )}
{showUpload && <PropUploadButton accept={accept} onUploaded={(url) => onChange(url)} />}
</div>
{mediaErrorMessage !== null && (
diff --git a/packages/app/src/editor/components/SrcAutocomplete.dom.test.tsx b/packages/app/src/editor/components/SrcAutocomplete.dom.test.tsx
new file mode 100644
index 000000000..3fab8af05
--- /dev/null
+++ b/packages/app/src/editor/components/SrcAutocomplete.dom.test.tsx
@@ -0,0 +1,209 @@
+import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+import { ALLOWED_IMAGE_MIME_TYPES } from '@inkeep/open-knowledge-core';
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+
+type GlobalShims = typeof globalThis & {
+ ResizeObserver?: unknown;
+ DOMRect?: unknown;
+};
+const g = globalThis as GlobalShims;
+if (g.ResizeObserver === undefined) {
+ class NoopResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ g.ResizeObserver = NoopResizeObserver;
+}
+const ElementProto = Element.prototype as Element & {
+ hasPointerCapture?: () => boolean;
+ releasePointerCapture?: () => void;
+ scrollIntoView?: () => void;
+};
+ElementProto.hasPointerCapture ??= () => false;
+ElementProto.releasePointerCapture ??= () => {};
+ElementProto.scrollIntoView ??= () => {};
+
+const stubAssetPaths = new Set<string>();
+const stubPageListValue = {
+ pages: new Set<string>(),
+ pagesBySlug: new Map<string, string>(),
+ pagesByBasename: new Map<string, string>(),
+ pageTitles: new Map<string, string>(),
+ pageMeta: new Map<string, unknown>(),
+ folderPaths: new Set<string>(),
+ assetPaths: stubAssetPaths,
+ loading: false,
+ error: null,
+ refetch: () => {},
+ addPage: () => {},
+};
+mock.module('@/components/PageListContext', () => ({
+ usePageList: () => stubPageListValue,
+ useOptionalPageList: () => stubPageListValue,
+}));
+
+const { SrcAutocomplete } = await import('./SrcAutocomplete');
+
+beforeEach(() => {
+ stubAssetPaths.clear();
+});
+
+afterEach(() => {
+ cleanup();
+});
+
+function getOptions(): HTMLButtonElement[] {
+ return screen.queryAllByTestId('src-autocomplete-option') as HTMLButtonElement[];
+}
+
+describe('SrcAutocomplete — open behavior', () => {
+ test('focus on an empty input with matching assets → popover opens with up to 8 source-order items', () => {
+ for (let i = 0; i < 10; i++) stubAssetPaths.add(`assets/photo-${i}.png`);
+
+ render(
+ <SrcAutocomplete
+ id="prop-src"
+ value=""
+ onChange={() => {}}
+ accept={ALLOWED_IMAGE_MIME_TYPES}
+ />,
+ );
+
+ const input = document.getElementById('prop-src') as HTMLInputElement;
+ fireEvent.focus(input);
+
+ const options = getOptions();
+ expect(options).toHaveLength(8);
+ expect(options[0]?.textContent).toContain('photo-0.png');
+ expect(options[7]?.textContent).toContain('photo-7.png');
+ });
+
+ test('focus with zero matching assets → popover stays closed (no chrome flash)', () => {
+ stubAssetPaths.add('docs/handbook.pdf');
+
+ render(
+ <SrcAutocomplete
+ id="prop-src"
+ value=""
+ onChange={() => {}}
+ accept={ALLOWED_IMAGE_MIME_TYPES}
+ />,
+ );
+
+ const input = document.getElementById('prop-src') as HTMLInputElement;
+ fireEvent.focus(input);
+
+ expect(getOptions()).toHaveLength(0);
+ });
+
+ test('descriptor accept filters assets before display (image accept → no mp4 in list)', () => {
+ stubAssetPaths.add('assets/photo.png');
+ stubAssetPaths.add('assets/clip.mp4');
+
+ render(
+ <SrcAutocomplete
+ id="prop-src"
+ value=""
+ onChange={() => {}}
+ accept={ALLOWED_IMAGE_MIME_TYPES}
+ />,
+ );
+
+ const input = document.getElementById('prop-src') as HTMLInputElement;
+ fireEvent.focus(input);
+
+ const labels = getOptions().map((b) => b.textContent ?? '');
+ expect(labels.some((t) => t.includes('photo.png'))).toBe(true);
+ expect(labels.some((t) => t.includes('clip.mp4'))).toBe(false);
+ });
+});
+
+describe('SrcAutocomplete — selection contract', () => {
+ test('clicking a suggestion emits onChange with leading-slash server-absolute path', () => {
+ stubAssetPaths.add('assets/photo.png');
+ const onChange = mock((_v: string) => {});
+
+ render(
+ <SrcAutocomplete
+ id="prop-src"
+ value=""
+ onChange={onChange}
+ accept={ALLOWED_IMAGE_MIME_TYPES}
+ />,
+ );
+
+ const input = document.getElementById('prop-src') as HTMLInputElement;
+ fireEvent.focus(input);
+
+ const option = getOptions()[0];
+ if (!option) throw new Error('expected an option to render');
+ fireEvent.mouseDown(option);
+
+ expect(onChange).toHaveBeenCalledTimes(1);
+ expect(onChange).toHaveBeenCalledWith('/assets/photo.png');
+ });
+
+ test('typing then Enter on the highlighted item emits onChange with the path', () => {
+ stubAssetPaths.add('assets/photo.png');
+ stubAssetPaths.add('assets/banner.png');
+ const onChange = mock((_v: string) => {});
+
+ render(
+ <SrcAutocomplete
+ id="prop-src"
+ value=""
+ onChange={onChange}
+ accept={ALLOWED_IMAGE_MIME_TYPES}
+ />,
+ );
+
+ const input = document.getElementById('prop-src') as HTMLInputElement;
+ fireEvent.focus(input);
+ fireEvent.keyDown(input, { key: 'ArrowDown' });
+ fireEvent.keyDown(input, { key: 'Enter' });
+
+ expect(onChange).toHaveBeenCalledTimes(1);
+ expect(onChange).toHaveBeenCalledWith('/assets/banner.png');
+ });
+});
+
+describe('SrcAutocomplete — keyboard handling', () => {
+ test('Escape closes the popover (subsequent focus reopens it)', () => {
+ stubAssetPaths.add('assets/photo.png');
+
+ render(
+ <SrcAutocomplete
+ id="prop-src"
+ value=""
+ onChange={() => {}}
+ accept={ALLOWED_IMAGE_MIME_TYPES}
+ />,
+ );
+
+ const input = document.getElementById('prop-src') as HTMLInputElement;
+ fireEvent.focus(input);
+ expect(getOptions().length).toBe(1);
+
+ fireEvent.keyDown(input, { key: 'Escape' });
+ expect(getOptions().length).toBe(0);
+ });
+
+ test('Enter with no matching suggestions is a no-op (does NOT call onChange)', () => {
+ const onChange = mock((_v: string) => {});
+
+ render(
+ <SrcAutocomplete
+ id="prop-src"
+ value=""
+ onChange={onChange}
+ accept={ALLOWED_IMAGE_MIME_TYPES}
+ />,
+ );
+
+ const input = document.getElementById('prop-src') as HTMLInputElement;
+ fireEvent.focus(input);
+ fireEvent.keyDown(input, { key: 'Enter' });
+ expect(onChange).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/app/src/editor/components/SrcAutocomplete.tsx b/packages/app/src/editor/components/SrcAutocomplete.tsx
new file mode 100644
index 000000000..b06705057
--- /dev/null
+++ b/packages/app/src/editor/components/SrcAutocomplete.tsx
@@ -0,0 +1,251 @@
+import {
+ createWorkspaceSearchCorpus,
+ createWorkspaceSearchDocument,
+ searchWorkspaceCorpus,
+ type WorkspaceSearchCorpus,
+} from '@inkeep/open-knowledge-core';
+import type { ReactNode } from 'react';
+import { useEffect, useId, useRef, useState } from 'react';
+import { useOptionalPageList } from '@/components/PageListContext';
+import { Input } from '@/components/ui/input';
+import { Popover, PopoverAnchor, PopoverContent } from '@/components/ui/popover';
+import { cn } from '@/lib/utils';
+import { filterAssetsByAccept } from '../utils/filter-assets-by-accept';
+
+const MAX_ITEMS = 8;
+
+/** Module-level shared instance to keep `assetPaths` referentially stable
+ * in the no-provider case (so the React Compiler can elide rerenders).
+ */
+const EMPTY_ASSET_SET: ReadonlySet<string> = new Set();
+
+interface SrcAutocompleteProps {
+ value: string;
+ onChange: (value: string) => void;
+ accept: readonly string[];
+ id: string;
+ placeholder?: string;
+ autoFocus?: boolean;
+ ariaInvalid?: boolean;
+ ariaDescribedBy?: string;
+ dataPropAutofocus?: string;
+ className?: string;
+}
+
+interface AssetItem {
+ path: string;
+ basename: string;
+}
+
+interface AutocompleteCorpus {
+ fingerprint: string;
+ byPath: ReadonlyMap<string, AssetItem>;
+ corpus: WorkspaceSearchCorpus;
+ itemsInOrder: readonly AssetItem[];
+}
+
+let cachedCorpus: AutocompleteCorpus | null = null;
+
+function makeAssetItem(path: string): AssetItem {
+ const basename = path.split('/').pop() ?? path;
+ return { path, basename };
+}
+
+function getCachedCorpus(items: readonly AssetItem[]): AutocompleteCorpus {
+ const fingerprint = items.map((item) => item.path).join('');
+ if (cachedCorpus?.fingerprint === fingerprint) return cachedCorpus;
+ cachedCorpus = {
+ fingerprint,
+ byPath: new Map(items.map((item) => [item.path, item])),
+ itemsInOrder: items,
+ corpus: createWorkspaceSearchCorpus(
+ items.map((item) =>
+ createWorkspaceSearchDocument({
+ kind: 'page',
+ path: item.path,
+ title: item.basename,
+ }),
+ ),
+ ),
+ };
+ return cachedCorpus;
+}
+
+function normalizeQueryForSearch(raw: string): string {
+ const trimmed = raw.trim();
+ if (trimmed.startsWith('/')) return trimmed.slice(1);
+ return trimmed;
+}
+
+function selectSuggestions(corpus: AutocompleteCorpus, rawQuery: string): readonly AssetItem[] {
+ const query = normalizeQueryForSearch(rawQuery);
+ if (!query) return corpus.itemsInOrder.slice(0, MAX_ITEMS);
+ return searchWorkspaceCorpus(corpus.corpus, query, {
+ intent: 'autocomplete',
+ limit: MAX_ITEMS,
+ })
+ .map((result) => corpus.byPath.get(result.document.path))
+ .filter((item): item is AssetItem => Boolean(item));
+}
+
+export function SrcAutocomplete({
+ value,
+ onChange,
+ accept,
+ id,
+ placeholder,
+ autoFocus,
+ ariaInvalid,
+ ariaDescribedBy,
+ dataPropAutofocus,
+ className,
+}: SrcAutocompleteProps): ReactNode {
+ const pageList = useOptionalPageList();
+ const assetPaths: ReadonlySet<string> = pageList?.assetPaths ?? EMPTY_ASSET_SET;
+
+ const matchingPaths = filterAssetsByAccept(assetPaths, accept);
+ const assetItems: readonly AssetItem[] = matchingPaths.map(makeAssetItem);
+ const corpus = getCachedCorpus(assetItems);
+ const suggestions = selectSuggestions(corpus, value);
+
+ const [open, setOpen] = useState(false);
+ const [highlight, setHighlight] = useState(0);
+
+ useEffect(() => {
+ if (highlight >= suggestions.length) setHighlight(0);
+ }, [highlight, suggestions.length]);
+
+ const listboxId = useId();
+ const inputRef = useRef<HTMLInputElement | null>(null);
+
+ const wantOpen = open && suggestions.length > 0;
+
+ const selectSuggestion = (item: AssetItem) => {
+ onChange(`/${item.path}`);
+ setOpen(false);
+ setHighlight(0);
+ inputRef.current?.focus();
+ };
+
+ return (
+ <Popover open={wantOpen} onOpenChange={(next) => setOpen(next)}>
+ <PopoverAnchor asChild>
+ <Input
+ ref={inputRef}
+ id={id}
+ type="text"
+ value={value}
+ placeholder={placeholder}
+ autoFocus={autoFocus}
+ data-prop-autofocus={dataPropAutofocus}
+ aria-invalid={ariaInvalid}
+ aria-describedby={ariaDescribedBy}
+ role="combobox"
+ aria-autocomplete="list"
+ aria-expanded={wantOpen}
+ aria-controls={wantOpen ? listboxId : undefined}
+ aria-activedescendant={
+ wantOpen && suggestions[highlight] ? `${listboxId}-opt-${highlight}` : undefined
+ }
+ className={className}
+ onChange={(e) => {
+ onChange(e.target.value);
+ setOpen(true);
+ setHighlight(0);
+ }}
+ onFocus={() => {
+ setOpen(true);
+ }}
+ onClick={() => {
+ setOpen(true);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === 'ArrowDown') {
+ if (suggestions.length === 0) return;
+ e.preventDefault();
+ setOpen(true);
+ setHighlight((h) => (h + 1) % suggestions.length);
+ return;
+ }
+ if (e.key === 'ArrowUp') {
+ if (suggestions.length === 0) return;
+ e.preventDefault();
+ setOpen(true);
+ setHighlight((h) => (h - 1 + suggestions.length) % suggestions.length);
+ return;
+ }
+ if (e.key === 'Enter') {
+ if (!wantOpen) return;
+ const item = suggestions[highlight];
+ if (!item) return;
+ e.preventDefault();
+ selectSuggestion(item);
+ return;
+ }
+ if (e.key === 'Escape') {
+ if (!wantOpen) return;
+ e.preventDefault();
+ e.stopPropagation();
+ setOpen(false);
+ return;
+ }
+ if (e.key === 'Tab') {
+ setOpen(false);
+ }
+ }}
+ />
+ </PopoverAnchor>
+ <PopoverContent
+ align="start"
+ sideOffset={4}
+ className="z-70 w-[--radix-popover-trigger-width] p-1"
+ onOpenAutoFocus={(e) => {
+ e.preventDefault();
+ }}
+ onCloseAutoFocus={(e) => {
+ e.preventDefault();
+ }}
+ onInteractOutside={(e) => {
+ const target = e.target;
+ if (target instanceof Node && inputRef.current?.contains(target)) {
+ e.preventDefault();
+ }
+ }}
+ >
+ <ul id={listboxId} aria-label="Asset suggestions" className="flex flex-col gap-px">
+ {suggestions.map((item, idx) => {
+ const optionId = `${listboxId}-opt-${idx}`;
+ const isHighlighted = idx === highlight;
+ return (
+ <li key={item.path}>
+ <button
+ id={optionId}
+ type="button"
+ role="option"
+ aria-selected={isHighlighted}
+ data-testid="src-autocomplete-option"
+ data-highlighted={isHighlighted ? '' : undefined}
+ className={cn(
+ 'flex w-full flex-col items-start gap-0.5 rounded-sm px-2 py-1 text-left text-xs',
+ 'transition-colors',
+ isHighlighted ? 'bg-accent text-accent-foreground' : 'hover:bg-accent/50',
+ )}
+ onMouseEnter={() => setHighlight(idx)}
+ onMouseDown={(e) => {
+ e.preventDefault();
+ selectSuggestion(item);
+ }}
+ >
+ <span className="font-medium">{item.basename}</span>
+ {item.basename !== item.path && (
+ <span className="text-muted-foreground/70">{item.path}</span>
+ )}
+ </button>
+ </li>
+ );
+ })}
+ </ul>
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/packages/app/src/editor/utils/filter-assets-by-accept.test.ts b/packages/app/src/editor/utils/filter-assets-by-accept.test.ts
new file mode 100644
index 000000000..7b77f1dc6
--- /dev/null
+++ b/packages/app/src/editor/utils/filter-assets-by-accept.test.ts
@@ -0,0 +1,102 @@
+import { describe, expect, test } from 'bun:test';
+import {
+ ALLOWED_AUDIO_MIME_TYPES,
+ ALLOWED_IMAGE_MIME_TYPES,
+ ALLOWED_PDF_MIME_TYPES,
+ ALLOWED_VIDEO_MIME_TYPES,
+} from '@inkeep/open-knowledge-core';
+import { filterAssetsByAccept } from './filter-assets-by-accept.ts';
+
+const PATHS = [
+ 'assets/photo.png',
+ 'assets/photo.jpg',
+ 'assets/clip.mp4',
+ 'assets/clip.webm',
+ 'assets/song.mp3',
+ 'assets/song.wav',
+ 'docs/handbook.pdf',
+ 'docs/notes.txt',
+ 'assets/icon.svg',
+ 'docs/spec.docx',
+];
+
+describe('filterAssetsByAccept', () => {
+ test('image accept → only raster image extensions (png/jpg/...) — svg excluded', () => {
+ const out = filterAssetsByAccept(PATHS, ALLOWED_IMAGE_MIME_TYPES);
+ expect(out.sort()).toEqual(['assets/photo.jpg', 'assets/photo.png'].sort());
+ });
+
+ test('video accept → only video extensions (mp4/webm)', () => {
+ const out = filterAssetsByAccept(PATHS, ALLOWED_VIDEO_MIME_TYPES);
+ expect(out.sort()).toEqual(['assets/clip.mp4', 'assets/clip.webm'].sort());
+ });
+
+ test('audio accept → only audio extensions (mp3/wav)', () => {
+ const out = filterAssetsByAccept(PATHS, ALLOWED_AUDIO_MIME_TYPES);
+ expect(out.sort()).toEqual(['assets/song.mp3', 'assets/song.wav'].sort());
+ });
+
+ test('pdf accept → only pdf', () => {
+ const out = filterAssetsByAccept(PATHS, ALLOWED_PDF_MIME_TYPES);
+ expect(out).toEqual(['docs/handbook.pdf']);
+ });
+
+ test('wildcard ["*/*"] → every path (File descriptor case — svg admitted as raw file)', () => {
+ const out = filterAssetsByAccept(PATHS, ['*/*']);
+ expect(out.sort()).toEqual([...PATHS].sort());
+ });
+
+ test('mixed accept (image + video) → union of kinds', () => {
+ const out = filterAssetsByAccept(PATHS, [
+ ...ALLOWED_IMAGE_MIME_TYPES,
+ ...ALLOWED_VIDEO_MIME_TYPES,
+ ]);
+ expect(out.sort()).toEqual(
+ ['assets/clip.mp4', 'assets/clip.webm', 'assets/photo.jpg', 'assets/photo.png'].sort(),
+ );
+ });
+
+ test('wildcard mixed into a list → short-circuits to all', () => {
+ const out = filterAssetsByAccept(PATHS, ['image/png', '*/*']);
+ expect(out.sort()).toEqual([...PATHS].sort());
+ });
+
+ test('unknown MIME types → silently drop those entries from the kind set', () => {
+ expect(filterAssetsByAccept(PATHS, ['application/x-custom'])).toEqual([]);
+ });
+
+ test('mixed known + unknown MIME → known kinds still match', () => {
+ expect(filterAssetsByAccept(PATHS, ['image/png', 'application/x-custom']).sort()).toEqual(
+ ['assets/photo.jpg', 'assets/photo.png'].sort(),
+ );
+ });
+
+ test('svg paths excluded from image-accept (raster-only sidebar extensions)', () => {
+ expect(filterAssetsByAccept(['logo.svg', 'banner.png'], ALLOWED_IMAGE_MIME_TYPES)).toEqual([
+ 'banner.png',
+ ]);
+ });
+
+ test('empty accept list → empty result (no kinds wanted)', () => {
+ expect(filterAssetsByAccept(PATHS, [])).toEqual([]);
+ });
+
+ test('preserves input order (no implicit sort)', () => {
+ const ordered = ['z.png', 'a.png', 'm.png'];
+ expect(filterAssetsByAccept(ordered, ALLOWED_IMAGE_MIME_TYPES)).toEqual([
+ 'z.png',
+ 'a.png',
+ 'm.png',
+ ]);
+ });
+
+ test('files with no extension are skipped', () => {
+ expect(filterAssetsByAccept(['README', 'LICENSE'], ALLOWED_IMAGE_MIME_TYPES)).toEqual([]);
+ });
+
+ test('case-insensitive extension matching', () => {
+ expect(filterAssetsByAccept(['assets/PHOTO.PNG'], ALLOWED_IMAGE_MIME_TYPES)).toEqual([
+ 'assets/PHOTO.PNG',
+ ]);
+ });
+});
diff --git a/packages/app/src/editor/utils/filter-assets-by-accept.ts b/packages/app/src/editor/utils/filter-assets-by-accept.ts
new file mode 100644
index 000000000..68fa2363f
--- /dev/null
+++ b/packages/app/src/editor/utils/filter-assets-by-accept.ts
@@ -0,0 +1,60 @@
+import {
+ type InlineAssetMediaKind,
+ mediaKindForSidebarAssetExtension,
+} from '@inkeep/open-knowledge-core';
+
+function mediaKindForMime(mime: string): InlineAssetMediaKind | null {
+ const [type] = mime.split('/');
+ switch (type) {
+ case 'image':
+ return 'image';
+ case 'video':
+ return 'video';
+ case 'audio':
+ return 'audio';
+ case 'application': {
+ if (mime === 'application/pdf') return 'pdf';
+ return null;
+ }
+ case 'text':
+ return 'text';
+ default:
+ return null;
+ }
+}
+
+function kindsForAccept(accept: readonly string[]): Set<InlineAssetMediaKind> | 'all' {
+ if (accept.length === 1 && accept[0] === '*/*') return 'all';
+ const kinds = new Set<InlineAssetMediaKind>();
+ for (const mime of accept) {
+ if (mime === '*/*') return 'all';
+ const kind = mediaKindForMime(mime);
+ if (kind) kinds.add(kind);
+ }
+ return kinds;
+}
+
+function extOf(path: string): string {
+ const lastDot = path.lastIndexOf('.');
+ if (lastDot < 0) return '';
+ const lastSlash = path.lastIndexOf('/');
+ if (lastDot < lastSlash) return ''; // dot is in a folder name, not the basename
+ return path.slice(lastDot + 1).toLowerCase();
+}
+
+export function filterAssetsByAccept(
+ assetPaths: Iterable<string>,
+ accept: readonly string[],
+): string[] {
+ const wanted = kindsForAccept(accept);
+ const out: string[] = [];
+ for (const path of assetPaths) {
+ if (wanted === 'all') {
+ out.push(path);
+ continue;
+ }
+ const kind = mediaKindForSidebarAssetExtension(extOf(path));
+ if (kind && wanted.has(kind)) out.push(path);
+ }
+ return out;
+}