:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(business-knowledge): show the chosen file in the upload drop zone (#130276)
Alex V984d9297febc
diff --git a/frontend/src/lib/lemon-ui/LemonFileInput/LemonFileInput.test.tsx b/frontend/src/lib/lemon-ui/LemonFileInput/LemonFileInput.test.tsxnew file mode 100644index 000000000000..113cc88d9048--- /dev/null+++ b/frontend/src/lib/lemon-ui/LemonFileInput/LemonFileInput.test.tsx@@ -0,0 +1,32 @@+import '@testing-library/jest-dom'++import { cleanup, fireEvent, render, screen } from '@testing-library/react'++import { LemonFileInput } from './LemonFileInput'++describe('LemonFileInput', () => {+ afterEach(() => {+ cleanup()+ })++ it('keeps the drop highlight while a drag moves over child elements and accepts the drop', () => {+ const onChange = jest.fn()+ const file = new File(['refunds'], 'refund-policy.md', { type: 'text/markdown' })+ const dataTransfer = { items: [{ kind: 'file' }], files: [file] }+ render(+ <LemonFileInput accept=".md" multiple={false} onChange={onChange} callToAction={<span>Drop here</span>} />+ )++ const child = screen.getByText('Drop here')+ const dropTarget = child.closest('.FileDropTarget') as HTMLElement++ fireEvent.dragEnter(dropTarget, { dataTransfer })+ fireEvent.dragEnter(child, { dataTransfer })+ fireEvent.dragLeave(dropTarget, { dataTransfer })+ expect(dropTarget).toHaveClass('FileDropTarget--active')++ fireEvent.drop(child, { dataTransfer })+ expect(dropTarget).not.toHaveClass('FileDropTarget--active')+ expect(onChange).toHaveBeenCalledWith([file])+ })+})diff --git a/frontend/src/lib/lemon-ui/LemonFileInput/LemonFileInput.tsx b/frontend/src/lib/lemon-ui/LemonFileInput/LemonFileInput.tsxindex 157af97b3cdd..b3a11bfd5a7b 100644--- a/frontend/src/lib/lemon-ui/LemonFileInput/LemonFileInput.tsx+++ b/frontend/src/lib/lemon-ui/LemonFileInput/LemonFileInput.tsx@@ -1,7 +1,7 @@import './LemonFileInput.scss'import clsx from 'clsx'-import { ChangeEvent, RefObject, createRef, useEffect, useState } from 'react'+import { ChangeEvent, RefObject, useEffect, useRef, useState } from 'react'import { IconUpload } from '@posthog/icons'@@ -52,11 +52,17 @@ export const LemonFileInput = ({const [files, setFiles] = useState(value || ([] as File[]))// dragCounter and drag are used to track whether the user is dragging a file over the textarea- // without drag counter the textarea highlight would flicker when the user drags a file over it- let dragCounter = 0+ // without drag counter the textarea highlight would flicker when the user drags a file over it.+ // Entering a child fires dragenter on it before dragleave on the parent, so the counter must+ // survive re-renders and the listeners must stay bound for the whole drag.+ const dragCounter = useRef(0)const [drag, setDrag] = useState(false)- const dropRef = createRef<HTMLDivElement>()- const fileInputRef = inputRef ?? createRef<HTMLInputElement>()+ const dropRef = useRef<HTMLDivElement>(null)+ const localInputRef = useRef<HTMLInputElement>(null)+ const fileInputRef = inputRef ?? localInputRef++ const latest = useRef({ files, multiple, disabledReason, onChange })+ latest.current = { files, multiple, disabledReason, onChange }useEffect(() => {if (value && value !== files) {@@ -84,64 +90,67 @@ export const LemonFileInput = ({e.target.value = ''}- const handleDrag = (e: DragEvent): void => {- e.preventDefault()- e.stopPropagation()- }-- const handleDragIn = (e: DragEvent): void => {- e.preventDefault()- e.stopPropagation()- if (disabledReason) {+ useEffect(() => {+ const div = (alternativeDropTargetRef || dropRef)?.current+ if (!div) {return}- dragCounter++- if (e.dataTransfer?.items && e.dataTransfer.items.length > 0) {- setDrag(true)- }- }- const handleDragOut = (e: DragEvent): void => {- e.preventDefault()- e.stopPropagation()- dragCounter--- if (dragCounter === 0) {- setDrag(false)+ const handleDrag = (e: DragEvent): void => {+ e.preventDefault()+ e.stopPropagation()}- }- const handleDrop = (e: DragEvent): void => {- e.preventDefault()- e.stopPropagation()- if (disabledReason) {- return+ const handleDragIn = (e: DragEvent): void => {+ e.preventDefault()+ e.stopPropagation()+ if (latest.current.disabledReason) {+ return+ }+ dragCounter.current+++ if (e.dataTransfer?.items && e.dataTransfer.items.length > 0) {+ setDrag(true)+ }}- setDrag(false)- if (e.dataTransfer?.files && e.dataTransfer.files.length > 0) {- const filesArr = Array.prototype.slice.call(e.dataTransfer?.files)- const localFiles = multiple ? [...files, ...filesArr] : [filesArr[0]]- setFiles(localFiles)- onChange?.(localFiles)- dragCounter = 0++ const handleDragOut = (e: DragEvent): void => {+ e.preventDefault()+ e.stopPropagation()+ dragCounter.current = Math.max(0, dragCounter.current - 1)+ if (dragCounter.current === 0) {+ setDrag(false)+ }}- }- useEffect(() => {- const div = (alternativeDropTargetRef || dropRef)?.current- if (!div) {- return+ const handleDrop = (e: DragEvent): void => {+ e.preventDefault()+ e.stopPropagation()+ dragCounter.current = 0+ setDrag(false)+ const { files: currentFiles, multiple: isMultiple, disabledReason: isDisabled } = latest.current+ if (isDisabled) {+ return+ }+ if (e.dataTransfer?.files && e.dataTransfer.files.length > 0) {+ const filesArr = Array.prototype.slice.call(e.dataTransfer.files)+ const localFiles = isMultiple ? [...currentFiles, ...filesArr] : [filesArr[0]]+ setFiles(localFiles)+ latest.current.onChange?.(localFiles)+ }}+div.addEventListener('dragenter', handleDragIn)div.addEventListener('dragleave', handleDragOut)div.addEventListener('dragover', handleDrag)div.addEventListener('drop', handleDrop)return () => {- div?.removeEventListener('dragenter', handleDragIn)- div?.removeEventListener('dragleave', handleDragOut)- div?.removeEventListener('dragover', handleDrag)- div?.removeEventListener('drop', handleDrop)+ div.removeEventListener('dragenter', handleDragIn)+ div.removeEventListener('dragleave', handleDragOut)+ div.removeEventListener('dragover', handleDrag)+ div.removeEventListener('drop', handleDrop)+ dragCounter.current = 0}- }, [value, handleDrop, handleDragOut, alternativeDropTargetRef, dropRef, handleDragIn])+ }, [alternativeDropTargetRef])useEffect(() => {const extraDragTarget = alternativeDropTargetRef?.currentdiff --git a/products/business_knowledge/frontend/components/CreateKnowledgeSourceModal/CreateKnowledgeSourceModal.tsx b/products/business_knowledge/frontend/components/CreateKnowledgeSourceModal/CreateKnowledgeSourceModal.tsxindex f01b8fbe872a..bd81e69b7f12 100644--- a/products/business_knowledge/frontend/components/CreateKnowledgeSourceModal/CreateKnowledgeSourceModal.tsx+++ b/products/business_knowledge/frontend/components/CreateKnowledgeSourceModal/CreateKnowledgeSourceModal.tsx@@ -4,7 +4,6 @@ import { Form } from 'kea-forms'import { LemonButton, LemonInputSelect, LemonModal, LemonSelect } from '@posthog/lemon-ui'import { LemonField } from 'lib/lemon-ui/LemonField'-import { LemonFileInput } from 'lib/lemon-ui/LemonFileInput'import { LemonInput } from 'lib/lemon-ui/LemonInput'import { LemonTabs } from 'lib/lemon-ui/LemonTabs'import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea'@@ -14,6 +13,7 @@ import { CreateTab, businessKnowledgeLogic } from '../../scenes/sources/businessimport { AlwaysIncludeField } from '../AlwaysIncludeField/AlwaysIncludeField'import { CrawlConfigFields } from '../CrawlConfigFields/CrawlConfigFields'import { CrawlModeHelp } from './CrawlModeHelp'+import { FileSourceDropzone } from './FileSourceDropzone'export function CreateKnowledgeSourceModal({refreshIntervalOptions,@@ -36,7 +36,7 @@ export function CreateKnowledgeSourceModal({submitTextSource,submitUrlSource,submitFileSource,- setFileSourceValue,+ setSourceFile,setCreateLibraryIds,} = useActions(businessKnowledgeLogic)@@ -143,27 +143,14 @@ export function CreateKnowledgeSourceModal({content: (<Form logic={businessKnowledgeLogic} formKey="fileSource" className="flex flex-col gap-2"><LemonField name="file" label="File">- <LemonFileInput- accept=".pdf,.docx,.md,.markdown,.txt,.csv"- multiple={false}- callToAction="Drop a file here or click to browse"- showUploadedFiles- onChange={(files) => {- const file = files[0] ?? null- setFileSourceValue('file', file)- if (file) {- const nameWithoutExt = file.name.replace(/\.[^.]+$/, '')- setFileSourceValue('name', nameWithoutExt)- }- }}- />+ <FileSourceDropzone onChange={setSourceFile} /></LemonField><LemonField name="name" label="Name"><LemonInput placeholder="Auto-filled from filename" /></LemonField><p className="text-xs text-muted">PDF, DOCX, Markdown, CSV, or plain text. Max 50 MB. The file is parsed into text and- chunked — the original file is not stored.+ split into sections. The original file is not stored.</p><AlwaysIncludeField /></Form>diff --git a/products/business_knowledge/frontend/components/CreateKnowledgeSourceModal/FileSourceDropzone.stories.tsx b/products/business_knowledge/frontend/components/CreateKnowledgeSourceModal/FileSourceDropzone.stories.tsxnew file mode 100644index 000000000000..632773756fd7--- /dev/null+++ b/products/business_knowledge/frontend/components/CreateKnowledgeSourceModal/FileSourceDropzone.stories.tsx@@ -0,0 +1,31 @@+import type { Meta, StoryObj } from '@storybook/react'++import { FileSourceDropzone } from './FileSourceDropzone'++const meta: Meta<typeof FileSourceDropzone> = {+ title: 'Scenes-App/BusinessKnowledge/FileSourceDropzone',+ component: FileSourceDropzone,+ parameters: { layout: 'padded', viewMode: 'story', testOptions: { snapshotBrowsers: [] } },+ args: {+ onChange: () => undefined,+ },+ decorators: [+ (Story) => (+ <div className="w-120">+ <Story />+ </div>+ ),+ ],+}++export default meta++type Story = StoryObj<typeof FileSourceDropzone>++export const Empty: Story = {+ args: { value: null },+}++export const FileSelected: Story = {+ args: { value: new File(['x'.repeat(248320)], 'refund-policy.pdf', { type: 'application/pdf' }) },+}diff --git a/products/business_knowledge/frontend/components/CreateKnowledgeSourceModal/FileSourceDropzone.tsx b/products/business_knowledge/frontend/components/CreateKnowledgeSourceModal/FileSourceDropzone.tsxnew file mode 100644index 000000000000..424b9f7c6481--- /dev/null+++ b/products/business_knowledge/frontend/components/CreateKnowledgeSourceModal/FileSourceDropzone.tsx@@ -0,0 +1,57 @@+import { IconDocument, IconUpload } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { LemonFileInput } from 'lib/lemon-ui/LemonFileInput'+import { cn } from 'lib/utils/css-classes'++import { formatFileSize } from '../../sourceFormUtils'++export function FileSourceDropzone({+ value,+ onChange,+}: {+ value?: File | null+ onChange: (file: File | null) => void+}): JSX.Element {+ return (+ <LemonFileInput+ accept=".pdf,.docx,.md,.markdown,.txt,.csv"+ multiple={false}+ value={value ? [value] : []}+ onChange={(files) => onChange(files[0] ?? null)}+ showUploadedFiles={false}+ callToAction={+ <div+ className={cn(+ 'flex w-full flex-col items-center gap-2 rounded border border-dashed p-6 text-center',+ value ? 'border-success' : 'border-primary'+ )}+ data-attr="business-knowledge-file-dropzone"+ >+ {value ? (+ <>+ <IconDocument className="text-3xl text-success" />+ <div className="flex min-w-0 max-w-full flex-col items-center">+ <span className="font-semibold break-all">{value.name}</span>+ <span className="text-xs text-secondary" translate="no">+ {formatFileSize(value.size)}+ </span>+ </div>+ <LemonButton type="secondary" size="small">+ Replace file+ </LemonButton>+ </>+ ) : (+ <>+ <IconUpload className="text-3xl text-secondary" />+ <span>Drag a file here</span>+ <LemonButton type="secondary" size="small">+ Choose file+ </LemonButton>+ </>+ )}+ </div>+ }+ />+ )+}diff --git a/products/business_knowledge/frontend/scenes/source/KnowledgeSourceDetails.tsx b/products/business_knowledge/frontend/scenes/source/KnowledgeSourceDetails.tsxindex d63cc52a77eb..89ae62daf1a0 100644--- a/products/business_knowledge/frontend/scenes/source/KnowledgeSourceDetails.tsx+++ b/products/business_knowledge/frontend/scenes/source/KnowledgeSourceDetails.tsx@@ -7,6 +7,7 @@ import { TZLabel } from 'lib/components/TZLabel'import type { KnowledgeLibrary } from '../../api'import { StatusTag } from '../../components/StatusTag/StatusTag'+import { formatFileSize } from '../../sourceFormUtils'import type { KnowledgeSource } from '../sources/businessKnowledgeLogic'import { SourceLibraries } from './SourceLibraries'@@ -27,16 +28,6 @@ function inAppPath(url: string): string {}}-function formatFileSize(bytes: number): string {- if (bytes < 1024) {- return `${bytes} B`- }- if (bytes < 1024 * 1024) {- return `${Math.round(bytes / 1024)} KB`- }- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`-}-function DetailRow({ label, children }: { label: string; children: ReactNode }): JSX.Element {return (<div className="flex items-start justify-between gap-2">diff --git a/products/business_knowledge/frontend/scenes/sources/businessKnowledgeLogic.test.ts b/products/business_knowledge/frontend/scenes/sources/businessKnowledgeLogic.test.tsindex 4fa58c7bbb77..c7326b8b6b27 100644--- a/products/business_knowledge/frontend/scenes/sources/businessKnowledgeLogic.test.ts+++ b/products/business_knowledge/frontend/scenes/sources/businessKnowledgeLogic.test.ts@@ -232,6 +232,21 @@ describe('businessKnowledgeLogic', () => {expect(mockedApi.updateSource).toHaveBeenCalledWith(MOCK_SOURCE.id, { library_ids: [libraryId] })})+ it('fills the file source name from the file only until the user types one', () => {+ const firstFile = new File(['a'], 'refund-policy.pdf')+ const secondFile = new File(['b'], 'shipping.docx')++ logic.actions.setSourceFile(firstFile)+ expect(logic.values.fileSource).toMatchObject({ file: firstFile, name: 'refund-policy' })++ logic.actions.setSourceFile(secondFile)+ expect(logic.values.fileSource).toMatchObject({ file: secondFile, name: 'shipping' })++ logic.actions.setFileSourceValue('name', 'Shipping rules')+ logic.actions.setSourceFile(firstFile)+ expect(logic.values.fileSource).toMatchObject({ file: firstFile, name: 'Shipping rules' })+ })+it('keeps the persisted filters apart per team', () => {logic.actions.setAddedByFilter('human')logic.unmount()diff --git a/products/business_knowledge/frontend/scenes/sources/businessKnowledgeLogic.ts b/products/business_knowledge/frontend/scenes/sources/businessKnowledgeLogic.tsindex 955f8c6e6c99..348d644a5814 100644--- a/products/business_knowledge/frontend/scenes/sources/businessKnowledgeLogic.ts+++ b/products/business_knowledge/frontend/scenes/sources/businessKnowledgeLogic.ts@@ -26,6 +26,7 @@ import type { CreateUrlSourcePayload, KnowledgeLibrary, RefreshIntervalOption }import type { KnowledgeLibraryApi, KnowledgeSourceApi } from '../../generated/api.schemas'import {DEFAULT_URL_SOURCE_FORM,+ fileNameWithoutExtension,type CrawlMode,type KnowledgeSource,type TextSourceFormValues,@@ -288,6 +289,9 @@ export interface businessKnowledgeLogicActions {setSearchTerm: (searchTerm: string) => {searchTerm: string}+ setSourceFile: (file: File | null) => {+ file: File | null+ }setSourceTypeFilter: (sourceTypeFilter: SourceTypeFilter) => {sourceTypeFilter: SourceTypeFilter}@@ -404,6 +408,7 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([setAddedByFilter: (addedByFilter: AddedByFilter) => ({ addedByFilter }),setLibraryScope: (libraryScope: string) => ({ libraryScope }),setCreateLibraryIds: (libraryIds: string[]) => ({ libraryIds }),+ setSourceFile: (file: File | null) => ({ file }),openLibraryDialog: (libraryDialog: LibraryDialog) => ({ libraryDialog }),closeLibraryDialog: true,createLibrary: (name: string) => ({ name }),@@ -637,6 +642,14 @@ export const businessKnowledgeLogic = kea<businessKnowledgeLogicType>([openCreateModal: () => {actions.setCreateLibraryIds(isLibraryScope(values.libraryScope) ? [values.libraryScope] : [])},+ setSourceFile: ({ file }) => {+ const { name, file: previousFile } = values.fileSource+ const nameIsDerived = !name.trim() || (!!previousFile && name === fileNameWithoutExtension(previousFile))+ actions.setFileSourceValue('file', file)+ if (file && nameIsDerived) {+ actions.setFileSourceValue('name', fileNameWithoutExtension(file))+ }+ },submitTextSourceSuccess: () => {posthog.capture('business knowledge source created', { source_type: 'text' })actions.loadLibraries()diff --git a/products/business_knowledge/frontend/sourceFormUtils.ts b/products/business_knowledge/frontend/sourceFormUtils.tsindex 23f7fba469b6..d6686f33dbf5 100644--- a/products/business_knowledge/frontend/sourceFormUtils.ts+++ b/products/business_knowledge/frontend/sourceFormUtils.ts@@ -85,6 +85,20 @@ export function validateUrl({ name, url, max_pages }: UrlSourceFormValues): {}}+export function fileNameWithoutExtension(file: File): string {+ return file.name.replace(/\.[^.]+$/, '')+}++export function formatFileSize(bytes: number): string {+ if (bytes < 1024) {+ return `${bytes} B`+ }+ if (bytes < 1024 * 1024) {+ return `${Math.round(bytes / 1024)} KB`+ }+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`+}+export function splitGlobs(raw: string): string[] {return raw.split(/[\n,]/)