Skip to content

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

Add-template-support-for-the-new-files (#2368)

Stanimir2ce977681fb1
diff --git a/package-lock.json b/package-lock.json
index e287710aa..47df4c971 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -208,7 +208,7 @@
"yarn": "please-use-npm"
},
"optionalDependencies": {
- "@tagspacespro/tagspacespro": "5.0.183"
+ "@tagspacespro/tagspacespro": "5.0.184-alpha.0"
}
},
"node_modules/@adobe/css-tools": {
@@ -19352,9 +19352,9 @@
}
},
"node_modules/@tagspacespro/tagspacespro": {
- "version": "5.0.183",
- "resolved": "https://npm.pkg.github.com/download/@tagspacespro/tagspacespro/5.0.183/d4ffd0d519c6d941d0f7b3532051f3ce6c1b9e95",
- "integrity": "sha512-FDlqyyyzLDO9FuFVcJ0Ew5zCPP0ta/xmRsgMfdgWTYRdUiYDHsVYNKfjD+9N+C7g5t1wvpqQaBtY0RALjLlALA==",
+ "version": "5.0.184-alpha.0",
+ "resolved": "https://npm.pkg.github.com/download/@tagspacespro/tagspacespro/5.0.184-alpha.0/628aa6dd095310e61c8cd64fcadf7a9e3ee86963",
+ "integrity": "sha512-4T2oBiy8LYLtY4CVfjte7FF+kOvqt2krQa4EXuIDY4YZYiUQD5wkG4rxtcWcMrh4vrGJfPMD+iXWPD6J7EPYXg==",
"license": "Proprietary",
"optional": true
},
diff --git a/package.json b/package.json
index 35e8b86f9..facd65542 100644
--- a/package.json
+++ b/package.json
@@ -246,7 +246,7 @@
"zod-to-json-schema": "^3.24.1"
},
"optionalDependencies": {
- "@tagspacespro/tagspacespro": "5.0.183"
+ "@tagspacespro/tagspacespro": "5.0.184-alpha.1"
},
"devDependencies": {
"@electron/notarize": "^2.5.0",
diff --git a/src/renderer/AppConfig.ts b/src/renderer/AppConfig.ts
index 3783ac923..1e9932e6c 100644
--- a/src/renderer/AppConfig.ts
+++ b/src/renderer/AppConfig.ts
@@ -190,4 +190,14 @@ AppConfig.showTSVersion =
? window.ExtShowTSVersion
: true;
+AppConfig.defaultTemplate =
+ typeof window !== 'undefined' && window.ExtDefaultFileTemplate !== undefined
+ ? window.ExtDefaultFileTemplate
+ : {
+ id: 'default',
+ name: 'Default',
+ content: '{createdInApp} ({date})',
+ fileNameTmpl: 'note[{timestamp}]',
+ };
+
export default AppConfig;
diff --git a/src/renderer/components/InfoIcon.tsx b/src/renderer/components/InfoIcon.tsx
index 86561d5b8..71701da4d 100644
--- a/src/renderer/components/InfoIcon.tsx
+++ b/src/renderer/components/InfoIcon.tsx
@@ -25,6 +25,9 @@ interface Props {
function InfoIcon(props: Props) {
const { tooltip } = props;
+ if (!tooltip) {
+ return <></>;
+ }
return (
<Tooltip title={tooltip}>
<HelpOutlined fontSize="small" sx={{ opacity: '0.7' }} />
diff --git a/src/renderer/components/dialogs/NewFileDialog.tsx b/src/renderer/components/dialogs/NewFileDialog.tsx
index babd9a908..bf90c5c4e 100644
--- a/src/renderer/components/dialogs/NewFileDialog.tsx
+++ b/src/renderer/components/dialogs/NewFileDialog.tsx
@@ -17,19 +17,21 @@
*/
import AppConfig from '-/AppConfig';
+import { getUuid } from '@tagspaces/tagspaces-common/utils-io';
import DraggablePaper from '-/components/DraggablePaper';
import TsButton from '-/components/TsButton';
import CreateFile from '-/components/dialogs/components/CreateFile';
import CreateLink from '-/components/dialogs/components/CreateLink';
import TargetPath from '-/components/dialogs/components/TargetPath';
+import TemplatesDropDown from '-/components/dialogs/components/TemplatesDropDown';
import TsDialogActions from '-/components/dialogs/components/TsDialogActions';
import TsDialogTitle from '-/components/dialogs/components/TsDialogTitle';
import { useTargetPathContext } from '-/components/dialogs/hooks/useTargetPathContext';
import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';
import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';
import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';
+import { Pro } from '-/pro';
import { TS } from '-/tagspaces.namespace';
-import versionMeta from '-/version.json';
import Dialog from '@mui/material/Dialog';
import DialogContent from '@mui/material/DialogContent';
import Paper from '@mui/material/Paper';
@@ -39,8 +41,10 @@ import {
formatDateTime4Tag,
locationType,
} from '@tagspaces/tagspaces-common/misc';
-import { useReducer, useRef } from 'react';
+import { useContext, useEffect, useReducer, useRef } from 'react';
import { useTranslation } from 'react-i18next';
+import versionMeta from '-/version.json';
+import useFirstRender from '-/utils/useFirstRender';
interface Props {
open: boolean;
@@ -50,7 +54,7 @@ interface Props {
}
function NewFileDialog(props: Props) {
- const { open, onClose, fileType } = props;
+ const { open, onClose, fileType, fileName } = props;
const { t } = useTranslation();
const { createFileAdvanced } = useOpenedEntryContext();
const { findLocation, openLocation, getFirstRWLocation } =
@@ -60,19 +64,80 @@ function NewFileDialog(props: Props) {
const haveError = useRef<boolean>(false);
const urlInputError = useRef<string>(undefined);
const firstRWLocation = getFirstRWLocation();
+ const fileTemplatesContext = Pro?.contextProviders?.FileTemplatesContext
+ ? useContext<TS.FileTemplatesContextData>(
+ Pro.contextProviders.FileTemplatesContext,
+ )
+ : undefined;
const [ignored, forceUpdate] = useReducer((x) => x + 1, 0, undefined);
const theme = useTheme();
const smallScreen = useMediaQuery(theme.breakpoints.down('md'));
- const fileName = useRef<string>(
- props.fileName ||
- (fileType === 'url' ? 'link' : 'note') +
+ const fileTemplate = fileTemplatesContext?.getTemplate(fileType);
+ const fileNameRef = useRef<string>(getFileName());
+ const fileContentRef = useRef<string>(getFileContent());
+ const firstRender = useFirstRender();
+
+ useEffect(() => {
+ if (
+ !firstRender &&
+ fileTemplate &&
+ fileNameRef.current &&
+ fileContentRef.current
+ ) {
+ fileNameRef.current = getFileName();
+ fileContentRef.current = getFileContent();
+ forceUpdate();
+ }
+ }, [fileTemplate]);
+
+ function getFileName() {
+ if (fileName) {
+ return (
+ fileName +
AppConfig.beginTagContainer +
formatDateTime4Tag(new Date(), true) +
- AppConfig.endTagContainer,
- );
+ AppConfig.endTagContainer
+ );
+ }
+ const template = fileTemplate ?? window.ExtDefaultFileTemplate;
+ if (template && template.fileNameTmpl !== undefined) {
+ return template.fileNameTmpl
+ .replace('{timestamp}', formatDateTime4Tag(new Date(), true))
+ .replace('{uuid}', getUuid());
+ }
+ return (
+ (fileType === 'url' ? 'link' : 'note') +
+ AppConfig.beginTagContainer +
+ formatDateTime4Tag(new Date(), true) +
+ AppConfig.endTagContainer
+ );
+ }
- const fileContent = useRef<string>('');
+ function getFileContent() {
+ if (fileType === 'url') return '';
+ const template = fileTemplate ?? window.ExtDefaultFileTemplate;
+ if (template && template.content) {
+ const creationDate = new Date().toISOString();
+ const dateTimeArray = creationDate.split('T');
+ return (
+ (fileType === 'html' ? '\n<br />\n' : ' \n\n') +
+ template.content
+ .replace(
+ '{createdInApp}',
+ `${t('core:createdIn')} ${versionMeta.name}`,
+ )
+ .replace('{date}', dateTimeArray[0])
+ .replace('{time}', dateTimeArray[1].split('.')[0])
+ );
+ }
+ return (
+ `${t('core:createdIn')} ${versionMeta.name}` +
+ ' (' +
+ new Date().toISOString().split('T')[0] +
+ ')'
+ );
+ }
function getFileType() {
if (fileType === 'txt') {
@@ -102,7 +167,7 @@ function NewFileDialog(props: Props) {
function createFile(fileType, targetPath) {
if (targetPath) {
- if (fileType === 'url' && !fileContent.current) {
+ if (fileType === 'url' && !fileContentRef.current) {
haveError.current = true;
urlInputError.current = t('core:emptyLink');
forceUpdate();
@@ -110,8 +175,8 @@ function NewFileDialog(props: Props) {
loadLocation();
createFileAdvanced(
targetPath,
- fileName.current,
- fileContent.current,
+ fileNameRef.current,
+ fileContentRef.current,
fileType,
);
onClose();
@@ -164,9 +229,9 @@ function NewFileDialog(props: Props) {
{fileType === 'url' ? (
<CreateLink
createFile={(type) => createFile(type, targetDirectoryPath)}
- handleFileNameChange={(name) => (fileName.current = name)}
+ handleFileNameChange={(name) => (fileNameRef.current = name)}
handleFileContentChange={(content) =>
- (fileContent.current = content)
+ (fileContentRef.current = content)
}
haveError={(error) => {
haveError.current = error;
@@ -174,23 +239,25 @@ function NewFileDialog(props: Props) {
forceUpdate();
}}
urlInputError={urlInputError.current}
- fileName={fileName.current}
+ fileName={fileNameRef.current}
/>
) : (
<CreateFile
fileType={fileType}
createFile={(type) => createFile(type, targetDirectoryPath)}
- handleFileNameChange={(name) => (fileName.current = name)}
+ handleFileNameChange={(name) => (fileNameRef.current = name)}
handleFileContentChange={(content) =>
- (fileContent.current = content)
+ (fileContentRef.current = content)
}
haveError={(error) => {
haveError.current = error;
forceUpdate();
}}
- fileName={fileName.current}
+ fileName={fileNameRef.current}
+ fileContent={fileContentRef.current}
/>
)}
+ <TemplatesDropDown fileType={fileType} label={t('templatesTab')} />
<TargetPath />
</DialogContent>
{!smallScreen && fileType && (
diff --git a/src/renderer/components/dialogs/SettingsDialog.tsx b/src/renderer/components/dialogs/SettingsDialog.tsx
index 4d7f54961..9542dc779 100644
--- a/src/renderer/components/dialogs/SettingsDialog.tsx
+++ b/src/renderer/components/dialogs/SettingsDialog.tsx
@@ -26,6 +26,7 @@ import {
} from '-/components/CommonIcons';
import DraggablePaper from '-/components/DraggablePaper';
import { BetaLabel } from '-/components/HelperComponents';
+import ArticleIcon from '@mui/icons-material/Article';
import TsButton from '-/components/TsButton';
import SettingsAI from '-/components/dialogs/components/SettingsAI';
import SettingsAdvanced from '-/components/dialogs/components/SettingsAdvanced';
@@ -46,6 +47,7 @@ import useMediaQuery from '@mui/material/useMediaQuery';
import Links from 'assets/links';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
+import SettingsTemplates from '-/components/dialogs/components/SettingsTemplates';
interface Props {
open: boolean;
@@ -162,6 +164,20 @@ function SettingsDialog(props: Props) {
</span>
}
/>
+ <Tab
+ style={{
+ textTransform: 'unset',
+ justifyContent: 'flex-start',
+ }}
+ data-tid="templatesDialogTID"
+ iconPosition="start"
+ icon={smallScreen ? '' : <ArticleIcon />}
+ label={
+ <span style={{ whiteSpace: 'nowrap' }}>
+ {t('core:templatesTab')}
+ </span>
+ }
+ />
</Tabs>
<div
data-tid="settingsDialog"
@@ -177,6 +193,7 @@ function SettingsDialog(props: Props) {
{currentTab === 3 && <SettingsExtensions />}
{currentTab === 4 && <SettingsAdvanced />}
{currentTab === 5 && <SettingsAI closeSettings={onClose} />}
+ {currentTab === 6 && <SettingsTemplates />}
</div>
</DialogContent>
);
diff --git a/src/renderer/components/dialogs/components/CreateFile.tsx b/src/renderer/components/dialogs/components/CreateFile.tsx
index 05019d3ea..2f6cf525e 100644
--- a/src/renderer/components/dialogs/components/CreateFile.tsx
+++ b/src/renderer/components/dialogs/components/CreateFile.tsx
@@ -21,14 +21,16 @@ import TsTextField from '-/components/TsTextField';
import { useTargetPathContext } from '-/components/dialogs/hooks/useTargetPathContext';
import { fileNameValidation } from '-/services/utils-io';
import { TS } from '-/tagspaces.namespace';
+import useFirstRender from '-/utils/useFirstRender';
import { ButtonGroup, FormControl } from '@mui/material';
import FormHelperText from '@mui/material/FormHelperText';
import Grid from '@mui/material/Grid';
-import React, { useEffect, useReducer, useState } from 'react';
+import React, { useEffect, useReducer, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
interface Props {
fileName: string;
+ fileContent: string;
handleFileNameChange: (fileName: string) => void;
handleFileContentChange: (fileContent: string) => void;
createFile: (fileType: TS.FileType) => void;
@@ -43,6 +45,7 @@ function CreateFile(props: Props) {
fileType,
createFile,
fileName,
+ fileContent,
handleFileNameChange,
handleFileContentChange,
haveError,
@@ -51,11 +54,19 @@ function CreateFile(props: Props) {
const { targetDirectoryPath } = useTargetPathContext();
const [inputError, setInputError] = useState<boolean>(false);
-
+ const fileContentRef = useRef<HTMLInputElement | null>(null);
+ const fileNameRef = useRef<HTMLInputElement | null>(null);
+ const firstRender = useFirstRender();
const [ignored, forceUpdate] = useReducer((x) => x + 1, 0, undefined);
-
const noSuitableLocation = !targetDirectoryPath;
+ useEffect(() => {
+ if (!firstRender && fileNameRef.current && fileContentRef.current) {
+ fileNameRef.current.value = fileName;
+ fileContentRef.current.value = fileContent;
+ }
+ }, [fileName, fileContent]);
+
useEffect(() => {
haveError(inputError);
}, [inputError]);
@@ -109,6 +120,7 @@ function CreateFile(props: Props) {
<Grid container spacing={1}>
<FormControl fullWidth={true} error={inputError}>
<TsTextField
+ inputRef={fileNameRef}
error={inputError}
name="entryName"
label={t('core:fileName')}
@@ -138,6 +150,8 @@ function CreateFile(props: Props) {
label={t('core:fileContent')}
multiline
rows={5}
+ inputRef={fileContentRef}
+ defaultValue={fileContent}
onChange={handleContentChange}
/>
</FormControl>
diff --git a/src/renderer/components/dialogs/components/SettingsAI.tsx b/src/renderer/components/dialogs/components/SettingsAI.tsx
index 0a9df7ecb..dbd3fc191 100644
--- a/src/renderer/components/dialogs/components/SettingsAI.tsx
+++ b/src/renderer/components/dialogs/components/SettingsAI.tsx
@@ -228,7 +228,6 @@ function SettingsAI(props: Props) {
>
<Accordion defaultExpanded>
<AccordionSummary
- //expandIcon={<ExpandIcon />}
aria-controls="ai-general"
id="ai-general-header"
data-tid="aiGeneralTID"
diff --git a/src/renderer/components/dialogs/components/SettingsTemplates.tsx b/src/renderer/components/dialogs/components/SettingsTemplates.tsx
new file mode 100644
index 000000000..6bc3755c3
--- /dev/null
+++ b/src/renderer/components/dialogs/components/SettingsTemplates.tsx
@@ -0,0 +1,409 @@
+/**
+ * TagSpaces - universal file and folder organizer
+ * Copyright (C) 2025-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 {
+ CreateFileIcon,
+ ExpandIcon,
+ RemoveIcon,
+} from '-/components/CommonIcons';
+import { ProLabel } from '-/components/HelperComponents';
+import InfoIcon from '-/components/InfoIcon';
+import TsButton from '-/components/TsButton';
+import TsIconButton from '-/components/TsIconButton';
+import TsTextField from '-/components/TsTextField';
+import TsToggleButton from '-/components/TsToggleButton';
+import TemplatesDropDown from '-/components/dialogs/components/TemplatesDropDown';
+import { useNotificationContext } from '-/hooks/useNotificationContext';
+import { Pro } from '-/pro';
+import { TS } from '-/tagspaces.namespace';
+import CheckIcon from '@mui/icons-material/Check';
+import {
+ Accordion,
+ AccordionDetails,
+ AccordionSummary,
+ Typography,
+} from '@mui/material';
+import FormHelperText from '@mui/material/FormHelperText';
+import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
+import { getUuid } from '@tagspaces/tagspaces-common/utils-io';
+import React, { useContext } from 'react';
+import { useTranslation } from 'react-i18next';
+
+interface Props {}
+
+function SettingsTemplates(props: Props) {
+ const { t } = useTranslation();
+ const { showNotification } = useNotificationContext();
+ const editedTemplate = React.useRef<TS.FileTemplate>(undefined);
+ const [ignored, forceUpdate] = React.useReducer((x) => x + 1, 0, undefined);
+
+ const fileTemplatesContext = Pro?.contextProviders?.FileTemplatesContext
+ ? useContext<TS.FileTemplatesContextData>(
+ Pro.contextProviders.FileTemplatesContext,
+ )
+ : undefined;
+ const templatesArray = fileTemplatesContext?.getTemplates() ?? [
+ AppConfig.defaultTemplate,
+ ];
+
+ function saveTemplate(key?: string) {
+ if (fileTemplatesContext) {
+ if (key && editedTemplate.current) {
+ fileTemplatesContext.setTemplate(key, editedTemplate.current);
+ editedTemplate.current = undefined;
+ forceUpdate();
+ } else {
+ // new template
+ const id = getUuid();
+ const def = AppConfig.defaultTemplate;
+ const temp = {
+ id,
+ name: 'new template',
+ content: def.content,
+ fileNameTmpl: def.fileNameTmpl,
+ };
+ editedTemplate.current = temp;
+ fileTemplatesContext.setTemplate(id, temp);
+ forceUpdate();
+ }
+ } else {
+ showNotification(
+ 'Adding new file template is Pro feature',
+ 'default',
+ true,
+ );
+ }
+ }
+ function deleteTemplate(key: string) {
+ if (fileTemplatesContext && key) {
+ fileTemplatesContext.delTemplate(key);
+ forceUpdate();
+ }
+ }
+ function cancelSavingTemplate() {
+ editedTemplate.current = undefined;
+ forceUpdate();
+ }
+
+ function currentTemplate(template) {
+ return editedTemplate.current && editedTemplate.current.id === template.id
+ ? editedTemplate.current
+ : template;
+ }
+
+ /* const defaultTemplate =
+ templatesArray?.find((t) => t.type === undefined) ||
+ AppConfig.defaultTemplate;*/
+
+ function toggleType(template: TS.FileTemplate, type: 'html' | 'md' | 'txt') {
+ if (!fileTemplatesContext) return;
+
+ const merged: TS.FileTemplate = { ...template, ...editedTemplate.current };
+
+ if (merged.type === type) {
+ // remove the type property from the merged result
+ const { type, ...withoutType } = merged;
+ editedTemplate.current = withoutType;
+ } else {
+ // set type to 'html' otherwise
+ editedTemplate.current = { ...merged, type };
+ }
+
+ forceUpdate();
+ }
+
+ return (
+ <div
+ style={{
+ overflowX: 'hidden',
+ overflowY: 'auto',
+ height: '100%',
+ padding: 10,
+ }}
+ >
+ <Accordion defaultExpanded>
+ <AccordionSummary
+ aria-controls={'file-template-content'}
+ id="file-template-header"
+ data-tid={'fileTemplatesTID'}
+ >
+ <Typography>{t('core:templatesTab')}</Typography>
+ <ProLabel />
+ <InfoIcon
+ tooltip={
+ !!window.ExtFileTemplates &&
+ 'Template functionalities are disabled because templates are externally configured'
+ }
+ ></InfoIcon>
+ </AccordionSummary>
+ <AccordionDetails>
+ <Typography
+ variant="caption"
+ style={{ display: 'block', marginTop: -20, marginBottom: 10 }}
+ >
+ Supported template variables in the template content are:{' '}
+ <b>
+ {'{'}date{'}'}
+ </b>
+ ,{' '}
+ <b>
+ {'{'}time{'}'}
+ </b>{' '}
+ and{' '}
+ <b>
+ {'{'}createdInApp{'}'}
+ </b>
+ . The file name template supports{' '}
+ <b>
+ {'{'}timestamp{'}'}
+ </b>{' '}
+ and{' '}
+ <b>
+ {'{'}uuid{'}'}
+ </b>
+ . The last one will generate a unique identifier so the new file
+ will get an unique name.
+ </Typography>
+ <TsButton
+ disabled={!!window.ExtFileTemplates}
+ onClick={() => {
+ saveTemplate();
+ }}
+ style={{ marginBottom: 10 }}
+ startIcon={<CreateFileIcon />}
+ >
+ {t('addTemplate')}
+ </TsButton>
+ <TemplatesDropDown disabled={!!window.ExtFileTemplates} />
+ <TemplatesDropDown
+ disabled={!!window.ExtFileTemplates}
+ fileType="md"
+ />
+ <TemplatesDropDown
+ disabled={!!window.ExtFileTemplates}
+ fileType="txt"
+ />
+ <TemplatesDropDown
+ disabled={!!window.ExtFileTemplates}
+ fileType="html"
+ />
+ </AccordionDetails>
+ </Accordion>
+ {templatesArray &&
+ templatesArray.map((template) => (
+ <Accordion
+ defaultExpanded={
+ editedTemplate.current &&
+ editedTemplate.current.id === template.id
+ }
+ >
+ <AccordionSummary
+ expandIcon={<ExpandIcon />}
+ aria-controls={template.id + 'content'}
+ data-tid={template.id + 'TemplateTID'}
+ sx={{
+ '& .MuiAccordionSummary-content': { alignItems: 'center' },
+ }}
+ >
+ <Typography>
+ {currentTemplate(template).name}
+ {template.type ? (
+ <span
+ style={{
+ marginLeft: 5,
+ padding: 2,
+ fontSize: 12,
+ textTransform: 'uppercase',
+ border: '1px solid gray',
+ borderRadius: '3px',
+ }}
+ >
+ {template.type}
+ </span>
+ ) : (
+ ''
+ )}
+ {fileTemplatesContext?.getTemplate(template.type)?.id ===
+ template.id
+ ? ' - ' + t('defaultTemplate')
+ : ''}
+ </Typography>
+ <TsIconButton
+ disabled={!Pro || !!window.ExtFileTemplates}
+ aria-label="removeTemplate"
+ tooltip={t('core:remove')}
+ onClick={(e) => {
+ e.stopPropagation();
+ const result = confirm(
+ 'Do you want to remove "' + template.name + '"?',
+ );
+ if (result) {
+ deleteTemplate(template.id);
+ }
+ }}
+ data-tid="removeAIProviderTID"
+ >
+ <RemoveIcon />
+ </TsIconButton>
+ {editedTemplate.current &&
+ editedTemplate.current.id === template.id && (
+ <>
+ {editedTemplate.current.name &&
+ editedTemplate.current.fileNameTmpl && (
+ <TsButton
+ variant="text"
+ data-tid={'save' + template.id + 'TID'}
+ onClick={() => saveTemplate(template.id)}
+ >
+ {t('core:save')}
+ </TsButton>
+ )}
+ <TsButton
+ variant="text"
+ data-tid={'cancel' + template.id + 'TID'}
+ onClick={() => cancelSavingTemplate()}
+ >
+ {t('core:cancel')}
+ </TsButton>
+ </>
+ )}
+ </AccordionSummary>
+ <AccordionDetails>
+ <TsTextField
+ fullWidth
+ disabled={!Pro || !!window.ExtFileTemplates}
+ label={t('name')}
+ error={!currentTemplate(template).name}
+ value={currentTemplate(template).name}
+ onChange={(e) => {
+ if (fileTemplatesContext) {
+ editedTemplate.current = {
+ ...template,
+ ...editedTemplate.current,
+ name: e.target.value,
+ };
+ forceUpdate();
+ }
+ }}
+ />
+ {!currentTemplate(template).name && (
+ <FormHelperText sx={{ marginTop: 0, color: 'red' }}>
+ {t('core:templateNameEmptyError')}
+ </FormHelperText>
+ )}
+ <ToggleButtonGroup
+ value={currentTemplate(template).type}
+ exclusive
+ style={{ marginTop: 10, marginBottom: 10 }}
+ title="Template type"
+ >
+ <TsToggleButton
+ value={false}
+ data-tid="templateMdTypeTID"
+ style={{
+ borderTopRightRadius: 0,
+ borderBottomRightRadius: 0,
+ }}
+ onClick={() => toggleType(template, 'md')}
+ >
+ <div style={{ display: 'flex', textTransform: 'unset' }}>
+ {currentTemplate(template).type === 'md' && <CheckIcon />}
+ &nbsp;&nbsp;MD&nbsp;&nbsp;
+ </div>
+ </TsToggleButton>
+ <TsToggleButton
+ value={false}
+ data-tid="templateTxtTypeTID"
+ style={{
+ borderTopRightRadius: 0,
+ borderBottomRightRadius: 0,
+ borderTopLeftRadius: 0,
+ borderBottomLeftRadius: 0,
+ }}
+ onClick={() => toggleType(template, 'txt')}
+ >
+ <div style={{ display: 'flex', textTransform: 'unset' }}>
+ {currentTemplate(template).type === 'txt' && <CheckIcon />}
+ &nbsp;TXT&nbsp;
+ </div>
+ </TsToggleButton>
+ <TsToggleButton
+ value={false}
+ data-tid="templateTxtTypeTID"
+ style={{
+ borderTopLeftRadius: 0,
+ borderBottomLeftRadius: 0,
+ }}
+ onClick={() => toggleType(template, 'html')}
+ >
+ <div style={{ display: 'flex', textTransform: 'unset' }}>
+ {currentTemplate(template).type === 'html' && <CheckIcon />}
+ HTML
+ </div>
+ </TsToggleButton>
+ </ToggleButtonGroup>
+ <TsTextField
+ fullWidth
+ multiline
+ rows={5}
+ disabled={!Pro || !!window.ExtFileTemplates}
+ label={t('core:templateContent')}
+ value={currentTemplate(template).content}
+ onChange={(e) => {
+ if (fileTemplatesContext) {
+ editedTemplate.current = {
+ ...template,
+ ...editedTemplate.current,
+ content: e.target.value,
+ };
+ forceUpdate();
+ }
+ }}
+ />
+ <TsTextField
+ fullWidth
+ disabled={!Pro || !!window.ExtFileTemplates}
+ error={!currentTemplate(template).fileNameTmpl}
+ label={t('fileNameTmpl')}
+ placeholder="e.g.: note[{timestamp}] or {uuid}"
+ value={currentTemplate(template).fileNameTmpl}
+ onChange={(e) => {
+ if (fileTemplatesContext) {
+ editedTemplate.current = {
+ ...template,
+ ...editedTemplate.current,
+ fileNameTmpl: e.target.value,
+ };
+ forceUpdate();
+ }
+ }}
+ />
+ {!currentTemplate(template).fileNameTmpl && (
+ <FormHelperText sx={{ marginTop: 0, color: 'red' }}>
+ {t('core:fileNameEmptyError')}
+ </FormHelperText>
+ )}
+ </AccordionDetails>
+ </Accordion>
+ ))}
+ </div>
+ );
+}
+
+export default SettingsTemplates;
diff --git a/src/renderer/components/dialogs/components/TemplatesDropDown.tsx b/src/renderer/components/dialogs/components/TemplatesDropDown.tsx
new file mode 100644
index 000000000..31b9647c9
--- /dev/null
+++ b/src/renderer/components/dialogs/components/TemplatesDropDown.tsx
@@ -0,0 +1,79 @@
+/**
+ * TagSpaces - universal file and folder organizer
+ * Copyright (C) 2025-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 TsSelect from '-/components/TsSelect';
+import { Pro } from '-/pro';
+import { TS } from '-/tagspaces.namespace';
+import MenuItem from '@mui/material/MenuItem';
+import { useContext } from 'react';
+import { useTranslation } from 'react-i18next';
+
+interface Props {
+ fileType?: 'md' | 'txt' | 'html' | 'url';
+ label?: string;
+ disabled?: boolean;
+}
+
+function TemplatesDropDown(props: Props) {
+ const { fileType, label, disabled = false } = props;
+ const { t } = useTranslation();
+ const fileTemplatesContext = Pro?.contextProviders?.FileTemplatesContext
+ ? useContext<TS.FileTemplatesContextData>(
+ Pro.contextProviders.FileTemplatesContext,
+ )
+ : undefined;
+ const templatesArray = fileTemplatesContext?.getTemplates();
+
+ if (fileType === 'url' || !templatesArray) {
+ return null;
+ }
+
+ const templates = fileType
+ ? templatesArray.filter((t) => t.type === fileType)
+ : templatesArray.filter((t) => t.type === undefined);
+
+ if (!templates || templates.length < 2) {
+ return null;
+ }
+
+ const selectLabel = label ? label : t('defaultTemplate' + (fileType ?? ''));
+
+ return (
+ <TsSelect
+ data-tid="tagDelimiterTID"
+ label={selectLabel}
+ disabled={disabled}
+ fullWidth={true}
+ value={fileTemplatesContext?.getTemplate(fileType)?.id}
+ onChange={(event) =>
+ fileTemplatesContext?.setTemplateActive(event.target.value)
+ }
+ >
+ {templates.map((tp, index) => (
+ <MenuItem value={tp.id}>
+ {
+ tp.name
+ // + (index === 0 ? ' (' + t('core:defaultTemplate') + ')' : '')
+ }
+ </MenuItem>
+ ))}
+ </TsSelect>
+ );
+}
+
+export default TemplatesDropDown;
diff --git a/src/renderer/containers/Root.tsx b/src/renderer/containers/Root.tsx
index ffd531bcd..12c9aae70 100644
--- a/src/renderer/containers/Root.tsx
+++ b/src/renderer/containers/Root.tsx
@@ -109,11 +109,13 @@ export default function Root({ store, persistor }: RootType) {
<Pro.contextProviders.ThumbDialogContextProvider>
<Pro.contextProviders.BgndDialogContextProvider>
<Pro.contextProviders.AiTemplatesContextProvider>
- <ChatContextProvider>
- <DialogsRoot>
- <MainPage />
- </DialogsRoot>
- </ChatContextProvider>
+ <Pro.contextProviders.FileTemplatesContextProvider>
+ <ChatContextProvider>
+ <DialogsRoot>
+ <MainPage />
+ </DialogsRoot>
+ </ChatContextProvider>
+ </Pro.contextProviders.FileTemplatesContextProvider>
</Pro.contextProviders.AiTemplatesContextProvider>
</Pro.contextProviders.BgndDialogContextProvider>
</Pro.contextProviders.ThumbDialogContextProvider>
diff --git a/src/renderer/hooks/OpenedEntryContextProvider.tsx b/src/renderer/hooks/OpenedEntryContextProvider.tsx
index f34260d9a..4541da5d0 100644
--- a/src/renderer/hooks/OpenedEntryContextProvider.tsx
+++ b/src/renderer/hooks/OpenedEntryContextProvider.tsx
@@ -71,6 +71,7 @@ import React, {
} from 'react';
import { useTranslation } from 'react-i18next';
import { useDispatch, useSelector } from 'react-redux';
+import { Pro } from '-/pro';
type OpenedEntryContextData = {
haveOpenedEntry: boolean;
@@ -111,7 +112,8 @@ type OpenedEntryContextData = {
targetPath: string,
fileName: string,
content: string,
- fileType: TS.FileType,
+ fileType?: TS.FileType,
+ createMeta?: string,
) => void;
createFile: () => void;
getOpenedDirProps: () => Promise<TS.DirProp>;
@@ -988,7 +990,6 @@ export const OpenedEntryContextProvider = ({
) {
const creationDate = new Date().toISOString();
const fileNameAndExt = fileName + '.' + fileType;
- const creationMeta = `${t('core:createdIn')} ${versionMeta.name} (${creationDate.substring(0, 10)})`;
const filePath =
normalizePath(targetPath) +
(currentLocation
@@ -1005,12 +1006,10 @@ export const OpenedEntryContextProvider = ({
creationDate +
'" >' +
content +
- '\n<br />\n' +
- creationMeta +
'\n';
'</body>' + newHTMLFileContent.split('<body></body>')[1];
} else if (fileType === 'md') {
- fileContent = content + ' \n\n' + creationMeta + '\n';
+ fileContent = content;
} else if (fileType === 'url') {
fileContent = '[InternetShortcut]\n' + 'URL=' + content + '\n';
}
diff --git a/src/renderer/locales/en/core.json b/src/renderer/locales/en/core.json
index 5d6db7305..9c719f3b5 100644
--- a/src/renderer/locales/en/core.json
+++ b/src/renderer/locales/en/core.json
@@ -988,5 +988,15 @@
"generateImageTags": "Generate Image Tags",
"tagDelimiterChange": "Changing Tag Delimiter will hide current tags with the old delimiter",
"space": "Space",
+ "templatesTab": "File Templates",
+ "defaultTemplate": "Default Template",
+ "defaultTemplatemd": "Default template for markdown files (.md)",
+ "defaultTemplatetxt": "Default template for text files (.txt)",
+ "defaultTemplatehtml": "Default template for HTML files (.html)",
+ "addTemplate": "Create New Template",
+ "templateContent": "Template Content",
+ "fileNameTmpl": "File Name Template",
+ "templateNameEmptyError": "Template name can't be empty",
+ "fileNameEmptyError": "Filename template can't be empty",
"-": "-"
}
diff --git a/src/renderer/services/utils-io.ts b/src/renderer/services/utils-io.ts
index e968410f8..75a173d9c 100644
--- a/src/renderer/services/utils-io.ts
+++ b/src/renderer/services/utils-io.ts
@@ -16,6 +16,7 @@
*/
import AppConfig from '-/AppConfig';
+import defaultSettings from '-/reducers/settings-default';
import { TS } from '-/tagspaces.namespace';
import { CommonLocation } from '-/utils/CommonLocation';
import { prepareTagForExport } from '@tagspaces/tagspaces-common/misc';
@@ -29,7 +30,6 @@ import {
import { getUuid } from '@tagspaces/tagspaces-common/utils-io';
import { saveAs } from 'file-saver';
import removeMd from 'remove-markdown';
-import defaultSettings from '-/reducers/settings-default';
import versionMeta from '../version.json';
export const instanceId = getUuid();
diff --git a/src/renderer/tagspaces.d.ts b/src/renderer/tagspaces.d.ts
index dac0bffe9..bbd10dc75 100644
--- a/src/renderer/tagspaces.d.ts
+++ b/src/renderer/tagspaces.d.ts
@@ -86,6 +86,8 @@ declare interface Window {
ExtDescriptionFromImagePrompt?: string;
ExtTagsFromTextPrompt?: string;
ExtTagsFromImagePrompt?: string;
+ ExtFileTemplates?: Array<any>;
+ ExtDefaultFileTemplate?: any;
}
declare interface NodeModule {
diff --git a/src/renderer/tagspaces.namespace.d.ts b/src/renderer/tagspaces.namespace.d.ts
index 43e33f8a2..490fca37d 100644
--- a/src/renderer/tagspaces.namespace.d.ts
+++ b/src/renderer/tagspaces.namespace.d.ts
@@ -325,6 +325,23 @@ export namespace TS {
setTemplate: (key: string, value: string) => void;
};
+ interface FileTemplate {
+ id: string;
+ content: string; // e.g: Created with TagSpaces on 20250605'
+ name?: string; // 'Template Name'
+ type?: 'md' | 'txt' | 'html';
+ fileNameTmpl?: string; // e.g. note, issue, task
+ screenshotUrl?: string; //'dataURL'
+ }
+
+ type FileTemplatesContextData = {
+ getTemplate: (type: string) => FileTemplate | undefined;
+ setTemplate: (id: string, value: FileTemplate) => void;
+ setTemplateActive: (id: string) => void;
+ getTemplates: () => TS.FileTemplate[];
+ delTemplate: (id: string) => void;
+ };
+
interface EditedEntryPath {
action: EditedEntryAction;
path: string;