Skip to content

TagSpaces is an offline, open source, document manager with tagging support

feat: added file picker for creating relative and ts links, corrected the navigation with relative links

Ilian Sapundshieve2335ea62dc5
diff --git a/src/renderer/components/EditDescription.tsx b/src/renderer/components/EditDescription.tsx
index 14e9ece2c..b06e2f4d4 100644
--- a/src/renderer/components/EditDescription.tsx
+++ b/src/renderer/components/EditDescription.tsx
@@ -27,7 +27,7 @@ import { useEffect, useRef } from 'react';
function EditDescription() {
const theme = useTheme();
- const { setEditDescriptionMode } = useFilePropertiesContext();
+ const { setEditDescriptionMode, setDescription } = useFilePropertiesContext();
const milkdownDivRef = useRef<HTMLDivElement>(null);
const fileDescriptionRef = useRef<CrepeRef>(null);
@@ -49,6 +49,27 @@ function EditDescription() {
fileDescriptionRef.current.setEditMode(editMode);
};
+ const insertMarkdown = (markdown: string) => {
+ const ref = fileDescriptionRef.current;
+ if (!ref) return;
+ ref.insert(markdown);
+ // The Crepe `markdownUpdated` listener in DescriptionMdEditor.tsx is
+ // gated on `view.hasFocus()` to avoid firing on programmatic updates,
+ // which means our insert here would otherwise be silently skipped and
+ // the description wouldn't be marked dirty. Push the new markdown into
+ // the parent state explicitly so save picks it up.
+ const next = ref.getMarkdown();
+ if (typeof next === 'string') {
+ setDescription(next);
+ }
+ // Return DOM focus so the caret blinks at the new position and the user
+ // can continue typing.
+ ref.focus();
+ };
+
+ const getSelectedText = () =>
+ fileDescriptionRef.current?.getSelectedText() ?? '';
+
return (
<Box
sx={{
@@ -58,6 +79,8 @@ function EditDescription() {
<EditDescriptionButtons
resetMdContent={resetMdContent}
setEditMode={setEditMode}
+ insertMarkdown={insertMarkdown}
+ getSelectedText={getSelectedText}
/>
<Box
ref={milkdownDivRef}
diff --git a/src/renderer/components/EditDescriptionButtons.tsx b/src/renderer/components/EditDescriptionButtons.tsx
index c8e3f5a27..2ce3c1388 100644
--- a/src/renderer/components/EditDescriptionButtons.tsx
+++ b/src/renderer/components/EditDescriptionButtons.tsx
@@ -17,13 +17,14 @@
*/
import AppConfig from '-/AppConfig';
-import { MoreMenuIcon } from '-/components/CommonIcons';
+import { LinkIcon, MoreMenuIcon } from '-/components/CommonIcons';
import { ProTooltip } from '-/components/HelperComponents';
import TsTooltip from '-/components/TsTooltip';
import TsButton from '-/components/TsButton';
import TsIconButton from '-/components/TsIconButton';
import AiGenDescButton from '-/components/chat/AiGenDescButton';
import AiGenTagsButton from '-/components/chat/AiGenTagsButton';
+import { useFilePickerDialogContext } from '-/components/dialogs/hooks/useFilePickerDialogContext';
import DescriptionMenu from '-/components/md/DescriptionMenu';
import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';
import { useFilePropertiesContext } from '-/hooks/useFilePropertiesContext';
@@ -35,18 +36,25 @@ import {
} from '-/services/utils-io';
import { ButtonGroup, useTheme } from '@mui/material';
import { formatDateTime4Tag } from '@tagspaces/tagspaces-common/misc';
-import { extractTitle } from '@tagspaces/tagspaces-common/paths';
+import {
+ extractContainingDirectoryPath,
+ extractTitle,
+} from '@tagspaces/tagspaces-common/paths';
import React from 'react';
import { useTranslation } from 'react-i18next';
interface ButtonsProps {
resetMdContent: (md: string) => void;
setEditMode: (editMode: boolean) => void;
+ insertMarkdown?: (markdown: string) => void;
+ getSelectedText?: () => string;
}
const EditDescriptionButtons: React.FC<ButtonsProps> = ({
resetMdContent,
setEditMode,
+ insertMarkdown,
+ getSelectedText,
}) => {
const { t } = useTranslation();
const {
@@ -58,8 +66,65 @@ const EditDescriptionButtons: React.FC<ButtonsProps> = ({
} = useFilePropertiesContext();
const { findLocation } = useCurrentLocationContext();
const { openedEntry, reloadOpenedFile } = useOpenedEntryContext();
+ const { openFilePickerDialog } = useFilePickerDialogContext();
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
const theme = useTheme();
+
+ function buildSafeMarkdownLink(label: string, url: string): string {
+ // CommonMark link labels can't contain unescaped `[` or `]` (and `\`
+ // must be escaped). TagSpaces filenames frequently embed `[tags]`, which
+ // would break naive `[${name}](...)` interpolation.
+ const escapedLabel = label
+ .replace(/\\/g, '\\\\')
+ .replace(/\[/g, '\\[')
+ .replace(/\]/g, '\\]');
+ // For the URL, URL-encode special chars so the markdown stays pure-ASCII
+ // through every save/reparse cycle (angle-bracket form `<url>` is lost
+ // by some markdown serializers). encodeURI preserves path separators,
+ // but does NOT encode `[ ] ( )` — encode those manually.
+ // Skip encoding for ts:// links: they already contain encoded params.
+ const isTsLink = /^ts:\/\//.test(url);
+ const safeUrl = isTsLink
+ ? url
+ : encodeURI(url)
+ .replace(/\[/g, '%5B')
+ .replace(/\]/g, '%5D')
+ .replace(/\(/g, '%28')
+ .replace(/\)/g, '%29');
+ return `[${escapedLabel}](${safeUrl})`;
+ }
+
+ function handleInsertFileLink() {
+ if (!insertMarkdown) return;
+ // Capture the editor's current selection text BEFORE the dialog opens.
+ // Once MUI's focus-trap moves focus into the dialog, reading the selection
+ // is still safe (ProseMirror state survives focus loss), but we read it
+ // here for clarity. Empty string = no selection.
+ const initialLabel = getSelectedText ? getSelectedText() : '';
+ // For a file's description the relative-link base is the file's
+ // containing folder; for a folder's description it's the folder itself
+ // (the description "lives in" the folder).
+ const sourceDir = openedEntry?.path
+ ? openedEntry.isFile
+ ? extractContainingDirectoryPath(
+ openedEntry.path,
+ findLocation(openedEntry.locationID)?.getDirSeparator?.() || '/',
+ )
+ : openedEntry.path
+ : undefined;
+ openFilePickerDialog({
+ mode: 'any',
+ sourceLocationId: openedEntry?.locationID,
+ sourceDir,
+ initialLocationId: openedEntry?.locationID,
+ showLabelField: true,
+ initialLabel,
+ onSelect: (entry, link, _linkType, label) => {
+ const finalLabel = (label && label.trim()) || entry.name || link;
+ insertMarkdown(buildSafeMarkdownLink(finalLabel, link));
+ },
+ });
+ }
//const [isDescriptionChanged, descriptionChanged] = useState<boolean>(false);
/*React.useImperativeHandle(buttonsRef, () => ({
@@ -232,6 +297,17 @@ const EditDescriptionButtons: React.FC<ButtonsProps> = ({
</ProTooltip>
</>
)}
+ {isEditDescriptionMode && insertMarkdown && (
+ <TsIconButton
+ tooltip={t('core:insertFileOrFolderLink')}
+ onClick={handleInsertFileLink}
+ sx={{ marginLeft: AppConfig.defaultSpaceBetweenButtons }}
+ data-tid="insertFileOrFolderLinkTID"
+ aria-label={t('core:insertFileOrFolderLink')}
+ >
+ <LinkIcon />
+ </TsIconButton>
+ )}
<TsIconButton
tooltip={t('core:moreActions')}
onClick={handleMoreClick}
diff --git a/src/renderer/components/FolderBrowser/FolderList.tsx b/src/renderer/components/FolderBrowser/FolderList.tsx
index 45292ec4a..fa9558b56 100644
--- a/src/renderer/components/FolderBrowser/FolderList.tsx
+++ b/src/renderer/components/FolderBrowser/FolderList.tsx
@@ -17,8 +17,14 @@
*/
import AppConfig from '-/AppConfig';
-import { FileIcon, FolderIcon } from '-/components/CommonIcons';
+import { FolderIcon } from '-/components/CommonIcons';
+import FileExtBadge from '-/components/FileExtBadge';
import TsTooltip from '-/components/TsTooltip';
+import {
+ getDefaultFolderColor,
+ getSupportedFileTypes,
+} from '-/reducers/settings';
+import { findColorForEntry } from '-/services/utils-io';
import { TS } from '-/tagspaces.namespace';
import { CommonLocation } from '-/utils/CommonLocation';
import ChevronRightIcon from '@mui/icons-material/ChevronRight';
@@ -29,8 +35,54 @@ import ListItemIcon from '@mui/material/ListItemIcon';
import ListItemText from '@mui/material/ListItemText';
import Skeleton from '@mui/material/Skeleton';
import Typography from '@mui/material/Typography';
+import { extractFileExtension } from '@tagspaces/tagspaces-common/paths';
import { useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { useSelector } from 'react-redux';
+
+const TILE_SX = {
+ minWidth: 36,
+ height: 22,
+ fontSize: 10,
+ lineHeight: 1,
+ padding: '0 4px',
+} as const;
+
+function getDisplayExtension(entry: TS.FileSystemEntry): string {
+ if (entry.extension) return entry.extension;
+ const source = entry.name || entry.path || '';
+ return source ? extractFileExtension(source) : '';
+}
+
+function ExtensionTile({
+ entry,
+ supportedFileTypes,
+ defaultFolderColor,
+}: {
+ entry: TS.FileSystemEntry;
+ supportedFileTypes: Array<any>;
+ defaultFolderColor: string;
+}) {
+ const ext = getDisplayExtension(entry);
+ const normalizedEntry: TS.FileSystemEntry =
+ entry.isFile && !entry.extension && ext
+ ? { ...entry, extension: ext }
+ : entry;
+ const color = findColorForEntry(
+ normalizedEntry,
+ supportedFileTypes,
+ defaultFolderColor,
+ );
+ return (
+ <FileExtBadge noWrap sx={{ ...TILE_SX, backgroundColor: color }}>
+ {entry.isFile ? (
+ ext || '·'
+ ) : (
+ <FolderIcon style={{ fontSize: 14, color: 'white' }} />
+ )}
+ </FileExtBadge>
+ );
+}
export type FolderListFilter = 'folders' | 'files' | 'all';
@@ -64,6 +116,8 @@ function FolderList({
height = 240,
}: Props) {
const { t } = useTranslation();
+ const supportedFileTypes = useSelector(getSupportedFileTypes);
+ const defaultFolderColor = useSelector(getDefaultFolderColor);
const [entries, setEntries] = useState<TS.FileSystemEntry[]>([]);
const [loading, setLoading] = useState(true);
const listRef = useRef<HTMLUListElement | null>(null);
@@ -137,12 +191,18 @@ function FolderList({
const visible = useMemo(() => {
const q = (query || '').trim().toLowerCase();
- return entries.filter((e) => {
+ const filtered = entries.filter((e) => {
if (filter === 'folders' && e.isFile) return false;
if (filter === 'files' && !e.isFile) return false;
if (q && !e.name.toLowerCase().includes(q)) return false;
return true;
});
+ // Show folders first, then files. Within each group keep the order from
+ // listDirectoryPromise (typically the location's natural sort).
+ return [...filtered].sort((a, b) => {
+ if (a.isFile === b.isFile) return 0;
+ return a.isFile ? 1 : -1;
+ });
}, [entries, filter, query]);
function handleClick(entry: TS.FileSystemEntry) {
@@ -217,8 +277,12 @@ function FolderList({
onDoubleClick={() => !entry.isFile && onDescend?.(entry.path)}
sx={{ gap: 1 }}
>
- <ListItemIcon sx={{ minWidth: 32 }}>
- {entry.isFile ? <FileIcon /> : <FolderIcon />}
+ <ListItemIcon sx={{ minWidth: 44 }}>
+ <ExtensionTile
+ entry={entry}
+ supportedFileTypes={supportedFileTypes}
+ defaultFolderColor={defaultFolderColor}
+ />
</ListItemIcon>
<ListItemText
primary={
diff --git a/src/renderer/components/dialogs/FilePickerDialog.tsx b/src/renderer/components/dialogs/FilePickerDialog.tsx
new file mode 100644
index 000000000..ae3b6228d
--- /dev/null
+++ b/src/renderer/components/dialogs/FilePickerDialog.tsx
@@ -0,0 +1,442 @@
+/**
+ * TagSpaces - universal file and folder organizer
+ * Copyright (C) 2024-present TagSpaces GmbH
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License (version 3) as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ */
+
+import AppConfig from '-/AppConfig';
+import { CheckIcon } from '-/components/CommonIcons';
+import DraggablePaper from '-/components/DraggablePaper';
+import { FolderBrowser } from '-/components/FolderBrowser';
+import TsButton from '-/components/TsButton';
+import TsToggleButton from '-/components/TsToggleButton';
+import SelectedItemsSummary from '-/components/dialogs/components/SelectedItemsSummary';
+import TsDialogActions from '-/components/dialogs/components/TsDialogActions';
+import TsDialogTitle from '-/components/dialogs/components/TsDialogTitle';
+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';
+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';
+import {
+ actions as SettingsActions,
+ getLastLinkType,
+} from '-/reducers/settings';
+import {
+ buildRelativeLinkForEntry,
+ buildSharingLinkForEntry,
+} from '-/services/utils-io';
+import { TS } from '-/tagspaces.namespace';
+import Box from '@mui/material/Box';
+import Dialog from '@mui/material/Dialog';
+import DialogContent from '@mui/material/DialogContent';
+import TsTextField from '-/components/TsTextField';
+import Paper from '@mui/material/Paper';
+import Stack from '@mui/material/Stack';
+import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
+import Typography from '@mui/material/Typography';
+import { useTheme } from '@mui/material/styles';
+import useMediaQuery from '@mui/material/useMediaQuery';
+import { extractDirectoryName } from '@tagspaces/tagspaces-common/paths';
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useDispatch, useSelector } from 'react-redux';
+
+export type FilePickerMode = 'file' | 'folder' | 'any';
+export type FilePickerLinkType = 'ts' | 'relative';
+
+export interface FilePickerDialogProps {
+ open: boolean;
+ onClose: () => void;
+ mode?: FilePickerMode;
+ initialLocationId?: string;
+ initialPath?: string;
+ /** Source context for relative-link computation. When provided AND the
+ * picked entry is in the same location, the dialog shows a link-format
+ * toggle. Without these, output is always ts://.
+ *
+ * `sourceDir` is the directory the relative path will be resolved against.
+ * For a file's description: pass the file's containing directory.
+ * For a folder's description: pass the folder itself. */
+ sourceLocationId?: string;
+ sourceDir?: string;
+ title?: string;
+ confirmLabel?: string;
+ /** When true, render an editable "Link text" field. Default value is
+ * `initialLabel` (if set) otherwise the picked entry's name. The user can
+ * edit before confirming; the final value is returned in onSelect. */
+ showLabelField?: boolean;
+ initialLabel?: string;
+ onSelect: (
+ entry: TS.FileSystemEntry,
+ link: string,
+ linkType: FilePickerLinkType,
+ label: string,
+ ) => void;
+}
+
+function modeAccepts(entry: TS.FileSystemEntry, mode: FilePickerMode): boolean {
+ if (mode === 'any') return true;
+ if (mode === 'file') return entry.isFile === true;
+ return entry.isFile === false;
+}
+
+function FilePickerDialog(props: FilePickerDialogProps) {
+ const { t } = useTranslation();
+ const {
+ open,
+ onClose,
+ mode = 'file',
+ initialLocationId,
+ initialPath,
+ sourceLocationId,
+ sourceDir,
+ title,
+ confirmLabel,
+ showLabelField,
+ initialLabel,
+ onSelect,
+ } = props;
+
+ const { locations, findLocation } = useCurrentLocationContext();
+ const { currentDirectoryPath } = useDirectoryContentContext();
+ const dispatch = useDispatch();
+ const lastLinkType = useSelector(getLastLinkType);
+ const theme = useTheme();
+ const smallScreen = useMediaQuery(theme.breakpoints.down('md'));
+
+ const defaultLocation = findLocation();
+ const [activeTargetLocationId, setActiveTargetLocationId] = useState<
+ string | undefined
+ >(initialLocationId || defaultLocation?.uuid);
+ const targetLocation = findLocation(activeTargetLocationId);
+ const [path, setPath] = useState<string>(
+ initialPath || currentDirectoryPath || targetLocation?.path || '',
+ );
+ const [selectedEntry, setSelectedEntry] = useState<
+ TS.FileSystemEntry | undefined
+ >(undefined);
+ const [linkType, setLinkTypeState] =
+ useState<FilePickerLinkType>(lastLinkType);
+ // Wrap setLinkType to also persist the user's choice in settings so it
+ // becomes the default the next time the dialog opens. Mirrors the
+ // `lastMoveCopyMode` pattern in MoveCopyFilesDialog.
+ const setLinkType = (next: FilePickerLinkType) => {
+ setLinkTypeState(next);
+ dispatch(SettingsActions.setLastLinkType(next));
+ };
+ // Editable "Link text" field. If `initialLabel` is provided (e.g. text was
+ // selected in a markdown editor before opening), use it as the default;
+ // otherwise empty until the user picks an entry (then auto-fills from name).
+ const [linkLabel, setLinkLabel] = useState<string>(initialLabel || '');
+ // Tracks whether the user has typed in the label field. If so we stop
+ // auto-overwriting it from the picked entry's name.
+ const userEditedLabelRef = useRef<boolean>(!!initialLabel);
+ // Tracks the previous entry's name so we can auto-update the label when
+ // the user switches to a different entry — but only as long as the label
+ // still matches the previous entry's name (i.e. they haven't customized).
+ const prevEntryNameRef = useRef<string>('');
+
+ // Reset all transient state on each fresh open of the dialog so reuse from a
+ // keepMounted context provider doesn't show stale selection between opens.
+ useEffect(() => {
+ if (open) {
+ setActiveTargetLocationId(initialLocationId || defaultLocation?.uuid);
+ setPath(
+ initialPath || currentDirectoryPath || defaultLocation?.path || '',
+ );
+ setSelectedEntry(undefined);
+ // Reset link-format to the persisted preference on each open.
+ setLinkTypeState(lastLinkType);
+ setLinkLabel(initialLabel || '');
+ userEditedLabelRef.current = !!initialLabel;
+ prevEntryNameRef.current = '';
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [open]);
+
+ // Auto-fill the label from the picked entry's name unless the user has
+ // customized it (or unless an initialLabel was supplied by the caller).
+ useEffect(() => {
+ if (!selectedEntry) return;
+ const entryName = selectedEntry.name || '';
+ const customized =
+ userEditedLabelRef.current &&
+ linkLabel !== prevEntryNameRef.current &&
+ linkLabel !== '';
+ if (!customized) {
+ setLinkLabel(entryName);
+ userEditedLabelRef.current = false;
+ }
+ prevEntryNameRef.current = entryName;
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [selectedEntry]);
+
+ function handleLabelChange(e: React.ChangeEvent<HTMLInputElement>) {
+ setLinkLabel(e.target.value);
+ userEditedLabelRef.current = true;
+ }
+
+ function handlePickLocation(loc: any) {
+ setActiveTargetLocationId(loc.uuid);
+ setPath(loc.path || '');
+ setSelectedEntry(undefined);
+ }
+
+ function handlePathChange(next: string) {
+ setPath(next);
+ // Changing folder invalidates a previous file selection.
+ if (selectedEntry?.isFile) {
+ setSelectedEntry(undefined);
+ }
+ }
+
+ function handleFileSelect(entry: TS.FileSystemEntry) {
+ setSelectedEntry(entry);
+ }
+
+ function handleSelectCurrentFolder() {
+ if (!targetLocation) return;
+ const sep = targetLocation.getDirSeparator?.() || '/';
+ const folderName =
+ extractDirectoryName(path || '', sep) || targetLocation.name;
+ const folderEntry: TS.FileSystemEntry = {
+ uuid: targetLocation.uuid + ':' + path,
+ name: folderName,
+ isFile: false,
+ path: path || targetLocation.path || '',
+ extension: '',
+ tags: [],
+ size: 0,
+ lmdt: 0,
+ locationID: targetLocation.uuid,
+ } as TS.FileSystemEntry;
+ setSelectedEntry(folderEntry);
+ }
+
+ // Relative-link availability — recomputed whenever the selection or source
+ // context changes. The picked entry comes from listDirectoryPromise on the
+ // currently-browsed `targetLocation` (and is cleared on location switch),
+ // so by construction it lives in `targetLocation`. Many IO backends don't
+ // populate `entry.locationID` on listing results, so we don't rely on it.
+ const canUseRelative = useMemo(() => {
+ if (!selectedEntry || !sourceLocationId || !sourceDir || !targetLocation) {
+ return false;
+ }
+ if (targetLocation.uuid !== sourceLocationId) {
+ return false;
+ }
+ const rel = buildRelativeLinkForEntry(
+ selectedEntry,
+ targetLocation,
+ sourceDir,
+ );
+ return rel !== null;
+ }, [selectedEntry, sourceLocationId, sourceDir, targetLocation]);
+
+ const dialogTitleText =
+ title ||
+ (mode === 'folder'
+ ? t('core:chooseFolder')
+ : mode === 'any'
+ ? t('core:chooseEntry')
+ : t('core:chooseFile'));
+
+ const emptyStateCaption =
+ mode === 'folder'
+ ? t('core:selectAFolder')
+ : mode === 'any'
+ ? t('core:selectAnEntry')
+ : t('core:selectAFile');
+
+ const primaryDisabled =
+ !selectedEntry || !modeAccepts(selectedEntry, mode) || !targetLocation;
+
+ function handleConfirm() {
+ if (!selectedEntry || !targetLocation) return;
+ let link: string;
+ if (linkType === 'relative' && canUseRelative && sourceDir) {
+ const rel = buildRelativeLinkForEntry(
+ selectedEntry,
+ targetLocation,
+ sourceDir,
+ );
+ link = rel ?? buildSharingLinkForEntry(selectedEntry, targetLocation);
+ } else {
+ link = buildSharingLinkForEntry(selectedEntry, targetLocation);
+ }
+ const finalLabel =
+ (linkLabel && linkLabel.trim()) || selectedEntry.name || '';
+ onSelect(selectedEntry, link, canUseRelative ? linkType : 'ts', finalLabel);
+ onClose();
+ }
+
+ return (
+ <Dialog
+ open={open}
+ onClose={onClose}
+ keepMounted
+ scroll="paper"
+ aria-labelledby="fpd-title"
+ PaperComponent={smallScreen ? Paper : DraggablePaper}
+ fullScreen={smallScreen}
+ fullWidth
+ maxWidth="sm"
+ >
+ <TsDialogTitle
+ dialogTitle={
+ <Typography
+ component="div"
+ variant="h6"
+ id="fpd-title"
+ sx={{ fontSize: '1.05rem', fontWeight: 600 }}
+ >
+ {dialogTitleText}
+ </Typography>
+ }
+ closeButtonTestId="closeFilePickerTID"
+ onClose={onClose}
+ />
+ <DialogContent sx={{ overflowX: 'hidden', overflowY: 'auto' }}>
+ {targetLocation && (
+ <FolderBrowser
+ locations={locations}
+ activeLocationId={targetLocation.uuid}
+ onActiveLocationChange={handlePickLocation}
+ path={path || targetLocation.path || ''}
+ onPathChange={handlePathChange}
+ filter={mode === 'folder' ? 'folders' : 'all'}
+ onFileSelect={handleFileSelect}
+ listHeight={smallScreen ? '50vh' : 240}
+ />
+ )}
+
+ {/* Folder-mode / any-mode: explicit "Select this folder" affordance */}
+ {mode !== 'file' && targetLocation && (
+ <Box sx={{ marginTop: 1 }}>
+ <TsButton
+ data-tid="filePickerSelectCurrentFolder"
+ onClick={handleSelectCurrentFolder}
+ >
+ {t('core:selectThisFolder')}
+ </TsButton>
+ </Box>
+ )}
+
+ <Box sx={{ marginTop: 1.5 }}>
+ {selectedEntry ? (
+ <SelectedItemsSummary entries={[selectedEntry]} />
+ ) : (
+ <Typography
+ variant="body2"
+ color="text.secondary"
+ sx={{ padding: '8px 12px' }}
+ >
+ {emptyStateCaption}
+ </Typography>
+ )}
+ </Box>
+
+ {showLabelField && (
+ <Box sx={{ marginTop: 1.5 }}>
+ <TsTextField
+ label={t('core:linkText')}
+ value={linkLabel}
+ onChange={handleLabelChange}
+ updateValue={(v: string) => {
+ setLinkLabel(v);
+ userEditedLabelRef.current = true;
+ }}
+ retrieveValue={() => linkLabel}
+ placeholder={selectedEntry?.name || ''}
+ slotProps={{
+ htmlInput: { 'data-tid': 'fpdLinkLabelField' },
+ }}
+ />
+ </Box>
+ )}
+ </DialogContent>
+ <TsDialogActions
+ sx={{
+ justifyContent: 'space-between',
+ flexWrap: 'wrap',
+ rowGap: 1,
+ }}
+ >
+ {/* Link-format toggle — visible whenever the caller supplied source
+ context (so the option is discoverable). The "Relative link"
+ option is disabled until the user selects an entry that lives in
+ the same location as the source. */}
+ {sourceLocationId && sourceDir ? (
+ <ToggleButtonGroup
+ value={linkType}
+ exclusive
+ onChange={(_, next) => {
+ if (next) setLinkType(next);
+ }}
+ aria-label={t('core:link')}
+ sx={{
+ borderRadius: AppConfig.defaultCSSRadius,
+ '& .MuiToggleButton-root': {
+ padding: '3px 11px',
+ '&:first-of-type': {
+ borderTopLeftRadius: AppConfig.defaultCSSRadius,
+ borderBottomLeftRadius: AppConfig.defaultCSSRadius,
+ },
+ '&:last-of-type': {
+ borderTopRightRadius: AppConfig.defaultCSSRadius,
+ borderBottomRightRadius: AppConfig.defaultCSSRadius,
+ },
+ },
+ }}
+ >
+ <TsToggleButton
+ value="relative"
+ data-tid="fpdLinkTypeRelative"
+ sx={{ gap: linkType === 'relative' ? 0.5 : 0 }}
+ >
+ {linkType === 'relative' && (
+ <CheckIcon sx={{ fontSize: '1rem' }} />
+ )}
+ {t('core:relativeLink')}
+ </TsToggleButton>
+ <TsToggleButton
+ value="ts"
+ data-tid="fpdLinkTypeTs"
+ sx={{ gap: linkType === 'ts' ? 0.5 : 0 }}
+ >
+ {linkType === 'ts' && <CheckIcon sx={{ fontSize: '1rem' }} />}
+ {t('core:sharingLink')}
+ </TsToggleButton>
+ </ToggleButtonGroup>
+ ) : (
+ <Box />
+ )}
+ <Stack direction="row" spacing={1}>
+ <TsButton data-tid="closeFilePickerDialog" onClick={onClose}>
+ {t('core:cancel')}
+ </TsButton>
+ <TsButton
+ data-tid="confirmFilePicker"
+ disabled={primaryDisabled}
+ onClick={handleConfirm}
+ variant="contained"
+ >
+ {confirmLabel || t('core:select')}
+ </TsButton>
+ </Stack>
+ </TsDialogActions>
+ </Dialog>
+ );
+}
+
+export default FilePickerDialog;
diff --git a/src/renderer/components/dialogs/components/SelectedItemsSummary.tsx b/src/renderer/components/dialogs/components/SelectedItemsSummary.tsx
index 65858d2b4..43be94652 100644
--- a/src/renderer/components/dialogs/components/SelectedItemsSummary.tsx
+++ b/src/renderer/components/dialogs/components/SelectedItemsSummary.tsx
@@ -25,6 +25,7 @@ import {
} from '-/reducers/settings';
import { findColorForEntry } from '-/services/utils-io';
import { TS } from '-/tagspaces.namespace';
+import { extractFileExtension } from '@tagspaces/tagspaces-common/paths';
import ExpandLess from '@mui/icons-material/ExpandLess';
import ExpandMore from '@mui/icons-material/ExpandMore';
import Box from '@mui/material/Box';
@@ -74,6 +75,15 @@ const TILE_SX = {
padding: '0 4px',
} as const;
+function getDisplayExtension(entry: TS.FileSystemEntry): string {
+ if (entry.extension) return entry.extension;
+ // Some IO backends don't populate `extension`; derive from the filename
+ // (or path as a final fallback) so the tile + color computation work.
+ const source = entry.name || entry.path || '';
+ if (!source) return '';
+ return extractFileExtension(source);
+}
+
function ExtensionTile({
entry,
supportedFileTypes,
@@ -83,8 +93,15 @@ function ExtensionTile({
supportedFileTypes: Array<any>;
defaultFolderColor: string;
}) {
+ const ext = getDisplayExtension(entry);
+ // Normalize the entry so findColorForEntry / the badge label see the same
+ // derived extension when the IO layer didn't supply one.
+ const normalizedEntry: TS.FileSystemEntry =
+ entry.isFile && !entry.extension && ext
+ ? { ...entry, extension: ext }
+ : entry;
const color = findColorForEntry(
- entry,
+ normalizedEntry,
supportedFileTypes,
defaultFolderColor,
);
@@ -97,7 +114,7 @@ function ExtensionTile({
}}
>
{entry.isFile ? (
- entry.extension || '·'
+ ext || '·'
) : (
<FolderIcon style={{ fontSize: 14, color: 'white' }} />
)}
diff --git a/src/renderer/components/dialogs/hooks/FilePickerDialogContextProvider.tsx b/src/renderer/components/dialogs/hooks/FilePickerDialogContextProvider.tsx
new file mode 100644
index 000000000..a0149945d
--- /dev/null
+++ b/src/renderer/components/dialogs/hooks/FilePickerDialogContextProvider.tsx
@@ -0,0 +1,161 @@
+/**
+ * TagSpaces - universal file and folder organizer
+ * Copyright (C) 2024-present TagSpaces GmbH
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License (version 3) as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ */
+
+/**
+ * Extension postMessage protocol for requesting a file picker (spec only —
+ * the host-side router that translates these messages into
+ * `openFilePickerDialog` calls is a follow-up).
+ *
+ * Request (extension → host):
+ * {
+ * command: 'requestFilePicker',
+ * eventID: string,
+ * options?: {
+ * mode?: 'file' | 'folder' | 'any',
+ * allowedExtensions?: string[],
+ * title?: string,
+ * sourceLocationId?: string,
+ * sourceDir?: string,
+ * },
+ * }
+ *
+ * Response (host → extension iframe via `iframe.contentWindow.postMessage`):
+ * {
+ * eventID: string,
+ * cancelled?: true, // mutually exclusive with the rest
+ * link?: 'ts://...' | '../foo.md',
+ * linkType?: 'ts' | 'relative',
+ * name?: string,
+ * path?: string, // absolute path inside the location
+ * locationId?: string,
+ * isFile?: boolean,
+ * extension?: string,
+ * }
+ */
+
+import LoadingLazy from '-/components/LoadingLazy';
+import { TS } from '-/tagspaces.namespace';
+import React, { createContext, useMemo, useReducer, useRef } from 'react';
+import type { FilePickerLinkType, FilePickerMode } from '../FilePickerDialog';
+
+export interface FilePickerDialogOpenOptions {
+ mode?: FilePickerMode;
+ initialLocationId?: string;
+ initialPath?: string;
+ sourceLocationId?: string;
+ sourceDir?: string;
+ title?: string;
+ confirmLabel?: string;
+ /** Render an editable "Link text" field. Defaults to `initialLabel` if
+ * provided, otherwise the picked entry's name. The final value is returned
+ * in onSelect's 4th arg. */
+ showLabelField?: boolean;
+ initialLabel?: string;
+ onSelect: (
+ entry: TS.FileSystemEntry,
+ link: string,
+ linkType: FilePickerLinkType,
+ label: string,
+ ) => void;
+}
+
+type FilePickerDialogContextData = {
+ openFilePickerDialog: (options: FilePickerDialogOpenOptions) => void;
+ closeFilePickerDialog: () => void;
+};
+
+export const FilePickerDialogContext =
+ createContext<FilePickerDialogContextData>({
+ openFilePickerDialog: () => undefined,
+ closeFilePickerDialog: () => undefined,
+ });
+
+export type FilePickerDialogContextProviderProps = {
+ children: React.ReactNode;
+};
+
+const FilePickerDialog = React.lazy(
+ () =>
+ import(/* webpackChunkName: "FilePickerDialog" */ '../FilePickerDialog'),
+);
+
+export const FilePickerDialogContextProvider = ({
+ children,
+}: FilePickerDialogContextProviderProps) => {
+ const open = useRef<boolean>(false);
+ const options = useRef<FilePickerDialogOpenOptions | undefined>(undefined);
+
+ const [, forceUpdate] = useReducer((x) => x + 1, 0, undefined);
+
+ function openDialog(next: FilePickerDialogOpenOptions) {
+ open.current = true;
+ options.current = next;
+ forceUpdate();
+ }
+
+ function closeDialog() {
+ open.current = false;
+ forceUpdate();
+ }
+
+ function FilePickerDialogAsync(props: Record<string, unknown>) {
+ return (
+ <React.Suspense fallback={<LoadingLazy />}>
+ <FilePickerDialog {...(props as any)} />
+ </React.Suspense>
+ );
+ }
+
+ const context = useMemo(
+ () => ({
+ openFilePickerDialog: openDialog,
+ closeFilePickerDialog: closeDialog,
+ }),
+ [],
+ );
+
+ const current = options.current;
+
+ return (
+ <FilePickerDialogContext.Provider value={context}>
+ <FilePickerDialogAsync
+ open={open.current}
+ onClose={closeDialog}
+ mode={current?.mode}
+ initialLocationId={current?.initialLocationId}
+ initialPath={current?.initialPath}
+ sourceLocationId={current?.sourceLocationId}
+ sourceDir={current?.sourceDir}
+ title={current?.title}
+ confirmLabel={current?.confirmLabel}
+ showLabelField={current?.showLabelField}
+ initialLabel={current?.initialLabel}
+ onSelect={(
+ entry: TS.FileSystemEntry,
+ link: string,
+ linkType: FilePickerLinkType,
+ label: string,
+ ) => {
+ // Read from the ref so callers can pass freshly-closed-over handlers.
+ options.current?.onSelect(entry, link, linkType, label);
+ }}
+ />
+ {children}
+ </FilePickerDialogContext.Provider>
+ );
+};
diff --git a/src/renderer/components/dialogs/hooks/useFilePickerDialogContext.tsx b/src/renderer/components/dialogs/hooks/useFilePickerDialogContext.tsx
new file mode 100644
index 000000000..120ffdce1
--- /dev/null
+++ b/src/renderer/components/dialogs/hooks/useFilePickerDialogContext.tsx
@@ -0,0 +1,6 @@
+import { useContext } from 'react';
+
+import { FilePickerDialogContext } from '-/components/dialogs/hooks/FilePickerDialogContextProvider';
+
+export const useFilePickerDialogContext = () =>
+ useContext(FilePickerDialogContext);
diff --git a/src/renderer/components/md/DescriptionMdEditor.tsx b/src/renderer/components/md/DescriptionMdEditor.tsx
index 8c81c7ccb..d9d1745a4 100644
--- a/src/renderer/components/md/DescriptionMdEditor.tsx
+++ b/src/renderer/components/md/DescriptionMdEditor.tsx
@@ -28,10 +28,12 @@ import AppConfig from '-/AppConfig';
import { CrepeRef, useCrepeHandler } from '-/components/md/useCrepeHandler';
import { createCrepeEditor } from '-/components/md/utils';
+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';
import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';
import { useEditedEntryMetaContext } from '-/hooks/useEditedEntryMetaContext';
import { useFilePropertiesContext } from '-/hooks/useFilePropertiesContext';
import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';
+import { extractContainingDirectoryPath } from '@tagspaces/tagspaces-common/paths';
import useFirstRender from '-/utils/useFirstRender';
import { useTranslation } from 'react-i18next';
@@ -45,6 +47,7 @@ const DescriptionMdEditor = forwardRef<CrepeRef, CrepeMdEditorProps>(
const { onFocus } = props;
const { t } = useTranslation();
const { currentDirectory } = useDirectoryContentContext();
+ const { findLocation } = useCurrentLocationContext();
const { metaActions } = useEditedEntryMetaContext();
const {
saveDescription,
@@ -68,6 +71,23 @@ const DescriptionMdEditor = forwardRef<CrepeRef, CrepeMdEditorProps>(
const isMac = AppConfig.isMacLike;
const mod = isMac ? '\u2318' : 'Ctrl+';
+ // Base folder for resolving relative markdown links. For a file's
+ // description the base is the file's containing folder; for a folder's
+ // description the base is the folder itself (the description "lives in"
+ // the folder). Falls back to currentDirectory if the entry path isn't
+ // available yet.
+ const linkBaseFolder = (() => {
+ if (openedEntry?.path) {
+ if (!openedEntry.isFile) {
+ return openedEntry.path;
+ }
+ const loc = findLocation(openedEntry.locationID);
+ const sep = loc?.getDirSeparator?.() || '/';
+ return extractContainingDirectoryPath(openedEntry.path, sep);
+ }
+ return currentDirectory?.path;
+ })();
+
const { get, loading } = useEditor(
(root) => {
// Build a Milkdown‐based “Crepe” editor:
@@ -80,12 +100,13 @@ const DescriptionMdEditor = forwardRef<CrepeRef, CrepeMdEditorProps>(
isEditDescriptionMode,
{},
placeholder,
- currentDirectory?.path,
+ linkBaseFolder,
openLink,
(newMd: string) => {
setDescription(newMd);
},
onFocus,
+ openedEntry?.locationID,
);
// Listen for status changes:
@@ -119,7 +140,7 @@ const DescriptionMdEditor = forwardRef<CrepeRef, CrepeMdEditorProps>(
return crepe;
},
- [currentDirectory?.path], //, isEditDescriptionMode],
+ [linkBaseFolder],
);
// Whenever openedEntry changes and the user hasn't manually edited,
diff --git a/src/renderer/components/md/LigthMdEditor.tsx b/src/renderer/components/md/LigthMdEditor.tsx
index c13eeac4a..f53d781d4 100644
--- a/src/renderer/components/md/LigthMdEditor.tsx
+++ b/src/renderer/components/md/LigthMdEditor.tsx
@@ -16,10 +16,14 @@
*
*/
import { createCrepeEditor } from '-/components/md/utils';
+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';
import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';
import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';
import { Crepe } from '@milkdown/crepe';
+import { EditorStatus } from '@milkdown/kit/core';
+import { getMarkdown, replaceAll } from '@milkdown/kit/utils';
import { Milkdown, useEditor } from '@milkdown/react';
+import { useEffect, useRef } from 'react';
interface LightMdEditorProps {
defaultContent: string;
@@ -29,10 +33,13 @@ function LightMdEditor(props: LightMdEditorProps) {
const { defaultContent, placeholder } = props;
const { currentDirectory } = useDirectoryContentContext();
+ const { currentLocation } = useCurrentLocationContext();
const { openLink } = useOpenedEntryContext();
- useEditor(
+ const crepeRef = useRef<Crepe | null>(null);
+
+ const { get, loading } = useEditor(
(root) => {
- return createCrepeEditor(
+ const crepe = createCrepeEditor(
root,
defaultContent,
false,
@@ -45,11 +52,47 @@ function LightMdEditor(props: LightMdEditorProps) {
placeholder,
currentDirectory?.path,
openLink,
+ undefined,
+ undefined,
+ currentLocation?.uuid,
);
+ crepe.editor.onStatusChange((status: EditorStatus) => {
+ if (status === EditorStatus.Created) {
+ crepeRef.current = crepe;
+ }
+ });
+ return crepe;
},
- [defaultContent],
+ // Recreate the editor only when the link resolution context changes —
+ // location id, current folder path, or readonly options. Content updates
+ // are handled imperatively in the effect below so the editor instance is
+ // stable across folder switches.
+ [currentDirectory?.path, currentLocation?.uuid],
);
+ // Imperatively push new defaultContent into the editor when it changes
+ // (e.g. user navigates to a different folder, or directoryMeta finishes
+ // loading after the editor mounted).
+ useEffect(() => {
+ const editor = get();
+ if (
+ loading ||
+ !editor ||
+ editor.status !== EditorStatus.Created ||
+ !crepeRef.current
+ ) {
+ return;
+ }
+ try {
+ const currentMd = editor.action(getMarkdown());
+ if (currentMd !== defaultContent) {
+ editor.action(replaceAll(defaultContent || '', true));
+ }
+ } catch (e) {
+ // Editor may not be fully ready; ignore.
+ }
+ }, [defaultContent, get, loading]);
+
return <Milkdown />;
}
diff --git a/src/renderer/components/md/useCrepeHandler.ts b/src/renderer/components/md/useCrepeHandler.ts
index 03b13b10a..a0425e903 100644
--- a/src/renderer/components/md/useCrepeHandler.ts
+++ b/src/renderer/components/md/useCrepeHandler.ts
@@ -1,6 +1,6 @@
import React, { useImperativeHandle } from 'react';
import { replaceAll, insert, getMarkdown } from '@milkdown/kit/utils';
-import { EditorStatus } from '@milkdown/kit/core';
+import { editorViewCtx, EditorStatus } from '@milkdown/kit/core';
import type { Editor } from '@milkdown/kit/core';
import { Crepe } from '@milkdown/crepe';
@@ -9,7 +9,9 @@ export interface CrepeRef {
insert: (markdown: string) => void;
setEditMode: (isEditMode: boolean) => void;
getMarkdown: () => string | undefined;
+ getSelectedText: () => string;
destroy: () => void;
+ focus: () => void;
}
export function useCrepeHandler(
@@ -27,7 +29,18 @@ export function useCrepeHandler(
insert: (markdown: string) => {
const editor = get();
if (loading || !editor || editor.status !== EditorStatus.Created) return;
- editor.action(insert(markdown));
+ // `inline: true` serializes the parsed doc to DOM and re-parses as an
+ // inline slice, so the inserted content (e.g. a markdown link) lands
+ // inside the current paragraph instead of splitting it into a new block.
+ editor.action(insert(markdown, true));
+ },
+ focus: () => {
+ const editor = get();
+ if (loading || !editor || editor.status !== EditorStatus.Created) return;
+ editor.action((ctx) => {
+ const view = ctx.get(editorViewCtx);
+ view?.focus();
+ });
},
setEditMode: (isEditable: boolean) => {
const crepe = getCrepe();
@@ -57,6 +70,19 @@ export function useCrepeHandler(
if (loading || !editor || editor.status !== EditorStatus.Created) return;
return editor.action(getMarkdown());
},
+ getSelectedText: () => {
+ const editor = get();
+ if (loading || !editor || editor.status !== EditorStatus.Created) {
+ return '';
+ }
+ return editor.action((ctx) => {
+ const view = ctx.get(editorViewCtx);
+ if (!view) return '';
+ const { from, to, empty } = view.state.selection;
+ if (empty) return '';
+ return view.state.doc.textBetween(from, to, ' ').trim();
+ });
+ },
destroy: () => {
const crepe = getCrepe();
if (crepe) {
diff --git a/src/renderer/components/md/utils.ts b/src/renderer/components/md/utils.ts
index 4a5bb37a6..ed832aa9a 100644
--- a/src/renderer/components/md/utils.ts
+++ b/src/renderer/components/md/utils.ts
@@ -42,6 +42,7 @@ export function createCrepeEditor(
openLink?: (url: string, options?) => void,
onChange?: (markdown: string, prevMarkdown: string) => void,
onFocus?: () => void,
+ currentLocationId?: string,
): Crepe {
const crepe = new Crepe({
root,
@@ -105,9 +106,30 @@ export function createCrepeEditor(
!href.includes('://') &&
!href.startsWith('/')
) {
- const absolutePath = resolveRelativePath(currentFolder, href);
+ // Markdown link URLs are URL-encoded so they roundtrip
+ // safely through the markdown serializer (spaces, brackets,
+ // parens). Decode before resolving against the filesystem
+ // path so segments match the real entry names.
+ let decodedHref = href;
+ try {
+ decodedHref = decodeURI(href);
+ } catch {
+ // leave as-is if malformed
+ }
+ const absolutePath = resolveRelativePath(
+ currentFolder,
+ decodedHref,
+ );
+ // Include the current location id so openLink knows where
+ // to look up the entry — otherwise it falls back to the
+ // "first RW location" which is often wrong in multi-
+ // location setups.
resolvedHref =
- 'ts://?cmdopen=' + encodeURIComponent(absolutePath);
+ 'ts://?cmdopen=' +
+ encodeURIComponent(absolutePath) +
+ (currentLocationId
+ ? '&tslid=' + encodeURIComponent(currentLocationId)
+ : '');
}
openLink(resolvedHref, { fullWidth: false });
return true;
diff --git a/src/renderer/containers/DialogsRoot.tsx b/src/renderer/containers/DialogsRoot.tsx
index d2e1cd9ce..f483ed7d9 100644
--- a/src/renderer/containers/DialogsRoot.tsx
+++ b/src/renderer/containers/DialogsRoot.tsx
@@ -26,6 +26,7 @@ import { EntryExistDialogContextProvider } from '-/components/dialogs/hooks/Entr
import { ImportMacTagDialogContextProvider } from '-/components/dialogs/hooks/ImportMacTagDialogContextProvider';
import { KeyboardDialogContextProvider } from '-/components/dialogs/hooks/KeyboardDialogContextProvider';
import { LicenseDialogContextProvider } from '-/components/dialogs/hooks/LicenseDialogContextProvider';
+import { FilePickerDialogContextProvider } from '-/components/dialogs/hooks/FilePickerDialogContextProvider';
import { LinkDialogContextProvider } from '-/components/dialogs/hooks/LinkDialogContextProvider';
import { MenuContextProvider } from '-/components/dialogs/hooks/MenuContextProvider';
import { NewAudioDialogContextProvider } from '-/components/dialogs/hooks/NewAudioDialogContextProvider';
@@ -67,6 +68,7 @@ const providers = [
AboutDialogContextProvider,
KeyboardDialogContextProvider,
LinkDialogContextProvider,
+ FilePickerDialogContextProvider,
ProTeaserDialogContextProvider,
AiGenerationDialogContextProvider,
ResolveConflictContextProvider,
diff --git a/src/renderer/hooks/FilePropertiesContextProvider.tsx b/src/renderer/hooks/FilePropertiesContextProvider.tsx
index 4d80bd2ab..87dfd93a1 100644
--- a/src/renderer/hooks/FilePropertiesContextProvider.tsx
+++ b/src/renderer/hooks/FilePropertiesContextProvider.tsx
@@ -81,22 +81,23 @@ export const FilePropertiesContextProvider = ({
const [isEditMode, setIsEditMode] = useState<boolean>(false);
const [isEditDescriptionMode, setIsEditDescriptionMode] =
- useState<boolean>(true);
+ useState<boolean>(false);
const [ignored, forceUpdate] = useReducer((x) => x + 1, 0, undefined);
useEffect(() => {
if (openedEntry) {
- // auto set EditDescriptionMode on opening
+ // Description starts in read mode for every opened entry. The user
+ // explicitly enters edit mode via the "Edit description" button (or by
+ // double-clicking the description area). On read-only locations, force
+ // edit mode off if it was somehow on.
const openedLocation = findLocation(openedEntry.locationID);
- if (openedLocation) {
- if (openedLocation.isReadOnly) {
- if (isEditDescriptionMode) {
- setIsEditDescriptionMode(false);
- }
- } else if (!isEditDescriptionMode) {
- setIsEditDescriptionMode(true);
- }
+ if (
+ openedLocation &&
+ openedLocation.isReadOnly &&
+ isEditDescriptionMode
+ ) {
+ setIsEditDescriptionMode(false);
}
if (
diff --git a/src/renderer/hooks/OpenedEntryContextProvider.tsx b/src/renderer/hooks/OpenedEntryContextProvider.tsx
index 83301ece2..3e0aa502b 100644
--- a/src/renderer/hooks/OpenedEntryContextProvider.tsx
+++ b/src/renderer/hooks/OpenedEntryContextProvider.tsx
@@ -746,7 +746,14 @@ export const OpenedEntryContextProvider = ({
setSelectedEntries([fsEntry]);
setEntryInFullWidth(options.fullWidth);
} else {
- openDirectory(fsEntry.path);
+ // Navigate the file manager AND also set the folder as the
+ // opened entry so the details panel (description tab, etc.)
+ // refreshes to the new folder. Matches the behavior of the
+ // 'ts' kind path for folder targets.
+ openDirectory(fsEntry.path).then(() => {
+ openEntry(fsEntry);
+ return true;
+ });
}
}
return true;
diff --git a/src/renderer/locales/en/core.json b/src/renderer/locales/en/core.json
index 748b621bd..b0153fc7f 100644
--- a/src/renderer/locales/en/core.json
+++ b/src/renderer/locales/en/core.json
@@ -45,6 +45,16 @@
"noFoldersMatch": "No folders match.",
"filterFolders": "Filter folders",
"recentDestinationGone": "That folder is no longer available.",
+ "chooseFile": "Choose file",
+ "chooseEntry": "Choose file or folder",
+ "selectAFile": "Select a file",
+ "selectAFolder": "Select a folder",
+ "selectAnEntry": "Select a file or folder",
+ "selectThisFolder": "Select this folder",
+ "select": "Select",
+ "relativeLink": "Relative link",
+ "insertFileOrFolderLink": "Insert file/folder link",
+ "linkText": "Link text",
"sortByName": "Name",
"addTagsToGroupTitle": "Add tags to tag group",
"addTagsToGroupTagsPlaceholder": "Comma separated list of tags",
diff --git a/src/renderer/reducers/settings-default.ts b/src/renderer/reducers/settings-default.ts
index bb4cdb735..0ef178465 100644
--- a/src/renderer/reducers/settings-default.ts
+++ b/src/renderer/reducers/settings-default.ts
@@ -125,6 +125,7 @@ export default {
tsSearchHistory: 10,
tsRecentMoveCopyDestinations: 5,
lastMoveCopyMode: 'move' as 'move' | 'copy',
+ lastLinkType: 'relative' as 'ts' | 'relative',
storedSearchesVisible: true,
showBookmarks: true,
fileOpenHistory: false,
diff --git a/src/renderer/reducers/settings.ts b/src/renderer/reducers/settings.ts
index ae47b68a1..8f624c64b 100644
--- a/src/renderer/reducers/settings.ts
+++ b/src/renderer/reducers/settings.ts
@@ -111,6 +111,7 @@ export const types = {
SET_FOLDER_OPEN_HISTORY: 'SET_FOLDER_OPEN_HISTORY',
SET_FILE_EDIT_HISTORY: 'SET_FILE_EDIT_HISTORY',
SET_LAST_MOVE_COPY_MODE: 'SETTINGS/SET_LAST_MOVE_COPY_MODE',
+ SET_LAST_LINK_TYPE: 'SETTINGS/SET_LAST_LINK_TYPE',
SET_HIDE_PRO_FEATURES: 'SETTINGS/SET_HIDE_PRO_FEATURES',
SET_AUTO_SAVE_DESCRIPTION: 'SETTINGS/SET_AUTO_SAVE_DESCRIPTION',
SET_PERSPECTIVE_ENABLED: 'SETTINGS/SET_PERSPECTIVE_ENABLED',
@@ -549,6 +550,12 @@ export default (state: any = defaultSettings, action: any) => {
lastMoveCopyMode: action.mode,
};
}
+ case types.SET_LAST_LINK_TYPE: {
+ return {
+ ...state,
+ lastLinkType: action.linkType,
+ };
+ }
case types.SET_FILE_EDIT_HISTORY: {
return {
...state,
@@ -979,6 +986,10 @@ export const actions = {
type: types.SET_LAST_MOVE_COPY_MODE,
mode,
}),
+ setLastLinkType: (linkType: 'ts' | 'relative') => ({
+ type: types.SET_LAST_LINK_TYPE,
+ linkType,
+ }),
checkForUpdate: () => (dispatch: (actions: Object) => void) => {
getLastVersionPromise()
.then((lastVersion) => {
@@ -1040,6 +1051,9 @@ export const getMaxRecentMoveCopyDestinations = (state: any): number => {
export const getLastMoveCopyMode = (state: any): 'move' | 'copy' => {
return state.settings.lastMoveCopyMode === 'copy' ? 'copy' : 'move';
};
+export const getLastLinkType = (state: any): 'ts' | 'relative' => {
+ return state.settings.lastLinkType === 'ts' ? 'ts' : 'relative';
+};
export const getEnableWS = (state: any) => state.settings.enableWS;
export const getDesktopMode = (state: any) => {
if (typeof AppConfig.ExtDisplayMode === 'undefined') {
diff --git a/src/renderer/services/utils-io.ts b/src/renderer/services/utils-io.ts
index bb6ded3cb..56dcccccc 100644
--- a/src/renderer/services/utils-io.ts
+++ b/src/renderer/services/utils-io.ts
@@ -25,10 +25,13 @@ import { prepareTagForExport } from '@tagspaces/tagspaces-common/misc';
import {
baseName,
cleanFrontDirSeparator,
+ cleanRootPath,
cleanTrailingDirSeparator,
+ extractContainingDirectoryPath,
extractFileExtension,
extractFileName,
extractTagsAsObjects,
+ generateSharingLink,
} from '@tagspaces/tagspaces-common/paths';
import { getUuid, loadJSONString } from '@tagspaces/tagspaces-common/utils-io';
import Links from 'assets/links';
@@ -723,6 +726,90 @@ export function getRelativeEntryPath(
return relEntryPath;
}
+/**
+ * Build a TagSpaces `ts://?...` sharing link for the given entry inside its
+ * location. Mirrors the canonical recipe used by LinksTab.tsx and
+ * HistoryContextProvider.tsx so all `ts://` links across the renderer have an
+ * identical shape.
+ */
+export function buildSharingLinkForEntry(
+ entry: TS.FileSystemEntry,
+ location: CommonLocation,
+): string {
+ const sep = location.getDirSeparator?.() || '/';
+ const relativeEntryPath = cleanRootPath(
+ entry.path || '',
+ location.path || '',
+ sep,
+ );
+ return generateSharingLink(
+ location.uuid,
+ relativeEntryPath,
+ undefined,
+ entry.uuid,
+ );
+}
+
+/**
+ * Build a Markdown-style relative path from `sourceDir` to the entry.
+ * Returns `null` when relativity is not possible — either no `sourceDir` was
+ * provided, or the entry and source dir are not under the same location root.
+ *
+ * Same directory → returns the leaf name (e.g. `B.md`).
+ * Descendant → `subdir/B.md`.
+ * Sibling/parent → `../images/B.png`.
+ *
+ * Callers are responsible for providing the correct `sourceDir`:
+ * - For a file's description: the file's containing directory
+ * - For a folder's description: the folder itself
+ */
+export function buildRelativeLinkForEntry(
+ entry: TS.FileSystemEntry,
+ location: CommonLocation,
+ sourceDir: string,
+): string | null {
+ if (!entry.path || !sourceDir) return null;
+ const root = cleanTrailingDirSeparator(location.path || '').replace(
+ /\\/g,
+ '/',
+ );
+ const target = cleanTrailingDirSeparator(entry.path).replace(/\\/g, '/');
+ const sourceDirNorm = cleanTrailingDirSeparator(sourceDir).replace(
+ /\\/g,
+ '/',
+ );
+
+ // Both source and target must live under the same location root.
+ if (root) {
+ if (!(target === root || target.startsWith(root + '/'))) return null;
+ if (!(sourceDirNorm === root || sourceDirNorm.startsWith(root + '/'))) {
+ return null;
+ }
+ }
+
+ const sourceRel = cleanFrontDirSeparator(
+ root ? sourceDirNorm.slice(root.length) : sourceDirNorm,
+ );
+ const targetRel = cleanFrontDirSeparator(
+ root ? target.slice(root.length) : target,
+ );
+ const sourceSegments = sourceRel ? sourceRel.split('/') : [];
+ const targetSegments = targetRel ? targetRel.split('/') : [];
+
+ let common = 0;
+ while (
+ common < sourceSegments.length &&
+ common < targetSegments.length &&
+ sourceSegments[common] === targetSegments[common]
+ ) {
+ common += 1;
+ }
+ const upHops = sourceSegments.length - common;
+ const tail = targetSegments.slice(common).join('/');
+ const relative = '../'.repeat(upHops) + tail;
+ return relative.length > 0 ? relative : './';
+}
+
/**
* @param entries
* @param entriesChanges Array<TS.FileSystemEntry> but partly changes from FileSystemEntry model like { path, tags:[] } are acceptable