mirror of
https://github.com/yu-i-i/overleaf-cep.git
synced 2026-11-12 13:13:45 +01:00
Template Gallery: add support
Make Template Gallery optional; rename environment variables
Refactor Template Gallery; resolves #38 and #39:
- replace free-text license input with a select box
- improve visual presentation of modals and enhance keyboard interaction
Template Gallery: replace markdown-it with marked
Fix template publishing to align with upstream project context changes
Template gallery: ui components were moved to shared folder
Fix style of Templates button in navbar
Template gallery: Fix `OLModal` usage (see upstream commit 19b3834)
Template gallery: Fix import after upstream converted `CompileManager`, `ClsiManager` and `RateLimiterMiddleware` to ESM
Template gallery: Fix import after upstream converted `AuthenticationController`, `ProjectGetter`, ProjectLocator` and `DocumentUpdaterHandler` to ESM
Template Gallery: migration to 6.1.0
- enable menu for editor redisign
- move frontend code to modules
Template gallery: add template management authorization middleware
- middleware to enforce template access rules
- introduce template manager role
- fix minor issues
Template Gallery: fix for 6.2.0
Template Gallery: fix for 6.3.0 and show language in the details
This commit is contained in:
@@ -67,6 +67,11 @@ if (settings.filestore.stores.template_files) {
|
||||
keyBuilder.templateFileKeyMiddleware,
|
||||
fileController.insertFile
|
||||
)
|
||||
app.delete(
|
||||
'/template/:template_id/v/:version/:format',
|
||||
keyBuilder.templateFileKeyMiddleware,
|
||||
fileController.deleteFile
|
||||
)
|
||||
}
|
||||
|
||||
app.get(
|
||||
|
||||
@@ -6,7 +6,7 @@ import Errors from './Errors.js'
|
||||
|
||||
const { ConversionError } = Errors
|
||||
|
||||
const APPROVED_FORMATS = ['png']
|
||||
const APPROVED_FORMATS = ['png', 'jpg']
|
||||
const FOURTY_SECONDS = 40 * 1000
|
||||
const KILL_SIGNAL = 'SIGTERM'
|
||||
|
||||
|
||||
@@ -111,7 +111,9 @@ async function _getConvertedFileAndCache(bucket, key, convertedKey, opts) {
|
||||
let convertedFsPath
|
||||
try {
|
||||
convertedFsPath = await _convertFile(bucket, key, opts)
|
||||
await ImageOptimiser.promises.compressPng(convertedFsPath)
|
||||
if (convertedFsPath.toLowerCase().endsWith(".png")) {
|
||||
await ImageOptimiser.promises.compressPng(convertedFsPath)
|
||||
}
|
||||
await PersistorManager.sendFile(bucket, convertedKey, convertedFsPath)
|
||||
} catch (err) {
|
||||
LocalFileWriter.deleteFile(convertedFsPath, () => {})
|
||||
|
||||
@@ -930,7 +930,7 @@ const _ProjectController = {
|
||||
}
|
||||
|
||||
const isAdminOrTemplateOwner =
|
||||
hasAdminAccess(user) || Settings.templates?.user_id === userId
|
||||
hasAdminAccess(user) || Settings.templates?.nonAdminCanManage || Settings.templates?.user_id === userId
|
||||
const showTemplatesServerPro =
|
||||
Features.hasFeature('templates-server-pro') && isAdminOrTemplateOwner
|
||||
|
||||
|
||||
@@ -274,7 +274,7 @@ async function _createBlankProject(
|
||||
_id: 1,
|
||||
...SplitTestUserGetter.getProjection('history-ranges-support'),
|
||||
})
|
||||
project.spellCheckLanguage = user.ace.spellCheckLanguage
|
||||
project.spellCheckLanguage = attributes.spellCheckLanguage || user.ace.spellCheckLanguage
|
||||
const historyRangesSupportAssignment =
|
||||
await SplitTestHandler.promises.getAssignmentForMongoUser(
|
||||
user,
|
||||
|
||||
@@ -5,11 +5,11 @@ import ProjectHelper from '../Project/ProjectHelper.mjs'
|
||||
import { expressify } from '@overleaf/promise-utils'
|
||||
import { parseReq, z } from '../../infrastructure/Validation.mjs'
|
||||
|
||||
// numeric v1 ids (template id / template version id)
|
||||
const numericId = z.string().regex(/^[0-9]+$/)
|
||||
const objectId = z.string().regex(/^[a-fA-F0-9]{24}$/)
|
||||
|
||||
const getV1TemplateSchema = z.object({
|
||||
params: z.strictObject({ Template_version_id: numericId }),
|
||||
params: z.strictObject({ Template_version_id: objectId }),
|
||||
query: z.object({
|
||||
id: numericId,
|
||||
templateName: z.string().optional(),
|
||||
@@ -17,25 +17,27 @@ const getV1TemplateSchema = z.object({
|
||||
texImage: z.string().optional(),
|
||||
mainFile: z.string().optional(),
|
||||
brandVariationId: z.coerce.number().int().positive().optional(),
|
||||
language: z.string().optional(),
|
||||
}),
|
||||
})
|
||||
|
||||
// Rollout-temporary fallback (pre-refinement schema from main); delete
|
||||
// when this route's REQ_VALIDATION_MODE instrumentation is removed.
|
||||
const getV1TemplateFallbackSchema = z.object({
|
||||
params: z.object({ Template_version_id: numericId }).passthrough(),
|
||||
params: z.object({ Template_version_id: objectId }).passthrough(),
|
||||
query: z.object({ id: numericId }).passthrough(),
|
||||
})
|
||||
|
||||
const createProjectFromV1TemplateSchema = z.object({
|
||||
body: z.strictObject({
|
||||
templateId: numericId,
|
||||
templateId: objectId,
|
||||
templateVersionId: numericId,
|
||||
brandVariationId: z.coerce.number().int().positive().optional(),
|
||||
compiler: z.string().optional(),
|
||||
mainFile: z.string().optional(),
|
||||
templateName: z.string().optional(),
|
||||
imageName: z.string().optional(),
|
||||
language: z.string().optional(),
|
||||
}),
|
||||
})
|
||||
|
||||
@@ -44,7 +46,7 @@ const createProjectFromV1TemplateSchema = z.object({
|
||||
const createProjectFromV1TemplateFallbackSchema = z.object({
|
||||
body: z
|
||||
.object({
|
||||
templateId: numericId,
|
||||
templateId: objectId,
|
||||
templateVersionId: numericId,
|
||||
})
|
||||
.passthrough(),
|
||||
@@ -59,14 +61,16 @@ const TemplatesController = {
|
||||
fallbackSchema: getV1TemplateFallbackSchema,
|
||||
})
|
||||
const data = {
|
||||
templateVersionId,
|
||||
templateId: query.id,
|
||||
templateVersionId: query.id,
|
||||
templateId: templateVersionId,
|
||||
name: query.templateName,
|
||||
compiler: ProjectHelper.compilerFromV1Engine(query.latexEngine),
|
||||
imageName: query.texImage,
|
||||
mainFile: query.mainFile,
|
||||
brandVariationId: query.brandVariationId,
|
||||
language: query.language,
|
||||
}
|
||||
|
||||
res.render(
|
||||
path.resolve(
|
||||
import.meta.dirname,
|
||||
@@ -81,6 +85,9 @@ const TemplatesController = {
|
||||
fallbackSchema: createProjectFromV1TemplateFallbackSchema,
|
||||
})
|
||||
const userId = SessionManager.getLoggedInUserId(req.session)
|
||||
|
||||
console.log("BODY = ", body)
|
||||
|
||||
const project = await TemplatesManager.promises.createProjectFromV1Template(
|
||||
body.brandVariationId,
|
||||
body.compiler,
|
||||
@@ -89,7 +96,8 @@ const TemplatesController = {
|
||||
body.templateName,
|
||||
body.templateVersionId,
|
||||
userId,
|
||||
body.imageName
|
||||
body.imageName,
|
||||
body.language
|
||||
)
|
||||
delete req.session.templateData
|
||||
if (!project) {
|
||||
|
||||
@@ -20,6 +20,7 @@ import OError from '@overleaf/o-error'
|
||||
|
||||
const { promises: ProjectRootDocManager } = ProjectRootDocManagerModule
|
||||
const { promises: ProjectOptionsHandler } = ProjectOptionsHandlerModule
|
||||
const TIMEOUT = 30000 // 30 sec
|
||||
|
||||
const TemplatesManager = {
|
||||
async createProjectFromV1Template(
|
||||
@@ -30,33 +31,33 @@ const TemplatesManager = {
|
||||
templateName,
|
||||
templateVersionId,
|
||||
userId,
|
||||
imageName
|
||||
imageName,
|
||||
spellCheckLanguage
|
||||
) {
|
||||
compiler = ProjectOptionsHandler.normalizeCompiler(
|
||||
compiler || settings.defaultLatexCompiler
|
||||
)
|
||||
imageName = ProjectOptionsHandler.normalizeImageName(
|
||||
imageName || 'wl_texlive:2018.1'
|
||||
)
|
||||
try {
|
||||
imageName = ProjectOptionsHandler.normalizeImageName(imageName)
|
||||
} catch {
|
||||
logger.warn( { templateId, imageName }, 'cannot use the image required by the template, using the default image')
|
||||
imageName = null
|
||||
}
|
||||
|
||||
const zipUrl = `${settings.apis.v1.url}/api/v1/overleaf/templates/${templateVersionId}`
|
||||
const zipUrl = `${settings.apis.filestore.url}/template/${templateId}/v/${templateVersionId}/zip`
|
||||
const zipReq = await fetchStreamWithResponse(zipUrl, {
|
||||
basicAuth: {
|
||||
user: settings.apis.v1.user,
|
||||
password: settings.apis.v1.pass,
|
||||
},
|
||||
signal: AbortSignal.timeout(settings.apis.v1.timeout),
|
||||
signal: AbortSignal.timeout(TIMEOUT),
|
||||
})
|
||||
|
||||
const projectName = ProjectDetailsHandler.fixProjectName(templateName)
|
||||
const dumpPath = `${settings.path.dumpFolder}/${crypto.randomUUID()}_templates-manager`
|
||||
const writeStream = fs.createWriteStream(dumpPath)
|
||||
|
||||
try {
|
||||
const attributes = {
|
||||
fromV1TemplateId: templateId,
|
||||
fromV1TemplateVersionId: templateVersionId,
|
||||
compiler,
|
||||
imageName,
|
||||
spellCheckLanguage
|
||||
}
|
||||
if (brandVariationId) attributes.brandVariationId = brandVariationId
|
||||
|
||||
|
||||
@@ -419,7 +419,7 @@ export default async function (webRouter, privateApiRouter, publicApiRouter) {
|
||||
labsEnabled: Settings.labs && Settings.labs.enable,
|
||||
wikiEnabled: Settings.overleaf != null || Settings.proxyLearn,
|
||||
templatesEnabled:
|
||||
Settings.overleaf != null || Settings.templates?.user_id != null,
|
||||
Settings.overleaf != null || Boolean(Settings.templates),
|
||||
cioWriteKey: Settings.analytics?.cio?.writeKey,
|
||||
cioSiteId: Settings.analytics?.cio?.siteId,
|
||||
linkedInInsightsPartnerId: Settings.analytics?.linkedIn?.partnerId,
|
||||
|
||||
@@ -68,7 +68,7 @@ const Features = {
|
||||
case 'oauth':
|
||||
return Boolean(Settings.oauth)
|
||||
case 'templates-server-pro':
|
||||
return Boolean(Settings.templates?.user_id)
|
||||
return Boolean(Settings.templates)
|
||||
case 'affiliations':
|
||||
case 'analytics':
|
||||
return Boolean(_.get(Settings, ['apis', 'v1', 'url']))
|
||||
|
||||
@@ -120,6 +120,7 @@ export const db = {
|
||||
systemmessages: internalDb.collection('systemmessages'),
|
||||
tags: internalDb.collection('tags'),
|
||||
teamInvites: internalDb.collection('teamInvites'),
|
||||
templates: internalDb.collection('templates'),
|
||||
tokens: internalDb.collection('tokens'),
|
||||
userAuditLogEntries: internalDb.collection('userAuditLogEntries'),
|
||||
users: internalDb.collection('users'),
|
||||
|
||||
@@ -295,6 +295,8 @@ async function initialize(webRouter, privateApiRouter, publicApiRouter) {
|
||||
'/read-only/one-time-login'
|
||||
)
|
||||
|
||||
await Modules.applyRouter(webRouter, privateApiRouter, publicApiRouter)
|
||||
|
||||
webRouter.get('/logout', UserPagesController.logout)
|
||||
webRouter.post('/logout', UserController.logout)
|
||||
|
||||
@@ -319,6 +321,8 @@ async function initialize(webRouter, privateApiRouter, publicApiRouter) {
|
||||
TokenAccessRouter.apply(webRouter)
|
||||
HistoryRouter.apply(webRouter, privateApiRouter)
|
||||
|
||||
await Modules.applyRouter(webRouter, privateApiRouter, publicApiRouter)
|
||||
|
||||
if (Settings.enableSubscriptions) {
|
||||
webRouter.get(
|
||||
'/user/bonus',
|
||||
|
||||
@@ -152,6 +152,18 @@ nav.navbar.navbar-default.navbar-main.navbar-expand-lg(
|
||||
|
||||
// logged out
|
||||
if !getSessionUser()
|
||||
// templates link
|
||||
if settings.templates
|
||||
+nav-item
|
||||
+nav-link(
|
||||
href="/templates"
|
||||
event-tracking="menu-click"
|
||||
event-tracking-action="clicked"
|
||||
event-tracking-trigger="click"
|
||||
event-tracking-mb="true"
|
||||
event-segmentation={ page: currentUrl, item: 'templates', location: 'top-menu' }
|
||||
) #{translate('templates')}
|
||||
|
||||
// register link
|
||||
if hasFeature('registration-page')
|
||||
+nav-item.primary
|
||||
|
||||
@@ -29,8 +29,10 @@ block content
|
||||
input(type="hidden" name="templateVersionId" value=templateVersionId)
|
||||
input(type="hidden" name="templateName" value=name)
|
||||
input(type="hidden" name="compiler" value=compiler)
|
||||
input(type="hidden" name="imageName" value=imageName)
|
||||
if imageName
|
||||
input(type="hidden" name="imageName" value=imageName)
|
||||
input(type="hidden" name="mainFile" value=mainFile)
|
||||
input(type="hidden" name="language" value=language)
|
||||
if brandVariationId
|
||||
input(type="hidden" name="brandVariationId" value=brandVariationId)
|
||||
input(hidden type="submit")
|
||||
|
||||
@@ -1027,8 +1027,18 @@ module.exports = {
|
||||
importProjectFromGithubModalWrapper: [],
|
||||
importProjectFromGithubMenu: [],
|
||||
editorLeftMenuSync: [],
|
||||
editorLeftMenuManageTemplate: [],
|
||||
menubarExtraComponents: [],
|
||||
editorLeftMenuManageTemplate: [
|
||||
Path.resolve(
|
||||
__dirname,
|
||||
'../modules/template-gallery/frontend/js/features/template/components/actions-manage-template'
|
||||
),
|
||||
],
|
||||
menubarExtraComponents: [
|
||||
Path.resolve(
|
||||
__dirname,
|
||||
'../modules/template-gallery/frontend/js/features/template/components/menubar-manage-template'
|
||||
),
|
||||
],
|
||||
insertMenuSections: [],
|
||||
oauth2Server: [],
|
||||
managedGroupSubscriptionEnrollmentNotification: [],
|
||||
@@ -1091,6 +1101,7 @@ module.exports = {
|
||||
'authentication/ldap',
|
||||
'authentication/saml',
|
||||
'authentication/oidc',
|
||||
'template-gallery',
|
||||
],
|
||||
viewIncludes: {},
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
"about_to_delete_cert": "",
|
||||
"about_to_delete_projects": "",
|
||||
"about_to_delete_tag": "",
|
||||
"about_to_delete_template": "",
|
||||
"about_to_delete_the_following_project": "",
|
||||
"about_to_delete_the_following_projects": "",
|
||||
"about_to_delete_user_preamble": "",
|
||||
@@ -155,6 +156,7 @@
|
||||
"all_project_activity_description": "",
|
||||
"all_projects": "",
|
||||
"all_projects_will_be_transferred_immediately": "",
|
||||
"all_templates": "",
|
||||
"all_these_experiments_are_available_exclusively": "",
|
||||
"allocate_license": "",
|
||||
"allows_to_search_by_author_title_etc_possible_to_pull_results_directly_from_your_reference_manager_if_connected": "",
|
||||
@@ -201,6 +203,7 @@
|
||||
"at_most_x_libraries_can_be_selected_plural": "",
|
||||
"attach_image_or_pdf": "",
|
||||
"audit_logs": "",
|
||||
"author": "",
|
||||
"auto_close_brackets": "",
|
||||
"auto_compile": "",
|
||||
"auto_complete": "",
|
||||
@@ -275,6 +278,8 @@
|
||||
"captions": "",
|
||||
"capture": "",
|
||||
"careers": "",
|
||||
"categories": "",
|
||||
"category": "",
|
||||
"category_arrows": "",
|
||||
"category_greek": "",
|
||||
"category_misc": "",
|
||||
@@ -451,6 +456,7 @@
|
||||
"cut": "",
|
||||
"dark_mode_pdf_preview": "",
|
||||
"dark_themes": "",
|
||||
"date": "",
|
||||
"date_and_owner": "",
|
||||
"date_and_time": "",
|
||||
"dealing_with_errors": "",
|
||||
@@ -483,6 +489,7 @@
|
||||
"delete_sso_config": "",
|
||||
"delete_table": "",
|
||||
"delete_tag": "",
|
||||
"delete_template": "",
|
||||
"delete_token": "",
|
||||
"delete_user": "",
|
||||
"delete_your_account": "",
|
||||
@@ -618,6 +625,7 @@
|
||||
"edit_sso_configuration": "",
|
||||
"edit_tag": "",
|
||||
"edit_tag_name": "",
|
||||
"edit_template": "",
|
||||
"edit_your_custom_dictionary": "",
|
||||
"edited": "",
|
||||
"editing": "",
|
||||
@@ -1134,6 +1142,7 @@
|
||||
"last_name": "",
|
||||
"last_resort_trouble_shooting_guide": "",
|
||||
"last_suggested_fix": "",
|
||||
"last_updated": "",
|
||||
"last_updated_date_by_x": "",
|
||||
"last_used": "",
|
||||
"last_verification_attempt": "",
|
||||
@@ -1142,6 +1151,8 @@
|
||||
"latam_discount_modal_title": "",
|
||||
"latex_places_figures_according_to_a_special_algorithm": "",
|
||||
"latex_places_tables_according_to_a_special_algorithm": "",
|
||||
"latex_templates": "",
|
||||
"latex_templates_for_journal_articles": "",
|
||||
"layout_options": "",
|
||||
"learn_more": "",
|
||||
"learn_more_about": "",
|
||||
@@ -1394,6 +1405,7 @@
|
||||
"no_search_results": "",
|
||||
"no_selection_select_file": "",
|
||||
"no_symbols_found": "",
|
||||
"no_templates_found": "",
|
||||
"no_thanks_cancel_now": "",
|
||||
"no_trashed_projects": "",
|
||||
"no_trashed_references": "",
|
||||
@@ -1434,6 +1446,7 @@
|
||||
"only_project_owner_can_link_github": "",
|
||||
"open_action_menu": "",
|
||||
"open_advanced_reference_search": "",
|
||||
"open_as_template": "",
|
||||
"open_each_file_in_its_own_tab": "",
|
||||
"open_file": "",
|
||||
"open_files_in_tabs": "",
|
||||
@@ -1464,6 +1477,7 @@
|
||||
"overleaf_labs": "",
|
||||
"overleaf_learning_center": "",
|
||||
"overleaf_logo": "",
|
||||
"overleaf_template_gallery": "",
|
||||
"overleafs_functionality_meets_my_needs": "",
|
||||
"overview": "",
|
||||
"overwrite": "",
|
||||
@@ -1529,6 +1543,7 @@
|
||||
"please_ask_the_project_owner_to_upgrade_to_track_changes": "",
|
||||
"please_change_primary_to_remove": "",
|
||||
"please_compile_pdf_before_download": "",
|
||||
"please_compile_pdf_before_publish_as_template": "",
|
||||
"please_confirm_primary_email_or_edit": "",
|
||||
"please_confirm_secondary_email_or_edit": "",
|
||||
"please_confirm_your_email_before_making_it_default": "",
|
||||
@@ -1566,8 +1581,10 @@
|
||||
"presentation_mode": "",
|
||||
"press_shift_space_for_suggestions": "",
|
||||
"press_space_to_open_the_ai_assistant": "",
|
||||
"prev": "",
|
||||
"preview": "",
|
||||
"preview_editor_tabs": "",
|
||||
"previous": "",
|
||||
"previous_page": "",
|
||||
"previous_reference": "",
|
||||
"previous_suggestion": "",
|
||||
@@ -2162,6 +2179,7 @@
|
||||
"tell_the_project_owner_and_ask_them_to_upgrade": "",
|
||||
"template": "",
|
||||
"template_description": "",
|
||||
"template_gallery": "",
|
||||
"template_title_taken_from_project_title": "",
|
||||
"templates": "",
|
||||
"temporarily_hides_the_preview": "",
|
||||
@@ -2361,6 +2379,7 @@
|
||||
"try_again": "",
|
||||
"try_for_free": "",
|
||||
"try_now": "",
|
||||
"try_recompile_project": "",
|
||||
"try_recompile_project_or_troubleshoot": "",
|
||||
"try_relinking_provider": "",
|
||||
"try_to_compile_despite_errors": "",
|
||||
@@ -2521,6 +2540,7 @@
|
||||
"view_options": "",
|
||||
"view_payment_portal": "",
|
||||
"view_payment_portal_disclaimer": "",
|
||||
"view_pdf": "",
|
||||
"view_trash": "",
|
||||
"view_your_invoices": "",
|
||||
"viewer": "",
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { NavbarSessionUser } from '@/shared/components/types/navbar'
|
||||
import NavLinkItem from '@/shared/components/navbar/nav-link-item'
|
||||
import { AccountMenuItems } from './account-menu-items'
|
||||
import { useSendProjectListMB } from '@/features/project-list/components/project-list-events'
|
||||
import getMeta from '@/utils/meta'
|
||||
|
||||
export default function LoggedInItems({
|
||||
sessionUser,
|
||||
@@ -14,11 +15,18 @@ export default function LoggedInItems({
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const sendProjectListMB = useSendProjectListMB()
|
||||
const { templatesEnabled } = getMeta('ol-ExposedSettings')
|
||||
|
||||
return (
|
||||
<>
|
||||
<NavLinkItem href="/project" className="nav-item-projects">
|
||||
{t('projects')}
|
||||
</NavLinkItem>
|
||||
{templatesEnabled && (
|
||||
<NavLinkItem href="/templates" className="nav-item-templates">
|
||||
{t('templates')}
|
||||
</NavLinkItem>
|
||||
)}
|
||||
<NavDropdownMenu
|
||||
title={t('Account')}
|
||||
className="nav-item-account"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import NavLinkItem from '@/shared/components/navbar/nav-link-item'
|
||||
import { useSendProjectListMB } from '@/features/project-list/components/project-list-events'
|
||||
import getMeta from '@/utils/meta'
|
||||
|
||||
export default function LoggedOutItems({
|
||||
showSignUpLink,
|
||||
@@ -9,9 +10,15 @@ export default function LoggedOutItems({
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const sendMB = useSendProjectListMB()
|
||||
const { templatesEnabled } = getMeta('ol-ExposedSettings')
|
||||
|
||||
return (
|
||||
<>
|
||||
{templatesEnabled && (
|
||||
<NavLinkItem href="/templates" className="nav-item-templates">
|
||||
{t('templates')}
|
||||
</NavLinkItem>
|
||||
)}
|
||||
{showSignUpLink ? (
|
||||
<NavLinkItem
|
||||
href="/register"
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
} from '../../../types/project/dashboard/notification'
|
||||
import { Survey } from '../../../types/project/dashboard/survey'
|
||||
import { GetProjectsResponseBody } from '../../../types/project/dashboard/api'
|
||||
import { GetTemplatesResponseBody } from '../../../types/template/dashboard/api'
|
||||
import { Tag } from '../../../app/src/Features/Tags/types'
|
||||
import { Institution } from '../../../types/institution'
|
||||
import {
|
||||
@@ -256,6 +257,7 @@ export interface Meta {
|
||||
'ol-postCheckoutRedirect': string
|
||||
'ol-postUrl': string
|
||||
'ol-prefetchedProjectsBlob': GetProjectsResponseBody | undefined
|
||||
'ol-prefetchedTemplatesBlob': GetTemplatesResponseBody | undefined
|
||||
'ol-preventCompileOnLoad'?: boolean
|
||||
'ol-primaryEmail': { email: string; confirmed: boolean }
|
||||
'ol-project': any // TODO
|
||||
|
||||
@@ -9,5 +9,6 @@
|
||||
i {
|
||||
margin-right: var(--spacing-02);
|
||||
padding-bottom: 3px;
|
||||
vertical-align: middle;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,6 +25,37 @@
|
||||
}
|
||||
|
||||
.gallery {
|
||||
padding-top: calc($header-height + var(--spacing-10)) !important;
|
||||
|
||||
.gallery-search-form-control {
|
||||
padding-top: 0px;
|
||||
padding-bottom: 0px;
|
||||
}
|
||||
|
||||
.gallery-header-sort-btn {
|
||||
font-size: var(--font-size-02);
|
||||
border: 0;
|
||||
text-align: left;
|
||||
color: var(--neutral-90);
|
||||
background-color: transparent;
|
||||
padding: 0;
|
||||
font-weight: bold;
|
||||
max-width: 100%;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
text-decoration: none;
|
||||
|
||||
&:hover {
|
||||
color: var(--neutral-90);
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.material-symbols {
|
||||
vertical-align: top;
|
||||
font-size: var(--font-size-05);
|
||||
}
|
||||
}
|
||||
|
||||
.gallery-tagged-tags-container-spacing {
|
||||
padding: 0 var(--spacing-09);
|
||||
margin-bottom: var(--spacing-16);
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
"about_to_delete_cert": "Du bist dabei, das folgende Zertifikat zu löschen:",
|
||||
"about_to_delete_projects": "Du bist dabei, die folgenden Projekte zu löschen:",
|
||||
"about_to_delete_tag": "Du bist dabei, das folgende Stichwort zu löschen (darin enthaltene Projekte werden nicht gelöscht):",
|
||||
"about_to_delete_template": "Du bist dabei, die folgende Vorlage zu löschen:",
|
||||
"about_to_delete_the_following_project": "Du bist dabei, das folgende Projekt zu löschen",
|
||||
"about_to_delete_the_following_projects": "Du bist dabei, die folgenden Projekte zu löschen",
|
||||
"about_to_delete_user_preamble": "Du bist dabei, __userName__ (__userEmail__) zu löschen. Das bedeutet:",
|
||||
@@ -259,6 +260,7 @@
|
||||
"cant_see_what_youre_looking_for_question": "Du kannst nicht finden, wonach du suchst?",
|
||||
"careers": "Karriere",
|
||||
"categories": "Kategorien",
|
||||
"category": "Kategorie",
|
||||
"category_arrows": "Pfeile",
|
||||
"category_greek": "Griechisch",
|
||||
"category_misc": "Sonstiges",
|
||||
@@ -414,6 +416,7 @@
|
||||
"delete_figure": "Abbildung löschen",
|
||||
"delete_projects": "Projekte löschen",
|
||||
"delete_tag": "Stichwort löschen",
|
||||
"delete_template": "Vorlage löschen",
|
||||
"delete_token": "Token löschen",
|
||||
"delete_user": "Nutzer löschen",
|
||||
"delete_your_account": "Lösche dein Konto",
|
||||
@@ -433,6 +436,7 @@
|
||||
"do_not_have_acct_or_do_not_want_to_link": "Wenn du kein <b>__appName__</b>-Konto hast oder nicht mit deinem <b>__institutionName__</b>-Konto verknüpfen möchtest, klicke auf <b>„__clickText__“</b>.",
|
||||
"do_not_link_accounts": "Konten nicht verknüpfen",
|
||||
"do_you_want_to_change_your_primary_email_address_to": "Willst Du deine primäre E-Mail-Adresse in <b>__email__</b> ändern?",
|
||||
"do_you_want_to_overwrite_it": "Möchtest du es überschreiben?",
|
||||
"do_you_want_to_overwrite_them": "Willst Du sie überschreiben?",
|
||||
"documentation": "Dokumentation",
|
||||
"does_not_contain_or_significantly_match_your_email": "nicht mit Teilen deiner E-Mail-Adresse übereinstimmt",
|
||||
@@ -483,6 +487,7 @@
|
||||
"edit_figure": "Abbildung bearbeiten",
|
||||
"edit_tag": "Stichwort bearbeiten",
|
||||
"edit_tag_name": "Stichwortname bearbeiten",
|
||||
"edit_template": "Vorlage bearbeiten",
|
||||
"edit_your_custom_dictionary": "Bearbeite dein benutzerdefiniertes Wörterbuch",
|
||||
"editing": "Bearbeitung",
|
||||
"editing_captions": "Beschriftungen bearbeiten",
|
||||
@@ -545,6 +550,7 @@
|
||||
"explore_plans": "Abonnements erkunden",
|
||||
"export_csv": "CSV-Datei exportieren",
|
||||
"export_project_to_github": "Projekt nach GitHub exportieren",
|
||||
"failed_to_publish_as_a_template": "Veröffentlichung als Vorlage fehlgeschlagen.",
|
||||
"failed_to_send_managed_user_invite_to_email": "Der Versand der Einladung für Verwaltete Benutzer an <0>__email__</0> hat nicht funktioniert. Bitte versuche es später noch einmal.",
|
||||
"faq_how_does_free_trial_works_answer": "Während deines __len__-tägigen Probe-Abonnements erhältst du vollen Zugriff auf die Funktionen des von dir gewählten __appName__-Abonnements. Es besteht keine Verpflichtung, über die Testperiode hinaus fortzufahren. Deine Karte wird am Ende des __len__-tägigen Testzeitraums belastet, sofern du nicht vorher gekündigt hast. Um zu kündigen, gehe zu deinen Abonnementeinstellungen in deinem Konto.",
|
||||
"fast": "Schnell",
|
||||
@@ -1126,6 +1132,7 @@
|
||||
"no_search_results": "Keine Suchergebnisse",
|
||||
"no_selection_select_file": "Derzeit ist keine Datei ausgewählt. Bitte wähle eine Datei aus dem Dateibaum aus.",
|
||||
"no_symbols_found": "Keine Symbole gefunden",
|
||||
"no_templates_found": "Keine Vorlagen gefunden.",
|
||||
"no_thanks_cancel_now": "Nein danke, ich möchte trotzdem kündigen",
|
||||
"no_update_email": "Nein, E-Mail-Adresse aktualisieren",
|
||||
"non_blinking_cursor": "Nicht blinkender Cursor",
|
||||
@@ -1227,6 +1234,8 @@
|
||||
"please_ask_the_project_owner_to_upgrade_to_track_changes": "Bitte den Projekteigentümer um ein Upgrade, um Änderungen verfolgen zu können",
|
||||
"please_change_primary_to_remove": "Bitte ändere deine primäre E-Mail-Adresse, um sie zu entfernen",
|
||||
"please_compile_pdf_before_download": "Bitte kompiliere dein Projekt, bevor du das PDF herunterlädst",
|
||||
"please_compile_pdf_before_publish_as_template": "Bitte kompiliere dein Projekt, bevor du es als Vorlage veröffentlichst.",
|
||||
"please_compile_pdf_before_word_count": "Bitte kompiliere dein Projekt, bevor du eine Wortzählung durchführst.",
|
||||
"please_confirm_email": "Bitte bestätige deine E-Mail-Adresse __emailAddress__, indem du auf den Link in der Bestätigungs-E-Mail klickst",
|
||||
"please_confirm_primary_email_or_edit": "Bitte bestätige deine primäre E-Mail-Adresse __emailAddress__. Um sie zu bearbeiten, gehe zu <0>Kontoeinstellungen</0>.",
|
||||
"please_confirm_secondary_email_or_edit": "Bitte bestätige deine sekundäre E-Mail-Adresse __emailAddress__. Um sie zu bearbeiten, gehe zu <0>Kontoeinstellungen</0>.",
|
||||
@@ -1558,6 +1567,7 @@
|
||||
"template_not_found_description": "Diese Methode zum Erstellen von Projekten aus Vorlagen wurde entfernt. Besuche unsere Vorlagengalerie, um weitere Vorlagen zu finden.",
|
||||
"template_title_taken_from_project_title": "Der Vorlagentitel wird automatisch aus dem Projekttitel übernommen",
|
||||
"template_top_pick_by_overleaf": "Diese Vorlage wurde von Overleaf-Mitarbeitern aufgrund ihrer hohen Qualität ausgewählt",
|
||||
"template_with_this_title_exists_and_owned_by_x": "Eine Vorlage mit diesem Namen existiert bereits, und der Besitzer ist: __x__.",
|
||||
"templates": "Vorlagen",
|
||||
"templates_admin_source_project": "Administration: Quellprojekt",
|
||||
"templates_page_title": "Vorlagen - Zeitschriften, Lebensläufe, Präsentationen, Berichte und mehr",
|
||||
@@ -1640,6 +1650,7 @@
|
||||
"try_again": "Bitte versuche es erneut",
|
||||
"try_for_free": "Kostenlos testen",
|
||||
"try_now": "Jetzt versuchen",
|
||||
"try_recompile_project": "Versuche bitte, das Projekt von Grund auf neu zu kompilieren.",
|
||||
"try_recompile_project_or_troubleshoot": "Versuche bitte, das Projekt von Grund auf neu zu kompilieren. Wenn das Problem weiterhin besteht, findest Du im <0>Troubleshooting Guide</0> weitere Hilfe",
|
||||
"try_to_compile_despite_errors": "Versuche, trotz Fehler zu kompilieren",
|
||||
"turn_off": "Deaktivieren",
|
||||
@@ -1655,6 +1666,7 @@
|
||||
"understand_managed_user_accounts": "Verwaltete Konten verstehen",
|
||||
"unfold_line": "Zeile ausklappen",
|
||||
"university": "Universität",
|
||||
"unknown": "Unbekannt",
|
||||
"unlimited": "Unbegrenzt",
|
||||
"unlimited_collaborators_per_project": "Unbeschränkt viele Mitarbeiter pro Projekt",
|
||||
"unlimited_collabs": "Unbeschränkt viele Mitarbeiter",
|
||||
@@ -1779,6 +1791,7 @@
|
||||
"you_can_opt_in_and_out_of_the_program_at_any_time_on_this_page": "Du kannst dich jederzeit auf dieser Seite für das Beta-Programm an- und abmelden",
|
||||
"you_can_still_use_your_premium_features": "Du kannst deine Premiumfunktionen weiterhin nutzen, bis die Pause aktiv wird.",
|
||||
"you_cant_add_or_change_password_due_to_sso": "Du kannst dein Passwort nicht hinzufügen oder ändern, da deine Gruppe oder Organisation <0>Single Sign-On (SSO)</0> verwendet.",
|
||||
"you_cant_overwrite_it": "Überschreiben ist nicht möglich.",
|
||||
"you_dont_have_any_repositories": "Du hast keine Repositories",
|
||||
"you_have_added_x_of_group_size_y": "Du hast <0>__addedUsersSize__</0> von <1>__groupSize__</1> verfügbaren Mitgliedern hinzugefügt",
|
||||
"you_unpaused_your_subscription": "Du hast dein Abonnement fortgesetzt.",
|
||||
|
||||
@@ -29,6 +29,7 @@
|
||||
"about_to_delete_cert": "You are about to delete the following certificate:",
|
||||
"about_to_delete_projects": "You are about to delete the following projects:",
|
||||
"about_to_delete_tag": "You are about to delete the following tag (any projects in them will not be deleted):",
|
||||
"about_to_delete_template": "You are about to delete the following template:",
|
||||
"about_to_delete_the_following_project": "You are about to delete the following project",
|
||||
"about_to_delete_the_following_projects": "You are about to delete the following projects",
|
||||
"about_to_delete_user_preamble": "You’re about to delete __userName__ (__userEmail__). Doing this will mean:",
|
||||
@@ -352,6 +353,7 @@
|
||||
"capture": "Capture",
|
||||
"careers": "Careers",
|
||||
"categories": "Categories",
|
||||
"category": "Category",
|
||||
"category_arrows": "Arrows",
|
||||
"category_greek": "Greek",
|
||||
"category_misc": "Misc",
|
||||
@@ -623,6 +625,7 @@
|
||||
"delete_sso_config": "Delete SSO configuration",
|
||||
"delete_table": "Delete table",
|
||||
"delete_tag": "Delete Tag",
|
||||
"delete_template": "Delete template",
|
||||
"delete_token": "Delete token",
|
||||
"delete_user": "Delete user",
|
||||
"delete_your_account": "Delete your account",
|
||||
@@ -781,6 +784,7 @@
|
||||
"edit_sso_configuration": "Edit SSO Configuration",
|
||||
"edit_tag": "Edit tag",
|
||||
"edit_tag_name": "Edit tag name",
|
||||
"edit_template": "Edit template",
|
||||
"edit_your_custom_dictionary": "Edit your custom dictionary",
|
||||
"editing": "Editing",
|
||||
"editing_and_collaboration": "Editing and collaboration",
|
||||
@@ -903,6 +907,7 @@
|
||||
"export_project_to_github": "Export Project to GitHub",
|
||||
"failed": "Failed",
|
||||
"failed_to_consent_to_workbench_terms": "Failed to consent to workbench terms. Please try again later.",
|
||||
"failed_to_publish_as_a_template": "Failed to publish as a template.",
|
||||
"failed_to_send_group_invite_to_email": "Failed to send group invite to <0>__email__</0>. Please try again later.",
|
||||
"failed_to_send_managed_user_invite_to_email": "Failed to send Managed User invite to <0>__email__</0>. Please try again later.",
|
||||
"failed_to_send_sso_link_invite_to_email": "Failed to send SSO invite reminder to <0>__email__</0>. Please try again later.",
|
||||
@@ -1849,6 +1854,7 @@
|
||||
"no_search_results": "No Search Results",
|
||||
"no_selection_select_file": "Currently, no file is selected. Please select a file from the file tree.",
|
||||
"no_symbols_found": "No symbols found",
|
||||
"no_templates_found": "No templates found.",
|
||||
"no_thanks_cancel_now": "No thanks, I still want to cancel",
|
||||
"no_trashed_projects": "No trashed projects",
|
||||
"no_trashed_references": "No references in Trash",
|
||||
@@ -1959,7 +1965,7 @@
|
||||
"overleaf_learning_center": "Overleaf learning center",
|
||||
"overleaf_logo": "Overleaf logo",
|
||||
"overleaf_multi_license_plans": "Overleaf multi-license plans",
|
||||
"overleaf_template_gallery": "overleaf template gallery",
|
||||
"overleaf_template_gallery": "overleaf ce+ template gallery",
|
||||
"overleafs_functionality_meets_my_needs": "Overleaf’s functionality meets my needs.",
|
||||
"overview": "Overview",
|
||||
"overwrite": "Overwrite",
|
||||
@@ -2051,6 +2057,7 @@
|
||||
"please_ask_the_project_owner_to_upgrade_to_track_changes": "Please ask the project owner to upgrade to use track changes",
|
||||
"please_change_primary_to_remove": "Please change your primary email in order to remove",
|
||||
"please_compile_pdf_before_download": "Please compile your project before downloading the PDF",
|
||||
"please_compile_pdf_before_publish_as_template": "Please compile your project before publishing it as a template",
|
||||
"please_confirm_email": "Please confirm your email __emailAddress__ by clicking on the link in the confirmation email ",
|
||||
"please_confirm_primary_email_or_edit": "Please confirm your primary email address __emailAddress__. To edit it, go to <0>Account settings</0>.",
|
||||
"please_confirm_secondary_email_or_edit": "Please confirm your secondary email address __emailAddress__. To edit it, go to <0>Account settings</0>.",
|
||||
@@ -2097,6 +2104,7 @@
|
||||
"presentations": "Presentations",
|
||||
"press_shift_space_for_suggestions": "Press Shift+Space for suggestions",
|
||||
"press_space_to_open_the_ai_assistant": "Press Space to open the AI assistant",
|
||||
"prev": "Prev",
|
||||
"preview": "Preview",
|
||||
"preview_editor_tabs": "Preview editor tabs",
|
||||
"previous_24_hours_only": "previous 24 hours only",
|
||||
@@ -2184,7 +2192,7 @@
|
||||
"pt": "Portuguese",
|
||||
"public": "Public",
|
||||
"publish": "Publish",
|
||||
"publish_as_template": "Manage Template",
|
||||
"publish_as_template": "Publish as a Template",
|
||||
"publisher_account": "Publisher Account",
|
||||
"publishing": "Publishing",
|
||||
"pull_github_changes_into_sharelatex": "Pull GitHub changes into __appName__",
|
||||
@@ -2815,6 +2823,7 @@
|
||||
"template_not_found_description": "This way of creating projects from templates has been removed. Please visit our template gallery to find more templates.",
|
||||
"template_title_taken_from_project_title": "The template title will be taken automatically from the project title",
|
||||
"template_top_pick_by_overleaf": "This template was hand-picked by Overleaf staff for its high quality",
|
||||
"template_with_this_title_exists_and_owned_by_x": "A template with this title already exists and is owned by __x__.",
|
||||
"templates": "Templates",
|
||||
"templates_admin_source_project": "Admin: Source Project",
|
||||
"templates_admin_v1_link": "Admin: V1 Published Version",
|
||||
@@ -3042,6 +3051,7 @@
|
||||
"try_for_free": "Try for free",
|
||||
"try_for_free_instead": "Try for free instead",
|
||||
"try_now": "Try Now",
|
||||
"try_recompile_project": "Please try recompiling the project from scratch.",
|
||||
"try_recompile_project_or_troubleshoot": "Please try recompiling the project from scratch, and if that doesn’t help, follow our <0>troubleshooting guide</0>.",
|
||||
"try_relinking_provider": "It looks like you need to re-link your __provider__ account.",
|
||||
"try_to_compile_despite_errors": "Try to compile despite errors",
|
||||
@@ -3345,6 +3355,7 @@
|
||||
"you_cant_add_or_change_password_due_to_ldap_or_sso": "You can’t add or change your password because your group or organization uses LDAP or SSO.",
|
||||
"you_cant_add_or_change_password_due_to_sso": "You can’t add or change your password because your group or organization uses <0>single sign-on (SSO)</0>.",
|
||||
"you_cant_join_this_group_subscription": "You can’t join this group subscription",
|
||||
"you_cant_overwrite_it": "You can’t overwrite it.",
|
||||
"you_cant_reset_password_due_to_ldap_or_sso": "You can’t reset your password because your group or organization uses LDAP or SSO. Contact your system administrator.",
|
||||
"you_cant_reset_password_due_to_sso": "You can’t reset your password because your group or organization uses SSO. <0>Log in with SSO</0>.",
|
||||
"you_currently_have_x_linked_with_your_overleaf_account": "You currently have <0>__managers__</0> linked with your __appName__ account.",
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
"about_to_archive_projects": "Вы собираетесь архивировать следующие проекты:",
|
||||
"about_to_delete_cert": "Вы собираетесь удалить следующий сертификат:",
|
||||
"about_to_delete_projects": "Следующие проекты будут удалены:",
|
||||
"about_to_delete_template": "Следующий шаблон будет удален:",
|
||||
"about_to_delete_the_following_project": "Вы собираетесь удалить следующий проект:",
|
||||
"about_to_delete_the_following_projects": "Вы собираетесь удалить следующие проекты:",
|
||||
"about_to_leave_project": "Вы собираетесь покинуть этот проект:",
|
||||
@@ -91,6 +92,7 @@
|
||||
"cancelling_will_end_your_subscription_on": "После отмены Ваша подписка завершится __terminationDate__.",
|
||||
"cant_find_email": "Извините, данный адрес не зарегистрирован.",
|
||||
"cant_find_page": "К сожалению, страница не найдена",
|
||||
"category": "Категория",
|
||||
"change": "Изменить",
|
||||
"change_password": "Изменение пароля",
|
||||
"change_plan": "Сменить тарифный план",
|
||||
@@ -156,10 +158,12 @@
|
||||
"delete_account_warning_message_3": "Вы собираетесь <strong>удалить все данные Вашего аккаунта</strong>, включая все Ваши проекты и настройки. Пожалуйста, введите адрес электронной почты и пароль Вашего аккаунта в форму внизу для продолжения.",
|
||||
"delete_and_leave_projects": "Удалить или оставить проекты",
|
||||
"delete_projects": "Удалить проекты",
|
||||
"delete_template": "Удалить шаблон",
|
||||
"delete_your_account": "Удалить аккаунт",
|
||||
"deleting": "Удаление",
|
||||
"disconnected": "Разъединен",
|
||||
"discover_latex": "Узнать о LaTeX",
|
||||
"do_you_want_to_overwrite_it": "Перезаписать?",
|
||||
"documentation": "Документация",
|
||||
"doesnt_match": "Не совпадает",
|
||||
"done": "Готово",
|
||||
@@ -171,6 +175,7 @@
|
||||
"dropbox_sync": "Синхронизация с Dropbox",
|
||||
"dropbox_sync_description": "Синхронизируйте Ваши __appName__ проекты с Вашим Dropbox. Изменения в __appName__ автоматически сохраняются в Вашем Dropbox, и наоборот.",
|
||||
"each_user_will_have_access_to": "Каждому пользователю будут доступны",
|
||||
"edit_template": "Редактировать шаблон",
|
||||
"editing": "Редактор",
|
||||
"educational_discount_tooltip": "Доступно для групп из высших учебных заведений.",
|
||||
"educational_percent_discount_applied": "Применена образовательная скидка __percent__%!",
|
||||
@@ -189,6 +194,7 @@
|
||||
"explore_features": "Посмотреть функции",
|
||||
"explore_plans": "Посмотреть тарифы",
|
||||
"export_project_to_github": "Экспорт проекта на GitHub",
|
||||
"failed_to_publish_as_a_template": "Не удалось создать шаблон.",
|
||||
"fast": "быстрый",
|
||||
"feature_controls": "Управление функциями",
|
||||
"feature_settings_subtext": "Просмотр и управление функциями, доступными участникам Вашей группы",
|
||||
@@ -427,6 +433,7 @@
|
||||
"no_preview_available": "К сожалению, предпросмотр не доступен",
|
||||
"no_projects": "Нет проектов",
|
||||
"no_search_results": "Ничего не найдено",
|
||||
"no_templates_found": "Шаблоны не найдены.",
|
||||
"no_thanks_cancel_now": "Нет, спасибо, я всё равно хочу отменить подписку",
|
||||
"normal": "нормальный",
|
||||
"not_now": "Не сейчас",
|
||||
@@ -470,6 +477,7 @@
|
||||
"planned_maintenance": "Плановые работы",
|
||||
"plans_and_pricing": "Тарифные планы",
|
||||
"please_compile_pdf_before_download": "Пожалуйста, скомпилируйте проект перед загрузкой PDF",
|
||||
"please_compile_pdf_before_publish_as_template": "Пожалуйста, скомпилируйте проект, прежде чем создавать из него шаблон",
|
||||
"please_contact_support_to_makes_change_to_your_plan": "Чтобы изменить тариф, <0>обратитесь в поддержку</0>",
|
||||
"please_enter_email": "Пожалуйста, введите адрес электронной почты",
|
||||
"please_get_in_touch": "Пожалуйста, свяжитесь с нами",
|
||||
@@ -612,6 +620,7 @@
|
||||
"talk_to_sales": "Связаться с отделом продаж",
|
||||
"taxes_may_be_added": "В зависимости от Вашего платёжного адреса могут быть добавлены налоги.",
|
||||
"template_description": "Описание шаблона",
|
||||
"template_with_this_title_exists_and_owned_by_x": "Уже есть шаблон с таким названием, его владелец __x__.",
|
||||
"templates": "Шаблоны",
|
||||
"ten_collaborators_per_project": "10 соавторов на проект",
|
||||
"terminated": "Компиляция отменена",
|
||||
@@ -641,7 +650,9 @@
|
||||
"track_changes": "Отслеживание изменений",
|
||||
"try_again": "Пожалуйста, попробуйте снова",
|
||||
"try_now": "Попробуйте",
|
||||
"try_recompile_project": "Попробуйте скомпилировать проект заново.",
|
||||
"university": "Университет",
|
||||
"unknown": "Неизвестный",
|
||||
"unlimited_collaborators_per_project": "Неограниченное число соавторов на проект",
|
||||
"unlimited_collabs": "Неограниченное число соавторов",
|
||||
"unlimited_projects": "Неограниченное число проектов",
|
||||
@@ -685,6 +696,7 @@
|
||||
"view_metrics_group_subtext": "Отслеживание и скачивание метрик использования групповой подписки",
|
||||
"view_payment_portal": "Счета и платёжные данные",
|
||||
"view_payment_portal_disclaimer": "У Вас могут быть счета, выставленные до февраля 2026 года. Если Вам нужен доступ к ним, <0>обратитесь в поддержку</0>.",
|
||||
"view_pdf": "Открыть PDF",
|
||||
"view_your_invoices": "Ваши счета",
|
||||
"want_change_to_apply_before_plan_end": "Если Вы хотите, чтобы это изменение вступило в силу до конца текущего расчётного периода, свяжитесь с нами.",
|
||||
"wed_love_you_to_stay": "Мы будем рады, если Вы останетесь",
|
||||
@@ -697,6 +709,7 @@
|
||||
"x_price_per_year": "__price__ в год",
|
||||
"year": "год",
|
||||
"yes_move_me_to_personal_plan": "Да, перевести меня на тариф Personal",
|
||||
"you": "Вы",
|
||||
"you_already_have_a_subscription": "У Вас уже есть подписка",
|
||||
"you_are_a_manager_and_member_of_x_plan_as_member_of_group_subscription_y_administered_by_z": "Вы <1>менеджер</1> и <1>участник</1> групповой подписки <0>__planName__</0> <1>__groupName__</1>, администратор — <1>__adminEmail__</1>.",
|
||||
"you_are_a_manager_and_member_of_x_plan_as_member_of_group_subscription_y_administered_by_z_you": "Вы <1>менеджер</1> и <1>участник</1> групповой подписки <0>__planName__</0> <1>__groupName__</1>, администратор — <1>Вы (__adminEmail__)</1>.",
|
||||
@@ -709,6 +722,7 @@
|
||||
"you_are_on_x_plan_as_member_of_group_subscription_y_administered_by_z": "Вы пользуетесь тарифом <0>__planName__</0> как <1>участник</1> групповой подписки <1>__groupName__</1>, администратор — <1>__adminEmail__</1>",
|
||||
"you_are_using_our_free_plan": "Вы пользуетесь бесплатным тарифом. Смените тариф, чтобы получить максимум от Overleaf",
|
||||
"you_can_still_use_your_premium_features": "Вы сможете пользоваться премиум-функциями до того, как приостановка вступит в силу.",
|
||||
"you_cant_overwrite_it": "Перезаписать нельзя.",
|
||||
"you_have_added_x_of_group_size_y": "Вы добавили <0>__addedUsersSize__</0> из <1>__groupSize__</1> доступных участников",
|
||||
"you_unpaused_your_subscription": "Вы возобновили подписку.",
|
||||
"youll_be_moved_to_the_free_plan": "Вы будете переведены на бесплатный тариф",
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import sanitizeHtml from 'sanitize-html'
|
||||
|
||||
const sanitizeOptions = {
|
||||
linksOnly: {
|
||||
allowedTags: ["a"],
|
||||
allowedAttributes: { "a": ["href"] }
|
||||
},
|
||||
reachText: {
|
||||
allowedTags: ["h1", "h2", "h3", "h4", "h5", "h6",
|
||||
"p", "blockquote", "ul", "ol", "li",
|
||||
"em", "strong", "s", "code", "pre", "hr", "a"],
|
||||
allowedAttributes: { "a": ["href"] }
|
||||
},
|
||||
plainText: {
|
||||
allowedTags: [],
|
||||
allowedAttributes: {},
|
||||
},
|
||||
}
|
||||
|
||||
export function cleanHtml(text, sanitizeType) {
|
||||
return sanitizeHtml(text, sanitizeOptions[sanitizeType])
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import Settings from '@overleaf/settings'
|
||||
import AdminAuthorizationHelper from '../../../../app/src/Features/Helpers/AdminAuthorizationHelper.mjs'
|
||||
const { hasAdminAccess } = AdminAuthorizationHelper
|
||||
import HttpErrorHandler from '../../../../app/src/Features/Errors/HttpErrorHandler.mjs'
|
||||
import SessionManager from '../../../../app/src/Features/Authentication/SessionManager.mjs'
|
||||
import { Template } from './models/Template.mjs'
|
||||
|
||||
async function ensureTemplateManagementAccess(req, res, next) {
|
||||
const user = SessionManager.getSessionUser(req.session)
|
||||
const userId = SessionManager.getLoggedInUserId(req.session)
|
||||
|
||||
const isPrivileged =
|
||||
hasAdminAccess(user) ||
|
||||
Settings.templates?.user_id === userId
|
||||
|
||||
if (isPrivileged) return next()
|
||||
|
||||
const templateId = req.params?.template_id
|
||||
|
||||
if (!templateId) {
|
||||
if (Settings.templates?.nonAdminCanManage) return next()
|
||||
return HttpErrorHandler.forbidden(req, res)
|
||||
}
|
||||
|
||||
// unprivileged owner is allowed to edit/delete own template
|
||||
// even non-admin is not allowed to manage templates
|
||||
const template = await Template.findById(templateId)
|
||||
.select('owner')
|
||||
.lean()
|
||||
|
||||
if (template?.owner?.toString() === userId) return next()
|
||||
|
||||
return HttpErrorHandler.forbidden(req, res)
|
||||
}
|
||||
|
||||
export default {
|
||||
ensureTemplateManagementAccess,
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import OError from '@overleaf/o-error'
|
||||
|
||||
export class TemplateNameConflictError extends OError {
|
||||
constructor(ownerId, message = 'template_with_this_title_exists_and_owned_by_x') {
|
||||
super(message, { ownerId })
|
||||
}
|
||||
}
|
||||
|
||||
export class RecompileRequiredError extends OError {
|
||||
constructor(message = 'Recompile required') {
|
||||
super(message, { status: 400 })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import Path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import logger from '@overleaf/logger'
|
||||
import ErrorController from '../../../../app/src/Features/Errors/ErrorController.js'
|
||||
import Errors from '../../../../app/src/Features/Errors/Errors.js'
|
||||
import SessionManager from '../../../../app/src/Features/Authentication/SessionManager.mjs'
|
||||
import TemplateGalleryManager from'./TemplateGalleryManager.mjs'
|
||||
import { getUserName } from './TemplateGalleryHelper.mjs'
|
||||
import { TemplateNameConflictError, RecompileRequiredError } from './TemplateErrors.mjs'
|
||||
import Settings from '@overleaf/settings'
|
||||
|
||||
const __dirname = Path.dirname(fileURLToPath(import.meta.url))
|
||||
|
||||
async function createTemplateFromProject(req, res, next) {
|
||||
const t = req.i18n.translate
|
||||
try {
|
||||
const userId = SessionManager.getLoggedInUserId(req.session)
|
||||
const result = await TemplateGalleryManager.createTemplateFromProject({
|
||||
projectId: req.params.Project_id,
|
||||
userId,
|
||||
templateSource: req.body,
|
||||
})
|
||||
if (result.conflict) {
|
||||
const ownerName = (result.templateOwnerName === 'you') ? t('you') : result.templateOwnerName
|
||||
const message = `${t('template_with_this_title_exists_and_owned_by_x', { x: ownerName })} `
|
||||
+ t(result.canOverride ? 'do_you_want_to_overwrite_it' : 'you_cant_overwrite_it')
|
||||
return res.status(409).json({ canOverride: result.canOverride, message })
|
||||
}
|
||||
return res.status(200).json({ template_id: result.templateId })
|
||||
} catch (error) {
|
||||
if (error instanceof Errors.InvalidNameError) {
|
||||
return res.status(error.info?.status || 400).json({ message: error.message })
|
||||
}
|
||||
|
||||
const mainMessage = t('failed_to_publish_as_a_template')
|
||||
if (error instanceof RecompileRequiredError) {
|
||||
return res.status(error.info?.status || 400).json({
|
||||
message: `${mainMessage} ${t('try_recompile_project')}`
|
||||
})
|
||||
}
|
||||
return res.status(400).json({ message: mainMessage })
|
||||
}
|
||||
}
|
||||
|
||||
async function editTemplate(req, res, next) {
|
||||
const t = req.i18n.translate
|
||||
try {
|
||||
const result = await TemplateGalleryManager.editTemplate({
|
||||
templateId: req.params.template_id,
|
||||
updates: req.body
|
||||
})
|
||||
res.status(200).json(result)
|
||||
} catch (error) {
|
||||
if (error instanceof TemplateNameConflictError) {
|
||||
const ownerId = error.info?.ownerId
|
||||
const userId = SessionManager.getLoggedInUserId(req.session)
|
||||
const ownerName = (ownerId === userId)
|
||||
? t('you')
|
||||
: await getUserName(ownerId) || t('unknown')
|
||||
const message = t(error.message, { x: ownerName })
|
||||
return res.status(409).json({ message })
|
||||
}
|
||||
if (error instanceof Errors.InvalidNameError) {
|
||||
return res.status(error.info?.status || 400).json({ message: error.message })
|
||||
}
|
||||
logger.error({ error }, 'Failure saving template')
|
||||
return res.status(500).json({ message: t('something_went_wrong_server') })
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteTemplate(req, res, next) {
|
||||
const t = req.i18n.translate
|
||||
try {
|
||||
await TemplateGalleryManager.deleteTemplate({
|
||||
templateId: req.params.template_id,
|
||||
version: req.body.version
|
||||
})
|
||||
res.sendStatus(200)
|
||||
} catch (error) {
|
||||
logger.error({ error }, 'Failure deleting template')
|
||||
return res.status(500).json({ message: t('something_went_wrong_server') })
|
||||
}
|
||||
}
|
||||
|
||||
async function getTemplatePreview(req, res, next) {
|
||||
try {
|
||||
const templateId = req.params.template_id
|
||||
const { version, style } = req.query
|
||||
|
||||
const { stream, contentType } = await TemplateGalleryManager.fetchTemplatePreview({ templateId, version, style })
|
||||
|
||||
res.setHeader('Content-Type', contentType)
|
||||
stream.pipe(res)
|
||||
} catch (error) {
|
||||
if (error.info?.status == 404) {
|
||||
return ErrorController.notFound(req, res, next)
|
||||
}
|
||||
return res.status(error.info?.status || 400).json(error.info)
|
||||
}
|
||||
}
|
||||
|
||||
async function templatesCategoryPage(req, res, next) {
|
||||
const t = req.i18n.translate
|
||||
try {
|
||||
let { category } = req.params
|
||||
const result = await TemplateGalleryManager.getTemplatesPageData(category)
|
||||
|
||||
let title
|
||||
if (result.categoryName) {
|
||||
title = t('latex_templates') + ' — ' + result.categoryName
|
||||
} else {
|
||||
category = null
|
||||
title = t('templates_page_title')
|
||||
}
|
||||
res.render(Path.resolve(__dirname, '../views/template_gallery/template-gallery'), {
|
||||
title,
|
||||
category,
|
||||
})
|
||||
} catch (error) {
|
||||
next(error)
|
||||
}
|
||||
}
|
||||
|
||||
async function templateDetailsPage(req, res, next) {
|
||||
const t = req.i18n.translate
|
||||
const userId = SessionManager.getLoggedInUserId(req.session)
|
||||
try {
|
||||
const template = await TemplateGalleryManager.getTemplate('_id', req.params.template_id)
|
||||
res.render(Path.resolve(__dirname, '../views/template_gallery/template'), {
|
||||
title: `${t('template')}: ${template.name}`,
|
||||
template: JSON.stringify(template),
|
||||
languages: Settings.languages,
|
||||
userIsTemplatesManager: Boolean(Settings.templates?.user_id && Settings.templates.user_id === userId)
|
||||
})
|
||||
} catch (error) {
|
||||
return ErrorController.notFound(req, res, next)
|
||||
}
|
||||
}
|
||||
|
||||
async function getTemplateJSON(req, res, next) {
|
||||
try {
|
||||
const { key, val } = req.query
|
||||
const template = await TemplateGalleryManager.getTemplate(key, val)
|
||||
res.json(template)
|
||||
} catch (error) {
|
||||
next(error)
|
||||
}
|
||||
}
|
||||
|
||||
async function getCategoryTemplatesJSON(req, res, next) {
|
||||
try {
|
||||
const result = await TemplateGalleryManager.getCategoryTemplates(req.query)
|
||||
res.json(result)
|
||||
} catch (error) {
|
||||
next(error)
|
||||
}
|
||||
}
|
||||
|
||||
export default {
|
||||
createTemplateFromProject,
|
||||
editTemplate,
|
||||
deleteTemplate,
|
||||
getTemplatePreview,
|
||||
templatesCategoryPage,
|
||||
templateDetailsPage,
|
||||
getTemplateJSON,
|
||||
getCategoryTemplatesJSON,
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
import { marked } from 'marked'
|
||||
import request from 'request'
|
||||
import logger from '@overleaf/logger'
|
||||
import settings from '@overleaf/settings'
|
||||
import Errors from '../../../../app/src/Features/Errors/Errors.js'
|
||||
import ProjectGetter from '../../../../app/src/Features/Project/ProjectGetter.mjs'
|
||||
import ProjectLocator from '../../../../app/src/Features/Project/ProjectLocator.mjs'
|
||||
import ProjectZipStreamManager from '../../../../app/src/Features/Downloads/ProjectZipStreamManager.mjs'
|
||||
import DocumentUpdaterHandler from '../../../../app/src/Features/DocumentUpdater/DocumentUpdaterHandler.mjs'
|
||||
import ClsiManager from '../../../../app/src/Features/Compile/ClsiManager.mjs'
|
||||
import UserGetter from '../../../../app/src/Features/User/UserGetter.mjs'
|
||||
import { fetchStreamWithResponse } from '@overleaf/fetch-utils'
|
||||
import { Template } from './models/Template.mjs'
|
||||
import { RecompileRequiredError } from './TemplateErrors.mjs'
|
||||
import { cleanHtml } from './CleanHtml.mjs'
|
||||
|
||||
const TIMEOUT = 30000
|
||||
|
||||
const MAX_PROJECT_NAME_LENGTH = 150
|
||||
const MAX_FORM_INPUT_LENGTH = 512
|
||||
const MAX_TEMPLATE_DESCRIPTION_LENGTH = 4096
|
||||
|
||||
// Configure marked for CommonMark-only parsing
|
||||
marked.setOptions({
|
||||
gfm: false,
|
||||
breaks: false,
|
||||
headerIds: false,
|
||||
mangle: false,
|
||||
})
|
||||
|
||||
marked.use({
|
||||
renderer: {
|
||||
html: () => '' // strips any HTML tags
|
||||
}
|
||||
})
|
||||
|
||||
function _createZipStreamForProjectAsync(projectId) {
|
||||
return new Promise((resolve, reject) => {
|
||||
ProjectZipStreamManager.createZipStreamForProject(projectId, false, null, (err, archive) => {
|
||||
if (err) {
|
||||
return reject(err)
|
||||
}
|
||||
archive.on('error', (err) => reject(err))
|
||||
resolve(archive)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
export function validateTemplateInput({ name, descriptionMD, authorMD, license }) {
|
||||
if (name?.length > MAX_PROJECT_NAME_LENGTH) {
|
||||
throw new Errors.InvalidNameError(`Template title exceeds the maximum length of ${MAX_PROJECT_NAME_LENGTH} characters.`)
|
||||
}
|
||||
if (descriptionMD?.length > MAX_TEMPLATE_DESCRIPTION_LENGTH) {
|
||||
throw new Errors.InvalidNameError(`Template description exceeds the maximum length of ${MAX_TEMPLATE_DESCRIPTION_LENGTH} characters.`)
|
||||
}
|
||||
if (authorMD?.length > MAX_FORM_INPUT_LENGTH) {
|
||||
throw new Errors.InvalidNameError('Author name is too long.')
|
||||
}
|
||||
if (license?.length > MAX_FORM_INPUT_LENGTH) {
|
||||
throw new Errors.InvalidNameError('License name is too long.')
|
||||
}
|
||||
}
|
||||
|
||||
export async function canUserOverrideTemplate(template, userId) {
|
||||
let templateOwnerId = template.owner
|
||||
let templateOwnerName = 'you'
|
||||
let userIsOwner = true
|
||||
let userIsAdmin
|
||||
if (templateOwnerId != userId) {
|
||||
userIsOwner = false
|
||||
try {
|
||||
userIsAdmin = (await UserGetter.promises.getUser(userId, { isAdmin: 1 })).isAdmin
|
||||
} catch (error) {
|
||||
logger.error({ error, userId }, 'Logged in user does not exist, strange...')
|
||||
userIsAdmin = false
|
||||
}
|
||||
templateOwnerName = await getUserName(templateOwnerId) || 'unknown'
|
||||
}
|
||||
const canOverride = userIsOwner || userIsAdmin || (settings.templates?.user_id === userId)
|
||||
return { canOverride, templateOwnerName }
|
||||
}
|
||||
|
||||
export async function getUserName(userId) {
|
||||
try {
|
||||
const user = await UserGetter.promises.getUser(userId, {
|
||||
first_name: 1,
|
||||
last_name: 1,
|
||||
})
|
||||
return ((user?.first_name || "") + " " + (user?.last_name || "")).trim()
|
||||
} catch (error) {
|
||||
return 'unknown'
|
||||
}
|
||||
}
|
||||
|
||||
export async function generateTemplateData(projectId, {
|
||||
descriptionMD,
|
||||
authorMD,
|
||||
category,
|
||||
license,
|
||||
name,
|
||||
}) {
|
||||
try {
|
||||
await DocumentUpdaterHandler.promises.flushProjectToMongo(projectId)
|
||||
|
||||
const project = await ProjectGetter.promises.getProject(projectId, {
|
||||
imageName: true,
|
||||
compiler: true,
|
||||
spellCheckLanguage: true,
|
||||
rootDoc_id: true,
|
||||
rootFolder: true,
|
||||
})
|
||||
|
||||
const { path } = await ProjectLocator.promises.findRootDoc({ project })
|
||||
const mainFile = path.fileSystem.replace(/^\/+/, '')
|
||||
const template = {
|
||||
name,
|
||||
category,
|
||||
authorMD,
|
||||
descriptionMD,
|
||||
license,
|
||||
mainFile,
|
||||
compiler: project.compiler,
|
||||
imageName: project.imageName,
|
||||
language: project.spellCheckLanguage,
|
||||
lastUpdated: new Date(),
|
||||
}
|
||||
|
||||
await renderTemplateHtmlFields(template)
|
||||
return template
|
||||
} catch (error) {
|
||||
logger.error({ error, projectId }, 'Failed to retrieve project data')
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export async function uploadTemplateAssets(projectId, userId, build, template) {
|
||||
let zipStream, pdfStream
|
||||
try {
|
||||
[zipStream, pdfStream] = await Promise.all([
|
||||
_createZipStreamForProjectAsync(projectId),
|
||||
ClsiManager.promises.getOutputFileStream(projectId, userId, undefined, build, 'output.pdf')
|
||||
])
|
||||
} catch (error) {
|
||||
logger.error({ error, projectId }, 'No output.pdf?')
|
||||
throw new RecompileRequiredError()
|
||||
}
|
||||
try {
|
||||
const templateUrl = `${settings.apis.filestore.url}/template/${template._id}/v/${template.version}`
|
||||
const zipUrl = `${templateUrl}/zip`
|
||||
const pdfUrl = `${templateUrl}/pdf`
|
||||
const [zipReq, pdfReq] = await Promise.all([
|
||||
fetchStreamWithResponse(zipUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/octet-stream',
|
||||
},
|
||||
body: zipStream,
|
||||
signal: AbortSignal.timeout(TIMEOUT),
|
||||
}),
|
||||
fetchStreamWithResponse(pdfUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/pdf',
|
||||
},
|
||||
body: pdfStream,
|
||||
signal: AbortSignal.timeout(TIMEOUT),
|
||||
}),
|
||||
])
|
||||
const uploadErrors = []
|
||||
if (zipReq?.response.status !== 200) {
|
||||
uploadErrors.push({ file: 'zip', uri: zipUrl, statusCode: zipReq.response.status })
|
||||
}
|
||||
if (pdfReq?.response.status !== 200) {
|
||||
uploadErrors.push({ file: 'pdf', uri: pdfUrl, statusCode: pdfReq.response.status })
|
||||
}
|
||||
if (uploadErrors.length > 0) {
|
||||
logger.error({ uploadErrors }, 'Template upload failed')
|
||||
throw new RecompileRequiredError()
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof RecompileRequiredError) throw error
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteTemplateAssets(templateId, version, deleteFromDb) {
|
||||
if (deleteFromDb) {
|
||||
try {
|
||||
await Template.deleteOne({ _id: templateId }).exec()
|
||||
} catch (error) {
|
||||
logger.error({ error, templateId }, 'Failed to delete template from MongoDB')
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
// kick off file deletions, but don't wait
|
||||
const baseUrl = settings.apis.filestore.url
|
||||
const urlTemplate = `${baseUrl}/template/${templateId}/v/${version}/zip`
|
||||
const urlImages = `${baseUrl}/template/${templateId}/v/${version}/pdf`
|
||||
|
||||
const optsTemplate = {
|
||||
method: 'DELETE',
|
||||
uri: urlTemplate,
|
||||
timeout: TIMEOUT,
|
||||
}
|
||||
|
||||
const optsImages = {
|
||||
method: 'DELETE',
|
||||
uri: urlImages,
|
||||
timeout: TIMEOUT,
|
||||
}
|
||||
|
||||
request(optsTemplate, (err, response) => {
|
||||
if (err)
|
||||
logger.warn({ err, templateId }, 'Failed to delete template zip from filestore')
|
||||
})
|
||||
|
||||
request(optsImages, (err, response) => {
|
||||
if (err)
|
||||
logger.warn({ err, templateId }, 'Failed to delete images from filestore')
|
||||
})
|
||||
}
|
||||
|
||||
export function renderTemplateHtmlFields(updates) {
|
||||
if (updates.descriptionMD !== undefined) {
|
||||
const descriptionRawHTML = marked.parse(updates.descriptionMD)
|
||||
updates.description = cleanHtml(descriptionRawHTML, "reachText")
|
||||
}
|
||||
if (updates.authorMD !== undefined) {
|
||||
const authorRawHTML = marked.parse(updates.authorMD)
|
||||
updates.author = cleanHtml(authorRawHTML, "linksOnly")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
import _ from 'lodash'
|
||||
import logger from '@overleaf/logger'
|
||||
import { Readable } from 'stream'
|
||||
import settings from '@overleaf/settings'
|
||||
import { OError } from '../../../../app/src/Features/Errors/Errors.js'
|
||||
import { Template } from './models/Template.mjs'
|
||||
import {
|
||||
validateTemplateInput,
|
||||
renderTemplateHtmlFields,
|
||||
uploadTemplateAssets,
|
||||
deleteTemplateAssets,
|
||||
canUserOverrideTemplate,
|
||||
generateTemplateData
|
||||
} from './TemplateGalleryHelper.mjs'
|
||||
import { cleanHtml } from './CleanHtml.mjs'
|
||||
import { TemplateNameConflictError } from './TemplateErrors.mjs'
|
||||
import { fetchStreamWithResponse } from '@overleaf/fetch-utils'
|
||||
const TIMEOUT = 30000
|
||||
|
||||
async function editTemplate({ templateId, updates }) {
|
||||
|
||||
validateTemplateInput(updates)
|
||||
|
||||
const template = await Template.findById(templateId)
|
||||
if (!template) {
|
||||
throw new OError('Current template not found, strange...', { status: 500, templateId })
|
||||
}
|
||||
|
||||
if (updates.name) {
|
||||
const conflictingTemplate = await Template.findOne(
|
||||
{ name: updates.name, _id: { $ne: templateId } },
|
||||
{ owner: true }
|
||||
).exec()
|
||||
if (conflictingTemplate) {
|
||||
throw new TemplateNameConflictError(String(conflictingTemplate.owner))
|
||||
}
|
||||
}
|
||||
|
||||
await renderTemplateHtmlFields(updates)
|
||||
updates.lastUpdated = new Date()
|
||||
Object.assign(template, updates)
|
||||
|
||||
await template.save()
|
||||
|
||||
return updates
|
||||
}
|
||||
|
||||
async function deleteTemplate({ templateId, version }) {
|
||||
await deleteTemplateAssets(templateId, version, true)
|
||||
}
|
||||
|
||||
async function createTemplateFromProject({ projectId, userId, templateSource }) {
|
||||
validateTemplateInput(templateSource)
|
||||
let template = await Template.findOne({ name: templateSource.name }).exec()
|
||||
|
||||
if (template && !templateSource.override) {
|
||||
const { canOverride, templateOwnerName } = await canUserOverrideTemplate(template, userId)
|
||||
|
||||
return {
|
||||
conflict: true,
|
||||
canOverride,
|
||||
templateOwnerName
|
||||
}
|
||||
}
|
||||
|
||||
const templateData = await generateTemplateData(projectId, templateSource)
|
||||
|
||||
let previousVersionExists
|
||||
if (!template) {
|
||||
template = new Template(templateData)
|
||||
template.owner = userId
|
||||
previousVersionExists = false
|
||||
} else {
|
||||
Object.assign(template, templateData, {
|
||||
version: template.version + 1,
|
||||
})
|
||||
previousVersionExists = true
|
||||
}
|
||||
|
||||
await uploadTemplateAssets(projectId, userId, templateSource.build, template)
|
||||
await template.save()
|
||||
|
||||
if (previousVersionExists) {
|
||||
deleteTemplateAssets(template._id, template.version - 1, false)
|
||||
}
|
||||
return {
|
||||
conflict: false,
|
||||
templateId: template._id,
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchTemplatePreview({ templateId, version, style }) {
|
||||
if (!templateId || !version) {
|
||||
throw new OError('Template ID and version are required', { status: 404 })
|
||||
}
|
||||
const styleParam = style ? `style=${style}` : ''
|
||||
const isImage = (style === 'preview' || style === 'thumbnail')
|
||||
|
||||
if (style && !isImage) {
|
||||
throw new OError('Wrong style', { status: 404, style })
|
||||
}
|
||||
|
||||
const pdfUrl = `${settings.apis.filestore.url}/template/${templateId}/v/${version}/pdf?${styleParam}`
|
||||
const { response } = await fetchStreamWithResponse(pdfUrl, {
|
||||
method: 'GET',
|
||||
signal: AbortSignal.timeout(TIMEOUT),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new OError(`Failed to fetch file: ${response.statusText}`, { status: 400, templateId, version, styleParam })
|
||||
}
|
||||
|
||||
return {
|
||||
stream: Readable.from(response.body),
|
||||
contentType: isImage ? 'application/octet-stream' : 'application/pdf'
|
||||
}
|
||||
}
|
||||
|
||||
async function getTemplatesPageData(category) {
|
||||
const categoryName = settings.templateLinks.find(item => item.url.endsWith(`/${category}`))?.name
|
||||
const templateLinks = categoryName ? undefined : settings.templateLinks.filter(link => link.url !== '/templates/all')
|
||||
return {
|
||||
categoryName,
|
||||
templateLinks
|
||||
}
|
||||
}
|
||||
|
||||
async function getTemplate(key, val) {
|
||||
if (!key || !val) {
|
||||
logger.warn('No key or val provided to getTemplate')
|
||||
return null
|
||||
}
|
||||
|
||||
const query = { [key]: val }
|
||||
const template = await Template.findOne(query).exec()
|
||||
if (!template) return null
|
||||
|
||||
return _formatTemplateForPage(template)
|
||||
}
|
||||
|
||||
async function getCategoryTemplates(reqQuery) {
|
||||
const {
|
||||
category,
|
||||
by = 'lastUpdated',
|
||||
order = 'desc',
|
||||
} = reqQuery || {}
|
||||
|
||||
const query = (category === 'all') ? {} : { category : '/templates/' + category }
|
||||
const projection = { _id : 1, version : 1, name : 1, author : 1, description : 1, lastUpdated : 1 }
|
||||
const allTemplates = await Template.find(query, projection).exec()
|
||||
const formattedTemplates = allTemplates.map(_formatTemplateForList)
|
||||
const sortedTemplates = _sortTemplates(formattedTemplates, { by, order })
|
||||
|
||||
return {
|
||||
totalSize: sortedTemplates.length,
|
||||
templates: sortedTemplates,
|
||||
}
|
||||
}
|
||||
|
||||
function _sortTemplates(templates, sort) {
|
||||
if (
|
||||
(sort.by && !['lastUpdated', 'name'].includes(sort.by)) ||
|
||||
(sort.order && !['asc', 'desc'].includes(sort.order))
|
||||
) {
|
||||
throw new OError('Invalid sorting criteria', { status: 400, sort })
|
||||
}
|
||||
const sortedTemplates = _.orderBy(
|
||||
templates,
|
||||
[sort.by || 'lastUpdated'],
|
||||
[sort.order || 'desc']
|
||||
)
|
||||
return sortedTemplates
|
||||
}
|
||||
|
||||
function _formatTemplateForList(template) {
|
||||
return {
|
||||
id: String(template._id),
|
||||
version: String(template.version),
|
||||
name: template.name,
|
||||
author: cleanHtml(template.author, "plainText"),
|
||||
description: cleanHtml(template.description, "plainText"),
|
||||
lastUpdated: template.lastUpdated,
|
||||
}
|
||||
}
|
||||
|
||||
function _formatTemplateForPage(template) {
|
||||
return {
|
||||
id: template._id.toString(),
|
||||
version: template.version.toString(),
|
||||
category: template.category,
|
||||
name: template.name,
|
||||
author: cleanHtml(template.author, "linksOnly"),
|
||||
authorMD: template.authorMD,
|
||||
description: cleanHtml(template.description, "reachText"),
|
||||
descriptionMD: template.descriptionMD,
|
||||
license: template.license,
|
||||
lastUpdated: template.lastUpdated,
|
||||
owner: template.owner,
|
||||
mainFile: template.mainFile,
|
||||
compiler: template.compiler,
|
||||
imageName: template.imageName,
|
||||
language: template.language,
|
||||
}
|
||||
}
|
||||
|
||||
export default {
|
||||
createTemplateFromProject,
|
||||
editTemplate,
|
||||
deleteTemplate,
|
||||
getTemplate,
|
||||
getCategoryTemplates,
|
||||
fetchTemplatePreview,
|
||||
getTemplatesPageData,
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import logger from '@overleaf/logger'
|
||||
|
||||
import AuthenticationController from '../../../../app/src/Features/Authentication/AuthenticationController.mjs'
|
||||
import RateLimiterMiddleware from '../../../../app/src/Features/Security/RateLimiterMiddleware.mjs'
|
||||
import { RateLimiter } from '../../../../app/src/infrastructure/RateLimiter.mjs'
|
||||
import TemplateGalleryController from './TemplateGalleryController.mjs'
|
||||
import TemplateAuthorizationMiddleware from './TemplateAuthorizationMiddleware.mjs'
|
||||
|
||||
const rateLimiterNewTemplate = new RateLimiter('create-template-from-project', {
|
||||
points: 20,
|
||||
duration: 60,
|
||||
})
|
||||
const rateLimiter = new RateLimiter('template-gallery', {
|
||||
points: 60,
|
||||
duration: 60,
|
||||
})
|
||||
const rateLimiterThumbnails = new RateLimiter('template-gallery-thumbnails', {
|
||||
points: 240,
|
||||
duration: 60,
|
||||
})
|
||||
|
||||
export default {
|
||||
rateLimiter,
|
||||
apply(webRouter) {
|
||||
logger.debug({}, 'Init templates router')
|
||||
|
||||
webRouter.post(
|
||||
'/template/new/:Project_id',
|
||||
AuthenticationController.requireLogin(),
|
||||
RateLimiterMiddleware.rateLimit(rateLimiterNewTemplate),
|
||||
TemplateAuthorizationMiddleware.ensureTemplateManagementAccess,
|
||||
TemplateGalleryController.createTemplateFromProject
|
||||
)
|
||||
|
||||
webRouter.get(
|
||||
'/template/:template_id',
|
||||
RateLimiterMiddleware.rateLimit(rateLimiter),
|
||||
TemplateGalleryController.templateDetailsPage
|
||||
)
|
||||
|
||||
webRouter.post(
|
||||
'/template/:template_id/edit',
|
||||
AuthenticationController.requireLogin(),
|
||||
RateLimiterMiddleware.rateLimit(rateLimiter),
|
||||
TemplateAuthorizationMiddleware.ensureTemplateManagementAccess,
|
||||
TemplateGalleryController.editTemplate
|
||||
)
|
||||
|
||||
webRouter.delete(
|
||||
'/template/:template_id/delete',
|
||||
AuthenticationController.requireLogin(),
|
||||
RateLimiterMiddleware.rateLimit(rateLimiter),
|
||||
TemplateAuthorizationMiddleware.ensureTemplateManagementAccess,
|
||||
TemplateGalleryController.deleteTemplate
|
||||
)
|
||||
|
||||
webRouter.get(
|
||||
'/templates/:category?',
|
||||
RateLimiterMiddleware.rateLimit(rateLimiter),
|
||||
TemplateGalleryController.templatesCategoryPage
|
||||
)
|
||||
|
||||
webRouter.get(
|
||||
'/api/template',
|
||||
RateLimiterMiddleware.rateLimit(rateLimiter),
|
||||
TemplateGalleryController.getTemplateJSON
|
||||
)
|
||||
|
||||
webRouter.get(
|
||||
'/api/templates',
|
||||
RateLimiterMiddleware.rateLimit(rateLimiter),
|
||||
TemplateGalleryController.getCategoryTemplatesJSON
|
||||
)
|
||||
|
||||
webRouter.get(
|
||||
'/template/:template_id/preview',
|
||||
(req, res, next) => {
|
||||
req.query.style === 'thumbnail'
|
||||
? RateLimiterMiddleware.rateLimit(rateLimiterThumbnails)(req, res, next)
|
||||
: RateLimiterMiddleware.rateLimit(rateLimiter)(req, res, next)
|
||||
},
|
||||
TemplateGalleryController.getTemplatePreview
|
||||
)
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import mongoose from '../../../../../app/src/infrastructure/Mongoose.mjs'
|
||||
|
||||
const { Schema } = mongoose
|
||||
const { ObjectId } = Schema
|
||||
|
||||
export const TemplateSchema = new Schema(
|
||||
{
|
||||
name: { type: String, required: true },
|
||||
category: { type: String, required: true },
|
||||
description: { type: String },
|
||||
descriptionMD: { type: String },
|
||||
author: { type: String },
|
||||
authorMD: { type: String },
|
||||
license: { type: String, required: true },
|
||||
mainFile: { type: String, required: true },
|
||||
compiler: { type: String, required: true },
|
||||
imageName: { type: String },
|
||||
language: { type: String },
|
||||
version: { type: Number, default: 1, required: true },
|
||||
owner: { type: ObjectId, ref: 'User' },
|
||||
lastUpdated: {
|
||||
type: Date,
|
||||
default() {
|
||||
return new Date()
|
||||
},
|
||||
required: true
|
||||
},
|
||||
},
|
||||
{ minimize: false }
|
||||
)
|
||||
|
||||
export const Template = mongoose.model('Template', TemplateSchema)
|
||||
@@ -0,0 +1,15 @@
|
||||
extends ../../../../../app/views/layout-react
|
||||
|
||||
block entrypointVar
|
||||
- entrypoint = 'modules/template-gallery/pages/template-gallery'
|
||||
|
||||
block vars
|
||||
- const suppressFooter = true
|
||||
- const suppressPugCookieBanner = true
|
||||
- isWebsiteRedesign = true
|
||||
|
||||
block append meta
|
||||
meta(name="ol-templateCategory" data-type="string" content=category)
|
||||
|
||||
block content
|
||||
#template-gallery-root
|
||||
@@ -0,0 +1,19 @@
|
||||
extends ../../../../../app/views/layout-react
|
||||
|
||||
block entrypointVar
|
||||
- entrypoint = 'modules/template-gallery/pages/template'
|
||||
|
||||
block vars
|
||||
- const suppressNavbar = true
|
||||
- const suppressFooter = true
|
||||
- isWebsiteRedesign = true
|
||||
|
||||
block append meta
|
||||
meta(name="ol-template" data-type="json" content=template)
|
||||
meta(name="ol-languages" data-type="json" content=languages)
|
||||
meta(name="ol-userIsAdmin" data-type="boolean" content=hasAdminAccess())
|
||||
meta(name="ol-userIsTemplatesManager" data-type="boolean" content=userIsTemplatesManager)
|
||||
|
||||
block content
|
||||
#template-root
|
||||
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import OLCol from '@/shared/components/ol/ol-col'
|
||||
import OLRow from '@/shared/components/ol/ol-row'
|
||||
|
||||
export default function GalleryHeaderAll() {
|
||||
const { t } = useTranslation()
|
||||
return (
|
||||
<div className="gallery-header">
|
||||
<OLRow>
|
||||
<OLCol md={12}>
|
||||
<h1 className="gallery-title">
|
||||
<span className="eyebrow-text">
|
||||
<span aria-hidden="true">{</span>
|
||||
<span>{t('overleaf_template_gallery')}</span>
|
||||
<span aria-hidden="true">}</span>
|
||||
</span>
|
||||
{t('latex_templates')}
|
||||
</h1>
|
||||
</OLCol>
|
||||
</OLRow>
|
||||
<div className="row">
|
||||
<div className="col-md-12">
|
||||
<p className="gallery-summary">{t('latex_templates_for_journal_articles')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
import getMeta from '@/utils/meta'
|
||||
import OLCol from '@/shared/components/ol/ol-col'
|
||||
import OLRow from '@/shared/components/ol/ol-row'
|
||||
import GallerySearchSortHeader from './gallery-search-sort-header'
|
||||
|
||||
export default function GalleryHeaderTagged({ category }) {
|
||||
const title = getMeta('og:title')
|
||||
const { templateLinks } = getMeta('ol-ExposedSettings') || []
|
||||
|
||||
const description = templateLinks?.find(link => link.url.split("/").pop() === category)?.description
|
||||
const gotoAllLink = (category !== 'all')
|
||||
return (
|
||||
<div className="tagged-header-container">
|
||||
<GallerySearchSortHeader
|
||||
gotoAllLink={gotoAllLink}
|
||||
/>
|
||||
{ category && (
|
||||
<>
|
||||
<OLRow>
|
||||
<OLCol xs={12}>
|
||||
<h1 className="gallery-title">{title}</h1>
|
||||
</OLCol>
|
||||
</OLRow>
|
||||
<OLRow>
|
||||
<OLCol lg={8}>
|
||||
<p className="gallery-summary">{description}</p>
|
||||
</OLCol>
|
||||
</OLRow>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import getMeta from '@/utils/meta'
|
||||
|
||||
export default function GalleryPopularTags() {
|
||||
const { t } = useTranslation()
|
||||
const { templateLinks } = getMeta('ol-ExposedSettings') || []
|
||||
|
||||
if(!templateLinks || templateLinks.length < 2) return null
|
||||
|
||||
return (
|
||||
<div className="popular-tags">
|
||||
<h1>{t('categories')}</h1>
|
||||
<div className="row popular-tags-list">
|
||||
{templateLinks?.filter(link => link.url.split("/").pop() !== "all").map((link, index) => (
|
||||
<div key={index} className="gallery-thumbnail col-12 col-md-6 col-lg-4">
|
||||
<a href={link.url}>
|
||||
<div className="thumbnail-tag">
|
||||
<img
|
||||
src={`/img/website-redesign/gallery/${link.url.split("/").pop()}.svg`}
|
||||
alt={link.name}
|
||||
/>
|
||||
</div>
|
||||
<span className="caption-title">{link.name}</span>
|
||||
</a>
|
||||
<p>{link.description}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
import { useTemplateGalleryContext } from '../context/template-gallery-context'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import SearchForm from './search-form'
|
||||
import OLCol from '@/shared/components/ol/ol-col'
|
||||
import OLRow from '@/shared/components/ol/ol-row'
|
||||
import useSort from '../hooks/use-sort'
|
||||
import withContent, { SortBtnProps } from './sort/with-content'
|
||||
import MaterialIcon from '@/shared/components/material-icon'
|
||||
|
||||
function SortBtn({ onClick, text, iconType, screenReaderText }: SortBtnProps) {
|
||||
return (
|
||||
<button
|
||||
className="gallery-header-sort-btn inline-block"
|
||||
onClick={onClick}
|
||||
aria-label={screenReaderText}
|
||||
>
|
||||
<span>{text}</span>
|
||||
{iconType ? (
|
||||
<MaterialIcon type={iconType} />
|
||||
) : (
|
||||
<MaterialIcon type="arrow_upward" style={{ visibility: 'hidden' }} />
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
const SortByButton = withContent(SortBtn)
|
||||
|
||||
export default function GallerySearchSortHeader( { gotoAllLink }: { boolean } ) {
|
||||
const { t } = useTranslation()
|
||||
const {
|
||||
searchText,
|
||||
setSearchText,
|
||||
sort,
|
||||
} = useTemplateGalleryContext()
|
||||
|
||||
const { handleSort } = useSort()
|
||||
return (
|
||||
<OLRow className="align-items-center">
|
||||
{gotoAllLink ? (
|
||||
<OLCol className="col-auto">
|
||||
<a className="previous-page-link" href="/templates/all">
|
||||
<i className="material-symbols material-symbols-rounded" aria-hidden="true">arrow_left_alt</i>
|
||||
{t('all_templates')}
|
||||
</a>
|
||||
</OLCol>
|
||||
) : (
|
||||
<OLCol className="col-auto">
|
||||
<a className="previous-page-link" href="/templates">
|
||||
<i className="material-symbols material-symbols-rounded" aria-hidden="true">arrow_left_alt</i>
|
||||
{t('template_gallery')}
|
||||
</a>
|
||||
</OLCol>
|
||||
)}
|
||||
<OLCol className="d-flex justify-content-center gap-2">
|
||||
<SortByButton
|
||||
column="lastUpdated"
|
||||
text={t('last_updated')}
|
||||
sort={sort}
|
||||
onClick={() => handleSort('lastUpdated')}
|
||||
/>
|
||||
|
||||
<SortByButton
|
||||
column="name"
|
||||
text={t('title')}
|
||||
sort={sort}
|
||||
onClick={() => handleSort('name')}
|
||||
/>
|
||||
</OLCol>
|
||||
<OLCol xs={3} className="ms-auto" >
|
||||
<SearchForm
|
||||
inputValue={searchText}
|
||||
setInputValue={setSearchText}
|
||||
/>
|
||||
</OLCol>
|
||||
</OLRow>
|
||||
)
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { MergeAndOverride } from '../../../../../../../types/utils'
|
||||
import OLForm from '@/shared/components/ol/ol-form'
|
||||
import OLFormControl from '@/shared/components/ol/ol-form-control'
|
||||
import MaterialIcon from '@/shared/components/material-icon'
|
||||
|
||||
type SearchFormOwnProps = {
|
||||
inputValue: string
|
||||
setInputValue: (input: string) => void
|
||||
}
|
||||
|
||||
type SearchFormProps = MergeAndOverride<
|
||||
React.ComponentProps<typeof OLForm>,
|
||||
SearchFormOwnProps
|
||||
>
|
||||
|
||||
export default function SearchForm({
|
||||
inputValue,
|
||||
setInputValue,
|
||||
}: SearchFormProps) {
|
||||
const { t } = useTranslation()
|
||||
let placeholderMessage = t('search')
|
||||
const placeholder = `${placeholderMessage}…`
|
||||
|
||||
const handleChange: React.ComponentProps<typeof OLFormControl
|
||||
>['onChange'] = e => {
|
||||
setInputValue(e.target.value)
|
||||
}
|
||||
|
||||
const handleClear = () => setInputValue('')
|
||||
|
||||
return (
|
||||
<OLForm
|
||||
role="search"
|
||||
onSubmit={e => e.preventDefault()}
|
||||
>
|
||||
<OLFormControl
|
||||
className="gallery-search-form-control"
|
||||
id="gallery-search-form-control"
|
||||
type="text"
|
||||
value={inputValue}
|
||||
onChange={handleChange}
|
||||
placeholder={placeholder}
|
||||
aria-label={placeholder}
|
||||
prepend={<MaterialIcon type="search" />}
|
||||
append={
|
||||
inputValue.length > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
className="form-control-search-clear-btn"
|
||||
aria-label={t('clear_search')}
|
||||
onClick={handleClear}
|
||||
>
|
||||
<MaterialIcon type="clear" />
|
||||
</button>
|
||||
)
|
||||
}
|
||||
/>
|
||||
</OLForm>
|
||||
)
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Sort } from '../../types/api'
|
||||
|
||||
type SortBtnOwnProps = {
|
||||
column: string
|
||||
sort: Sort
|
||||
text: string
|
||||
onClick: () => void
|
||||
}
|
||||
|
||||
type WithContentProps = {
|
||||
iconType?: string
|
||||
screenReaderText: string
|
||||
}
|
||||
|
||||
export type SortBtnProps = SortBtnOwnProps & WithContentProps
|
||||
|
||||
function withContent<T extends SortBtnOwnProps>(
|
||||
WrappedComponent: React.ComponentType<T & WithContentProps>
|
||||
) {
|
||||
function WithContent(hocProps: T) {
|
||||
const { t } = useTranslation()
|
||||
const { column, text, sort } = hocProps
|
||||
let iconType
|
||||
|
||||
let screenReaderText = t('sort_by_x', { x: text })
|
||||
|
||||
if (column === sort.by) {
|
||||
iconType =
|
||||
sort.order === 'asc' ? 'arrow_upward_alt' : 'arrow_downward_alt'
|
||||
screenReaderText = t('reverse_x_sort_order', { x: text })
|
||||
}
|
||||
|
||||
return (
|
||||
<WrappedComponent
|
||||
{...hocProps}
|
||||
iconType={iconType}
|
||||
screenReaderText={screenReaderText}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return WithContent
|
||||
}
|
||||
|
||||
export default withContent
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
import { memo } from 'react'
|
||||
import { cleanHtml } from '../../../../../app/src/CleanHtml.mjs'
|
||||
|
||||
function TemplateGalleryEntry({ template }) {
|
||||
return (
|
||||
<div className={"gallery-thumbnail col-12 col-md-6 col-lg-4"}>
|
||||
<a href={`/template/${template.id}`} className="thumbnail-link">
|
||||
<div className="thumbnail">
|
||||
<img
|
||||
src={`/template/${template.id}/preview?version=${template.version}&style=thumbnail`}
|
||||
alt={template.name}
|
||||
/>
|
||||
</div>
|
||||
<span className="gallery-list-item-title">
|
||||
<span className="caption-title">{template.name}</span>
|
||||
<span className="badge-container"></span>
|
||||
</span>
|
||||
</a>
|
||||
<div className="caption">
|
||||
<p className="caption-description" dangerouslySetInnerHTML={{ __html: cleanHtml(template.description, 'plainText') }} />
|
||||
</div>
|
||||
<div className="author-name">
|
||||
<div dangerouslySetInnerHTML={{ __html: cleanHtml(template.author, 'plainText') }} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(TemplateGalleryEntry)
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
import { TemplateGalleryProvider } from '../context/template-gallery-context'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import useWaitForI18n from '@/shared/hooks/use-wait-for-i18n'
|
||||
import withErrorBoundary from '@/infrastructure/error-boundary'
|
||||
import { GenericErrorBoundaryFallback } from '@/shared/components/generic-error-boundary-fallback'
|
||||
import getMeta from '@/utils/meta'
|
||||
import DefaultNavbar from '@/shared/components/navbar/default-navbar'
|
||||
import Footer from '@/shared/components/footer/footer'
|
||||
import GalleryHeaderTagged from './gallery-header-tagged'
|
||||
import GalleryHeaderAll from './gallery-header-all'
|
||||
import TemplateGallery from './template-gallery'
|
||||
import GallerySearchSortHeader from './gallery-search-sort-header'
|
||||
import GalleryPopularTags from './gallery-popular-tags'
|
||||
|
||||
function TemplateGalleryRoot() {
|
||||
const { isReady } = useWaitForI18n()
|
||||
if (!isReady) {
|
||||
return null
|
||||
}
|
||||
return (
|
||||
<TemplateGalleryProvider>
|
||||
<TemplateGalleryPageContent />
|
||||
</TemplateGalleryProvider>
|
||||
)
|
||||
}
|
||||
|
||||
function TemplateGalleryPageContent() {
|
||||
const { t } = useTranslation()
|
||||
const navbarProps = getMeta('ol-navbar')
|
||||
const footerProps = getMeta('ol-footer')
|
||||
const category = getMeta('ol-templateCategory')
|
||||
|
||||
return (
|
||||
<>
|
||||
<DefaultNavbar {...navbarProps} />
|
||||
<main id="main-content"
|
||||
className={`content content-page gallery ${category ? 'gallery-tagged' : ''}`}
|
||||
>
|
||||
<div className="container">
|
||||
{category ? (
|
||||
<>
|
||||
<GalleryHeaderTagged category={category} />
|
||||
<TemplateGallery />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<GalleryHeaderAll />
|
||||
<GalleryPopularTags />
|
||||
<hr className="w-full border-muted mb-5" />
|
||||
<div className="recent-docs">
|
||||
<GallerySearchSortHeader />
|
||||
<h2>{t('all_templates')}</h2>
|
||||
<TemplateGallery />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
<Footer {...footerProps} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default withErrorBoundary(TemplateGalleryRoot, GenericErrorBoundaryFallback)
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import OLRow from '@/shared/components/ol/ol-row'
|
||||
import { useTemplateGalleryContext } from '../context/template-gallery-context'
|
||||
import TemplateGalleryEntry from './template-gallery-entry'
|
||||
import Pagination from '@/shared/components/pagination-cep'
|
||||
|
||||
export default function TemplateGallery() {
|
||||
const { t } = useTranslation()
|
||||
const {
|
||||
searchText,
|
||||
sort,
|
||||
visibleTemplates,
|
||||
} = useTemplateGalleryContext()
|
||||
|
||||
const templatesPerPage = 6
|
||||
const totalPages = Math.ceil(visibleTemplates.length / templatesPerPage)
|
||||
|
||||
const [currentPage, setCurrentPage] = useState(1)
|
||||
|
||||
useEffect(() => {
|
||||
setCurrentPage(1)
|
||||
}, [sort])
|
||||
|
||||
const [lastNonSearchPage, setLastNonSearchPage] = useState(1)
|
||||
const [isSearching, setIsSearching] = useState(false)
|
||||
useEffect(() => {
|
||||
if (searchText.length > 0) {
|
||||
if (!isSearching) {
|
||||
setLastNonSearchPage(currentPage)
|
||||
setIsSearching(true)
|
||||
}
|
||||
setCurrentPage(1)
|
||||
} else {
|
||||
if (isSearching) {
|
||||
setCurrentPage(lastNonSearchPage)
|
||||
setIsSearching(false)
|
||||
}
|
||||
}
|
||||
}, [searchText])
|
||||
|
||||
const startIndex = (currentPage - 1) * templatesPerPage
|
||||
const currentTemplates = visibleTemplates.slice(startIndex, startIndex + templatesPerPage)
|
||||
|
||||
return (
|
||||
<>
|
||||
<OLRow className="gallery-container">
|
||||
{currentTemplates.length > 0 ? (
|
||||
currentTemplates.map(p => (
|
||||
<TemplateGalleryEntry
|
||||
className="gallery-thumbnail col-12 col-md-6 col-lg-4"
|
||||
key={p.id}
|
||||
template={p}
|
||||
/>
|
||||
))
|
||||
) : (
|
||||
<OLRow>
|
||||
<p className="text-center">{t('no_templates_found')}</p>
|
||||
</OLRow>
|
||||
)}
|
||||
</OLRow>
|
||||
<Pagination currentPage={currentPage} totalPages={totalPages} onPageChange={setCurrentPage} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
import {
|
||||
createContext,
|
||||
ReactNode,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react'
|
||||
import { Template } from '../../../../../types/template'
|
||||
import { GetTemplatesResponseBody, Sort } from '../types/api'
|
||||
import getMeta from '@/utils/meta'
|
||||
import useAsync from '@/shared/hooks/use-async'
|
||||
import { getTemplates } from '../util/api'
|
||||
import sortTemplates from '../util/sort-templates'
|
||||
import { debugConsole } from '@/utils/debugging'
|
||||
|
||||
export type TemplateGalleryContextValue = {
|
||||
visibleTemplates: Template[]
|
||||
totalTemplatesCount: number
|
||||
error: Error | null
|
||||
sort: Sort
|
||||
setSort: React.Dispatch<React.SetStateAction<Sort>>
|
||||
searchText: string
|
||||
setSearchText: React.Dispatch<React.SetStateAction<string>>
|
||||
}
|
||||
|
||||
export const TemplateGalleryContext = createContext<
|
||||
TemplateGalleryContextValue | undefined
|
||||
>(undefined)
|
||||
|
||||
type TemplateGalleryProviderProps = {
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
export function TemplateGalleryProvider({ children }: TemplateGalleryProviderProps) {
|
||||
const [loadedTemplates, setLoadedTemplates] = useState<Template[]>([])
|
||||
const [visibleTemplates, setVisibleTemplates] = useState<Template[]>([])
|
||||
const [totalTemplatesCount, setTotalTemplatesCount] = useState<number>(0)
|
||||
const [sort, setSort] = useState<Sort>({
|
||||
by: 'lastUpdated',
|
||||
order: 'desc',
|
||||
})
|
||||
const prevSortRef = useRef<Sort>(sort)
|
||||
|
||||
const [searchText, setSearchText] = useState('')
|
||||
|
||||
const {
|
||||
error,
|
||||
runAsync,
|
||||
} = useAsync<GetTemplatesResponseBody>()
|
||||
|
||||
const category = getMeta('ol-templateCategory') || 'all'
|
||||
|
||||
useEffect(() => {
|
||||
runAsync(getTemplates(sort, category))
|
||||
.then(data => {
|
||||
setLoadedTemplates(data.templates)
|
||||
setTotalTemplatesCount(data.totalSize)
|
||||
})
|
||||
.catch(debugConsole.error)
|
||||
.finally(() => {
|
||||
})
|
||||
}, [runAsync])
|
||||
|
||||
useEffect(() => {
|
||||
let filteredTemplates = [...loadedTemplates]
|
||||
|
||||
if (searchText.length) {
|
||||
filteredTemplates = filteredTemplates.filter(template =>
|
||||
template.name.toLowerCase().includes(searchText.toLowerCase()) ||
|
||||
template.description.toLowerCase().includes(searchText.toLowerCase())
|
||||
)
|
||||
}
|
||||
|
||||
if (prevSortRef.current !== sort) {
|
||||
filteredTemplates = sortTemplates(filteredTemplates, sort)
|
||||
const loadedTemplatesSorted = sortTemplates(loadedTemplates, sort)
|
||||
setLoadedTemplates(loadedTemplatesSorted)
|
||||
}
|
||||
setVisibleTemplates(filteredTemplates)
|
||||
}, [
|
||||
loadedTemplates,
|
||||
searchText,
|
||||
sort,
|
||||
])
|
||||
|
||||
useEffect(() => {
|
||||
prevSortRef.current = sort
|
||||
}, [sort])
|
||||
|
||||
|
||||
const value = useMemo<TemplateGalleryContextValue>(
|
||||
() => ({
|
||||
error,
|
||||
searchText,
|
||||
setSearchText,
|
||||
setSort,
|
||||
sort,
|
||||
totalTemplatesCount,
|
||||
visibleTemplates,
|
||||
}),
|
||||
[
|
||||
error,
|
||||
searchText,
|
||||
setSearchText,
|
||||
setSort,
|
||||
sort,
|
||||
totalTemplatesCount,
|
||||
visibleTemplates,
|
||||
]
|
||||
)
|
||||
|
||||
return (
|
||||
<TemplateGalleryContext.Provider value={value}>
|
||||
{children}
|
||||
</TemplateGalleryContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function useTemplateGalleryContext() {
|
||||
const context = useContext(TemplateGalleryContext)
|
||||
if (!context) {
|
||||
throw new Error(
|
||||
'TemplateGalleryContext is only available inside TemplateGalleryProvider'
|
||||
)
|
||||
}
|
||||
return context
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
import { useTemplateGalleryContext } from '../context/template-gallery-context'
|
||||
import { Sort } from '../types/api'
|
||||
import { SortingOrder } from '../../../../../../../types/sorting-order'
|
||||
|
||||
const toggleSort = (order: SortingOrder): SortingOrder => {
|
||||
return order === 'asc' ? 'desc' : 'asc'
|
||||
}
|
||||
|
||||
function useSort() {
|
||||
const { sort, setSort } = useTemplateGalleryContext()
|
||||
const handleSort = (by: Sort['by']) => {
|
||||
setSort(prev => ({
|
||||
by,
|
||||
order: prev.by === by ? toggleSort(sort.order) : by === 'lastUpdated' ? 'desc' : 'asc',
|
||||
}))
|
||||
}
|
||||
return { handleSort }
|
||||
}
|
||||
|
||||
export default useSort
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
import { SortingOrder } from '../../../../../../../types/sorting-order'
|
||||
import { Template } from '../../../../../types/template'
|
||||
|
||||
export type Sort = {
|
||||
by: 'lastUpdated' | 'name'
|
||||
order: SortingOrder
|
||||
}
|
||||
|
||||
export type GetTemplatesResponseBody = {
|
||||
totalSize: number
|
||||
templates: Template[]
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
import { GetTemplatesResponseBody, Sort } from '../types/api'
|
||||
import { getJSON } from '@/infrastructure/fetch-json'
|
||||
|
||||
export function getTemplates(sortBy: Sort, category: string): Promise<GetTemplatesResponseBody> {
|
||||
const queryParams = new URLSearchParams({
|
||||
by: sortBy.by,
|
||||
order: sortBy.order,
|
||||
category,
|
||||
}).toString()
|
||||
|
||||
return getJSON(`/api/templates?${queryParams}`)
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
import { Sort } from '../types/api'
|
||||
import { Template } from '../../../../../types/template'
|
||||
import { SortingOrder } from '../../../../../../../types/sorting-order'
|
||||
import { Compare } from '../../../../../../../types/helpers/array/sort'
|
||||
|
||||
const order = (order: SortingOrder, templates: Template[]) => {
|
||||
return order === 'asc' ? [...templates] : templates.reverse()
|
||||
}
|
||||
|
||||
export const defaultComparator = (
|
||||
v1: Template,
|
||||
v2: Template,
|
||||
key: 'name' | 'lastUpdated'
|
||||
) => {
|
||||
const value1 = v1[key].toLowerCase()
|
||||
const value2 = v2[key].toLowerCase()
|
||||
|
||||
if (value1 !== value2) {
|
||||
return value1 < value2 ? Compare.SORT_A_BEFORE_B : Compare.SORT_A_AFTER_B
|
||||
}
|
||||
|
||||
return Compare.SORT_KEEP_ORDER
|
||||
}
|
||||
|
||||
export default function sortTemplates(templates: Template[], sort: Sort) {
|
||||
let sorted = [...templates]
|
||||
if (sort.by === 'name') {
|
||||
sorted = sorted.sort((...args) => {
|
||||
return defaultComparator(...args, 'name')
|
||||
})
|
||||
}
|
||||
|
||||
if (sort.by === 'lastUpdated') {
|
||||
sorted = sorted.sort((...args) => {
|
||||
return defaultComparator(...args, 'lastUpdated')
|
||||
})
|
||||
}
|
||||
|
||||
return order(sort.order, sorted)
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
import { useCallback, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import * as eventTracking from '@/infrastructure/event-tracking'
|
||||
import getMeta from '@/utils/meta'
|
||||
import OLTooltip from '@/shared/components/ol/ol-tooltip'
|
||||
import { useDetachCompileContext } from '@/shared/context/detach-compile-context'
|
||||
import EditorManageTemplateModalWrapper from './manage-template-modal/editor-manage-template-modal-wrapper'
|
||||
import LeftMenuButton from '@/features/editor-left-menu/components/left-menu-button'
|
||||
|
||||
type TemplateManageResponse = {
|
||||
template_id: string
|
||||
}
|
||||
|
||||
export default function ActionsManageTemplate() {
|
||||
|
||||
const templatesAdmin = getMeta('ol-showTemplatesServerPro')
|
||||
if (!templatesAdmin) {
|
||||
return null
|
||||
}
|
||||
|
||||
const [showModal, setShowModal] = useState(false)
|
||||
const { pdfFile } = useDetachCompileContext()
|
||||
const { t } = useTranslation()
|
||||
|
||||
const handleShowModal = useCallback(() => {
|
||||
eventTracking.sendMB('left-menu-template')
|
||||
setShowModal(true)
|
||||
}, [])
|
||||
|
||||
const openTemplate = useCallback(
|
||||
({ template_id: templateId }: TemplateManageResponse) => {
|
||||
location.assign(`/template/${templateId}`)
|
||||
},
|
||||
[]
|
||||
)
|
||||
|
||||
return (
|
||||
<>
|
||||
{pdfFile ? (
|
||||
<LeftMenuButton onClick={handleShowModal} icon='open_in_new'>
|
||||
{t('publish_as_template')}
|
||||
</LeftMenuButton>
|
||||
) : (
|
||||
<OLTooltip
|
||||
id="disabled-publish-as-template"
|
||||
description={t('please_compile_pdf_before_publish_as_template')}
|
||||
overlayProps={{
|
||||
placement: 'top',
|
||||
}}
|
||||
>
|
||||
{/* OverlayTrigger won't fire unless the child is a non-react html element (e.g div, span) */}
|
||||
<div>
|
||||
<LeftMenuButton
|
||||
icon='open_in_new'
|
||||
disabled
|
||||
disabledAccesibilityText={t(
|
||||
'please_compile_pdf_before_publish_as_template'
|
||||
)}
|
||||
>
|
||||
{t('publish_as_template')}
|
||||
</LeftMenuButton>
|
||||
</div>
|
||||
</OLTooltip>
|
||||
)}
|
||||
<EditorManageTemplateModalWrapper
|
||||
show={showModal}
|
||||
handleHide={() => setShowModal(false)}
|
||||
openTemplate={openTemplate}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
import { useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import useIsMounted from '@/shared/hooks/use-is-mounted'
|
||||
import OLButton from '@/shared/components/ol/ol-button'
|
||||
import DeleteTemplateModal from './modals/delete-template-modal'
|
||||
import { useTemplateContext } from '../context/template-context'
|
||||
import { deleteTemplate } from '../util/api'
|
||||
import type { Template } from '../../../../../types/template'
|
||||
|
||||
function DeleteTemplateButton() {
|
||||
const { t } = useTranslation()
|
||||
const [showModal, setShowModal] = useState(false)
|
||||
const isMounted = useIsMounted()
|
||||
const { template, setTemplate } = useTemplateContext()
|
||||
|
||||
const handleOpenModal = () => {
|
||||
setShowModal(true)
|
||||
}
|
||||
|
||||
const handleCloseModal = () => {
|
||||
if (isMounted.current) {
|
||||
setShowModal(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDeleteTemplate = async (template: Template) => {
|
||||
await deleteTemplate(template)
|
||||
handleCloseModal()
|
||||
const previousPage = document.referrer || '/templates'
|
||||
window.location.href = previousPage
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<OLButton variant="danger" onClick={handleOpenModal}>
|
||||
{t('delete')}
|
||||
</OLButton>
|
||||
<DeleteTemplateModal
|
||||
template={template}
|
||||
actionHandler={handleDeleteTemplate}
|
||||
showModal={showModal}
|
||||
handleCloseModal={handleCloseModal}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default DeleteTemplateButton
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
import { useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import useIsMounted from '@/shared/hooks/use-is-mounted'
|
||||
import OLButton from '@/shared/components/ol/ol-button'
|
||||
import EditTemplateModal from './modals/edit-template-modal'
|
||||
import { useTemplateContext } from '../context/template-context'
|
||||
import { updateTemplate } from '../util/api'
|
||||
import type { Template } from '../../../../../types/template'
|
||||
|
||||
export default function EditTemplateButton() {
|
||||
const { t } = useTranslation()
|
||||
const [showModal, setShowModal] = useState(false)
|
||||
const isMounted = useIsMounted()
|
||||
const { template, setTemplate } = useTemplateContext()
|
||||
|
||||
const handleOpenModal = () => {
|
||||
setShowModal(true)
|
||||
}
|
||||
|
||||
const handleCloseModal = () => {
|
||||
if (isMounted.current) {
|
||||
setShowModal(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleEditTemplate = async (editedTemplate: Template) => {
|
||||
const updated = await updateTemplate({ editedTemplate, template })
|
||||
if (updated) {
|
||||
setTemplate(prev => ({ ...prev, ...updated }))
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<OLButton variant="secondary" onClick={handleOpenModal}>
|
||||
{t('edit')}
|
||||
</OLButton>
|
||||
|
||||
<EditTemplateModal
|
||||
showModal={showModal}
|
||||
handleCloseModal={handleCloseModal}
|
||||
actionHandler={handleEditTemplate}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import React from 'react'
|
||||
import OLFormControl from '@/shared/components/ol/ol-form-control'
|
||||
|
||||
interface FormFieldInputProps extends React.ComponentProps<typeof OLFormControl> {
|
||||
value: string
|
||||
placeholder?: string
|
||||
onChange: React.ChangeEventHandler<HTMLInputElement | HTMLTextAreaElement>
|
||||
}
|
||||
|
||||
const FormFieldInput: React.FC<FormFieldInputProps> = ({
|
||||
type = 'text',
|
||||
...props
|
||||
}) => (
|
||||
<OLFormControl type={type} {...props} />
|
||||
)
|
||||
|
||||
export default FormFieldInput
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
import React from 'react'
|
||||
import OLFormGroup from '@/shared/components/ol/ol-form-group'
|
||||
import OLFormLabel from '@/shared/components/ol/ol-form-label'
|
||||
|
||||
interface LabeledRowFormGroupProps {
|
||||
controlId: string
|
||||
label: string
|
||||
children: React.ReactNode
|
||||
}
|
||||
|
||||
const LabeledRowFormGroup: React.FC<LabeledRowFormGroupProps> = ({
|
||||
controlId,
|
||||
label,
|
||||
children,
|
||||
}) => (
|
||||
<OLFormGroup controlId={controlId} className="row">
|
||||
<div className="col-2">
|
||||
<OLFormLabel className="col-form-label col">{label}</OLFormLabel>
|
||||
</div>
|
||||
<div className="col-10">
|
||||
{children}
|
||||
</div>
|
||||
</OLFormGroup>
|
||||
)
|
||||
|
||||
export default React.memo(LabeledRowFormGroup)
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
import React, { useCallback } from 'react'
|
||||
import LabeledRowFormGroup from '../form/labeled-row-form-group'
|
||||
import FormFieldInput from '../form/form-field-input'
|
||||
import SettingsTemplateCategory from '../settings/settings-template-category'
|
||||
import SettingsLicense from '../settings/settings-license'
|
||||
import SettingsLanguage from '../settings/settings-language'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import type { Template } from '../../../../../../types/template'
|
||||
|
||||
interface TemplateFormFieldsProps {
|
||||
template: Partial<Template>
|
||||
includeLanguage?: boolean
|
||||
onChange: (changes: Partial<Template>) => void
|
||||
onEnterKey?: () => void
|
||||
}
|
||||
|
||||
function TemplateFormFields({
|
||||
template,
|
||||
includeLanguage = false,
|
||||
onChange,
|
||||
onEnterKey,
|
||||
}: TemplateFormFieldsProps) {
|
||||
const { t } = useTranslation()
|
||||
|
||||
const handleKeyDown = useCallback(
|
||||
(e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault()
|
||||
onEnterKey?.()
|
||||
}
|
||||
},
|
||||
[onEnterKey]
|
||||
)
|
||||
|
||||
return (
|
||||
<>
|
||||
<LabeledRowFormGroup controlId="form-title" label={t('title') + ':'}>
|
||||
<FormFieldInput
|
||||
required
|
||||
maxLength="255"
|
||||
value={template.name ?? ''}
|
||||
placeholder={t('title')}
|
||||
onChange={e => onChange({ name: e.target.value })}
|
||||
onKeyDown={handleKeyDown}
|
||||
/>
|
||||
</LabeledRowFormGroup>
|
||||
|
||||
<LabeledRowFormGroup controlId="form-author" label={t('author') + ':'}>
|
||||
<FormFieldInput
|
||||
maxLength="255"
|
||||
value={template.authorMD ?? ''}
|
||||
placeholder={t('author')}
|
||||
onChange={e => onChange({ authorMD: e.target.value })}
|
||||
onKeyDown={handleKeyDown}
|
||||
/>
|
||||
</LabeledRowFormGroup>
|
||||
|
||||
<LabeledRowFormGroup controlId="form-category" label={t('category') + ':'}>
|
||||
<SettingsTemplateCategory
|
||||
value={template.category}
|
||||
onChange={val => onChange({ category: val })}
|
||||
/>
|
||||
</LabeledRowFormGroup>
|
||||
|
||||
<LabeledRowFormGroup controlId="form-description" label={t('description') + ':'}>
|
||||
<FormFieldInput
|
||||
as="textarea"
|
||||
rows={8}
|
||||
maxLength="5000"
|
||||
value={template.descriptionMD ?? ''}
|
||||
placeholder={t('description')}
|
||||
onChange={e => onChange({ descriptionMD: e.target.value })}
|
||||
autoFocus
|
||||
/>
|
||||
</LabeledRowFormGroup>
|
||||
|
||||
<LabeledRowFormGroup controlId="form-license" label={t('license') + ':'}>
|
||||
<SettingsLicense
|
||||
value={template.license}
|
||||
onChange={val => onChange({ license: val })}
|
||||
/>
|
||||
</LabeledRowFormGroup>
|
||||
|
||||
{includeLanguage && (
|
||||
<LabeledRowFormGroup controlId="form-language" label={t('language') + ':'}>
|
||||
<SettingsLanguage
|
||||
value={template.language}
|
||||
onChange={val => onChange({ language: val })}
|
||||
/>
|
||||
</LabeledRowFormGroup>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default React.memo(TemplateFormFields)
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
import React from 'react'
|
||||
import withErrorBoundary from '@/infrastructure/error-boundary'
|
||||
import { useProjectContext } from '@/shared/context/project-context'
|
||||
import ManageTemplateModal from './manage-template-modal'
|
||||
import type { Template } from '../../../../../../types/template'
|
||||
|
||||
interface EditorManageTemplateModalWrapperProps {
|
||||
show: boolean
|
||||
handleHide: () => void
|
||||
openTemplate: (data: Template) => void
|
||||
}
|
||||
|
||||
const EditorManageTemplateModalWrapper = React.memo(
|
||||
function EditorManageTemplateModalWrapper({
|
||||
show,
|
||||
handleHide,
|
||||
openTemplate,
|
||||
}: EditorManageTemplateModalWrapperProps) {
|
||||
const { project } = useProjectContext()
|
||||
|
||||
if (!project) {
|
||||
// wait for useProjectContext
|
||||
return null
|
||||
}
|
||||
return (
|
||||
<ManageTemplateModal
|
||||
handleHide={handleHide}
|
||||
show={show}
|
||||
handleAfterPublished={openTemplate}
|
||||
projectId={project._id}
|
||||
projectName={project.name}
|
||||
/>
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
export default withErrorBoundary(EditorManageTemplateModalWrapper)
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
import React, { useEffect, useState, useRef } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { debugConsole } from '@/utils/debugging'
|
||||
import { getJSON, postJSON } from '@/infrastructure/fetch-json'
|
||||
import Notification from '@/shared/components/notification'
|
||||
import {
|
||||
OLModalBody,
|
||||
OLModalFooter,
|
||||
OLModalHeader,
|
||||
OLModalTitle,
|
||||
} from '@/shared/components/ol/ol-modal'
|
||||
import OLForm from '@/shared/components/ol/ol-form'
|
||||
import OLButton from '@/shared/components/ol/ol-button'
|
||||
import { useDetachCompileContext } from '@/shared/context/detach-compile-context'
|
||||
import { useUserContext } from '@/shared/context/user-context'
|
||||
import { useFocusTrap } from '../../hooks/use-focus-trap'
|
||||
import TemplateFormFields from '../form/template-form-fields'
|
||||
import type { Template } from '../../../../../../types/template'
|
||||
|
||||
|
||||
interface ManageTemplateModalContentProps {
|
||||
handleHide: () => void
|
||||
inFlight: boolean
|
||||
setInFlight: (inFlight: boolean) => void
|
||||
handleAfterPublished: (data: Template) => void
|
||||
projectId: string
|
||||
projectName: string
|
||||
}
|
||||
|
||||
export default function ManageTemplateModalContent({
|
||||
handleHide,
|
||||
inFlight,
|
||||
setInFlight,
|
||||
handleAfterPublished,
|
||||
projectId,
|
||||
projectName,
|
||||
}: ManageTemplateModalContentProps) {
|
||||
const { t } = useTranslation()
|
||||
const { pdfFile } = useDetachCompileContext()
|
||||
const user = useUserContext()
|
||||
|
||||
const [template, setTemplate] = useState<Partial<Template>>({
|
||||
name: projectName,
|
||||
authorMD: `${user.first_name} ${user.last_name}`.trim(),
|
||||
})
|
||||
const [override, setOverride] = useState(false)
|
||||
const [titleConflict, setTitleConflict] = useState(false)
|
||||
const [error, setError] = useState<string | false>(false)
|
||||
const [notificationType, setNotificationType] = useState<'error' | 'warning'>('error')
|
||||
const [disablePublish, setDisablePublish] = useState(false)
|
||||
|
||||
// Only the trimmed name gates submission
|
||||
const valid = (template.name ?? '').trim()
|
||||
|
||||
useEffect(() => {
|
||||
const queryParams = new URLSearchParams({ key: 'name', val: projectName })
|
||||
getJSON(`/api/template?${queryParams}`)
|
||||
.then((data) => {
|
||||
if (!data) return
|
||||
setTemplate(prev => ({
|
||||
...prev,
|
||||
descriptionMD: data.descriptionMD,
|
||||
authorMD: data.authorMD,
|
||||
license: data.license,
|
||||
category: data.category,
|
||||
}))
|
||||
})
|
||||
.catch(debugConsole.error)
|
||||
}, [])
|
||||
|
||||
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault()
|
||||
|
||||
if (!valid) return
|
||||
|
||||
setError(false)
|
||||
setInFlight(true)
|
||||
|
||||
postJSON(`/template/new/${projectId}`, {
|
||||
body: {
|
||||
category: template.category,
|
||||
name: valid,
|
||||
authorMD: (template.authorMD ?? '').trim(),
|
||||
license: template.license,
|
||||
descriptionMD: (template.descriptionMD ?? '').trim(),
|
||||
build: pdfFile.build,
|
||||
override,
|
||||
},
|
||||
})
|
||||
.then(data => {
|
||||
handleHide()
|
||||
handleAfterPublished(data)
|
||||
})
|
||||
.catch(({ response, data }) => {
|
||||
if (response?.status === 409 && data.canOverride) {
|
||||
setNotificationType('warning')
|
||||
setOverride(true)
|
||||
} else {
|
||||
setNotificationType('error')
|
||||
setDisablePublish(true)
|
||||
}
|
||||
setError(data.message)
|
||||
if (response?.status === 409) setTitleConflict(true)
|
||||
})
|
||||
.finally(() => {
|
||||
setInFlight(false)
|
||||
})
|
||||
}
|
||||
|
||||
const handleChange = (changes: Partial<Template>) => {
|
||||
if ('name' in changes && titleConflict) {
|
||||
setError(false)
|
||||
setOverride(false)
|
||||
if (disablePublish) setDisablePublish(false)
|
||||
}
|
||||
setTemplate(prev => ({ ...prev, ...changes }))
|
||||
}
|
||||
|
||||
const handleEnterKey = () => {
|
||||
document.getElementById('submit-publish-template')?.click()
|
||||
}
|
||||
|
||||
const modalRef = useRef<HTMLDivElement>(null)
|
||||
useFocusTrap(modalRef)
|
||||
|
||||
return (
|
||||
<div ref={modalRef}>
|
||||
<OLModalHeader>
|
||||
<OLModalTitle>{t('publish_as_template')}</OLModalTitle>
|
||||
</OLModalHeader>
|
||||
|
||||
<OLModalBody>
|
||||
<div className="modal-body-publish">
|
||||
<div className="content-as-table">
|
||||
<OLForm id="publish-template-form" onSubmit={handleSubmit}>
|
||||
<TemplateFormFields
|
||||
template={template}
|
||||
includeLanguage={false}
|
||||
onChange={handleChange}
|
||||
onEnterKey={handleEnterKey}
|
||||
/>
|
||||
</OLForm>
|
||||
</div>
|
||||
</div>
|
||||
{error && (
|
||||
<Notification
|
||||
content={error.length ? error : t('generic_something_went_wrong')}
|
||||
type={notificationType}
|
||||
/>
|
||||
)}
|
||||
</OLModalBody>
|
||||
|
||||
<OLModalFooter>
|
||||
<OLButton variant="secondary" disabled={inFlight} onClick={handleHide}>
|
||||
{t('cancel')}
|
||||
</OLButton>
|
||||
<OLButton
|
||||
id="submit-publish-template"
|
||||
variant={override ? 'danger' : 'primary'}
|
||||
disabled={inFlight || !valid || disablePublish}
|
||||
form="publish-template-form"
|
||||
type="submit"
|
||||
>
|
||||
{inFlight ? <>{t('publishing')}…</> : override ? t('overwrite') : t('publish')}
|
||||
</OLButton>
|
||||
</OLModalFooter>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
import React, { memo, useCallback, useState } from 'react'
|
||||
import { OLModal } from '@/shared/components/ol/ol-modal'
|
||||
import ManageTemplateModalContent from './manage-template-modal-content'
|
||||
import type { Template } from '../../../../../../types/template'
|
||||
|
||||
interface ManageTemplateModalProps {
|
||||
show: boolean
|
||||
handleHide: () => void
|
||||
handleAfterPublished: (data: Template) => void
|
||||
projectId: string
|
||||
projectName: string
|
||||
}
|
||||
|
||||
function ManageTemplateModal({
|
||||
show,
|
||||
handleHide,
|
||||
handleAfterPublished,
|
||||
projectId,
|
||||
projectName,
|
||||
}: ManageTemplateModalProps) {
|
||||
const [inFlight, setInFlight] = useState(false)
|
||||
|
||||
const onHide = useCallback(() => {
|
||||
if (!inFlight) {
|
||||
handleHide()
|
||||
}
|
||||
}, [handleHide, inFlight])
|
||||
|
||||
return (
|
||||
<OLModal
|
||||
size="lg"
|
||||
animation
|
||||
show={show}
|
||||
onHide={onHide}
|
||||
id="publish-template-modal"
|
||||
// backdrop="static" will disable closing the modal by clicking
|
||||
// outside of the modal element
|
||||
backdrop='static'
|
||||
>
|
||||
<ManageTemplateModalContent
|
||||
handleHide={onHide}
|
||||
inFlight={inFlight}
|
||||
setInFlight={setInFlight}
|
||||
handleAfterPublished={handleAfterPublished}
|
||||
projectId={projectId}
|
||||
projectName={projectName}
|
||||
/>
|
||||
</OLModal>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(ManageTemplateModal)
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
import { useCallback, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import getMeta from '@/utils/meta'
|
||||
import { useDetachCompileContext as useCompileContext } from '@/shared/context/detach-compile-context'
|
||||
import { useCommandProvider } from '@/features/ide-react/hooks/use-command-provider'
|
||||
import EditorManageTemplateModalWrapper from './manage-template-modal/editor-manage-template-modal-wrapper'
|
||||
|
||||
type TemplateManageResponse = {
|
||||
template_id: string
|
||||
}
|
||||
|
||||
const MenubarManageTemplate = () => {
|
||||
const { t } = useTranslation()
|
||||
const { pdfUrl } = useCompileContext()
|
||||
|
||||
const [showManageTemplateModal, setShowManageTemplateModal] = useState(false)
|
||||
|
||||
const publishAsTemplateEnabled =
|
||||
getMeta('ol-showTemplatesServerPro') && pdfUrl
|
||||
|
||||
useCommandProvider(
|
||||
() => [
|
||||
{
|
||||
type: 'command',
|
||||
id: 'manage-template',
|
||||
label: t('publish_as_template'),
|
||||
disabled: !publishAsTemplateEnabled,
|
||||
handler: () => {
|
||||
setShowManageTemplateModal(true)
|
||||
},
|
||||
},
|
||||
],
|
||||
[t, publishAsTemplateEnabled]
|
||||
)
|
||||
|
||||
const openTemplate = useCallback(
|
||||
({ template_id: templateId }: TemplateManageResponse) => {
|
||||
location.assign(`/template/${templateId}`)
|
||||
},
|
||||
[]
|
||||
)
|
||||
|
||||
return (
|
||||
<EditorManageTemplateModalWrapper
|
||||
show={showManageTemplateModal}
|
||||
handleHide={() => setShowManageTemplateModal(false)}
|
||||
openTemplate={openTemplate}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export default MenubarManageTemplate
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import withErrorBoundary from '@/infrastructure/error-boundary'
|
||||
import Notification from '@/shared/components/notification'
|
||||
import TemplateActionModal from './template-action-modal'
|
||||
|
||||
type DeleteTemplateModalProps = Pick<
|
||||
React.ComponentProps<typeof TemplateActionModal>,
|
||||
'template' | 'actionHandler' | 'showModal' | 'handleCloseModal'
|
||||
>
|
||||
|
||||
function DeleteTemplateModal({
|
||||
template,
|
||||
actionHandler,
|
||||
showModal,
|
||||
handleCloseModal,
|
||||
}: DeleteTemplateModalProps) {
|
||||
const { t } = useTranslation()
|
||||
|
||||
return (
|
||||
<TemplateActionModal
|
||||
action="delete"
|
||||
actionHandler={actionHandler}
|
||||
title={t('delete_template')}
|
||||
showModal={showModal}
|
||||
handleCloseModal={handleCloseModal}
|
||||
template={template}
|
||||
>
|
||||
<p>{t('about_to_delete_template')}</p>
|
||||
<ul>
|
||||
<li key={`template-action-list-${template.id}`}>
|
||||
<b>{template.name}</b>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<Notification
|
||||
content={t('this_action_cannot_be_undone')}
|
||||
type="warning"
|
||||
/>
|
||||
</TemplateActionModal>
|
||||
)
|
||||
}
|
||||
|
||||
export default withErrorBoundary(DeleteTemplateModal)
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
import React, { useReducer, useState, useEffect, useRef, useCallback, useMemo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import OLForm from '@/shared/components/ol/ol-form'
|
||||
import OLButton from '@/shared/components/ol/ol-button'
|
||||
import withErrorBoundary from '@/infrastructure/error-boundary'
|
||||
import TemplateActionModal from './template-action-modal'
|
||||
import { useTemplateContext } from '../../context/template-context'
|
||||
import TemplateFormFields from '../form/template-form-fields'
|
||||
import type { Template } from '../../../../../../types/template'
|
||||
|
||||
type EditTemplateModalProps = {
|
||||
showModal: boolean
|
||||
handleCloseModal: () => void
|
||||
actionHandler: (editedTemplate: Template) => void | Promise<void>
|
||||
}
|
||||
|
||||
type ActionError = {
|
||||
info?: {
|
||||
statusCode?: number
|
||||
}
|
||||
}
|
||||
|
||||
type TemplateFormAction =
|
||||
| { type: 'UPDATE'; payload: Partial<Template> }
|
||||
| { type: 'RESET'; payload: Template }
|
||||
| { type: 'CLEAR_FIELD'; field: keyof Template }
|
||||
|
||||
function templateFormReducer(state: Template, action: TemplateFormAction): Template {
|
||||
switch (action.type) {
|
||||
case 'UPDATE':
|
||||
return { ...state, ...action.payload }
|
||||
case 'RESET':
|
||||
return { ...action.payload }
|
||||
case 'CLEAR_FIELD':
|
||||
return { ...state, [action.field]: '' }
|
||||
default:
|
||||
return state
|
||||
}
|
||||
}
|
||||
|
||||
function EditTemplateModal({
|
||||
showModal,
|
||||
handleCloseModal,
|
||||
actionHandler,
|
||||
}: EditTemplateModalProps) {
|
||||
const { t } = useTranslation()
|
||||
const { template } = useTemplateContext()
|
||||
|
||||
const [editedTemplate, dispatch] = useReducer(templateFormReducer, template)
|
||||
const [actionError, setActionError] = useState<ActionError | null>(null)
|
||||
const clearModalErrorRef = useRef<() => void>(() => {})
|
||||
|
||||
useEffect(() => {
|
||||
if (showModal) {
|
||||
dispatch({ type: 'RESET', payload: template })
|
||||
setActionError(null)
|
||||
}
|
||||
}, [showModal, template])
|
||||
|
||||
const isConflictError = useMemo(
|
||||
() => actionError?.info?.statusCode === 409,
|
||||
[actionError]
|
||||
)
|
||||
|
||||
const valid = useMemo(
|
||||
() => editedTemplate.name.trim().length > 0,
|
||||
[editedTemplate.name]
|
||||
)
|
||||
|
||||
const handleChange = useCallback(
|
||||
(changes: Partial<Template>) => {
|
||||
dispatch({ type: 'UPDATE', payload: changes })
|
||||
if ('name' in changes && isConflictError) {
|
||||
setActionError(null)
|
||||
clearModalErrorRef.current?.()
|
||||
}
|
||||
},
|
||||
[isConflictError]
|
||||
)
|
||||
|
||||
const handleEnterKey = useCallback(() => {
|
||||
document.getElementById('submit-edit-template')?.click()
|
||||
}, [])
|
||||
|
||||
const handleAction = useCallback(() => {
|
||||
return Promise.resolve(actionHandler(editedTemplate)).catch(err => {
|
||||
setActionError(err)
|
||||
throw err
|
||||
})
|
||||
}, [actionHandler, editedTemplate])
|
||||
|
||||
const submitButtonDisabled = !valid || isConflictError
|
||||
|
||||
return (
|
||||
<TemplateActionModal
|
||||
action="edit"
|
||||
title={t('edit_template')}
|
||||
template={editedTemplate}
|
||||
showModal={showModal}
|
||||
handleCloseModal={handleCloseModal}
|
||||
size="lg"
|
||||
actionHandler={handleAction}
|
||||
renderFooterButtons={({ onConfirm, onCancel, isProcessing }) => (
|
||||
<>
|
||||
<OLButton variant="secondary" onClick={onCancel}>
|
||||
{t('cancel')}
|
||||
</OLButton>
|
||||
<OLButton
|
||||
id="submit-edit-template"
|
||||
onClick={onConfirm}
|
||||
variant="primary"
|
||||
disabled={submitButtonDisabled || isProcessing}
|
||||
>
|
||||
{t('save')}
|
||||
</OLButton>
|
||||
</>
|
||||
)}
|
||||
onClearError={fn => {
|
||||
clearModalErrorRef.current = fn
|
||||
}}
|
||||
>
|
||||
<div className="modal-body-publish">
|
||||
<div className="content-as-table">
|
||||
<OLForm onSubmit={e => e.preventDefault()}>
|
||||
<TemplateFormFields
|
||||
template={editedTemplate}
|
||||
includeLanguage
|
||||
onChange={handleChange}
|
||||
onEnterKey={handleEnterKey}
|
||||
/>
|
||||
</OLForm>
|
||||
</div>
|
||||
</div>
|
||||
</TemplateActionModal>
|
||||
)
|
||||
}
|
||||
|
||||
export default withErrorBoundary(React.memo(EditTemplateModal))
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
import { memo, useEffect, useState, useRef } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { getUserFacingMessage } from '@/infrastructure/fetch-json'
|
||||
import * as eventTracking from '@/infrastructure/event-tracking'
|
||||
import { isSmallDevice } from '@/infrastructure/event-tracking'
|
||||
import useIsMounted from '@/shared/hooks/use-is-mounted'
|
||||
import Notification from '@/shared/components/notification'
|
||||
import OLButton from '@/shared/components/ol/ol-button'
|
||||
import {
|
||||
OLModal,
|
||||
OLModalBody,
|
||||
OLModalFooter,
|
||||
OLModalHeader,
|
||||
OLModalTitle,
|
||||
} from '@/shared/components/ol/ol-modal'
|
||||
import type { Template } from '../../../../../../types/template'
|
||||
import { useFocusTrap } from '../../hooks/use-focus-trap'
|
||||
|
||||
type TemplateActionModalProps = {
|
||||
title: string
|
||||
size?: string
|
||||
action: 'delete' | 'edit'
|
||||
actionHandler: (template: Template) => Promise<void>
|
||||
handleCloseModal: () => void
|
||||
template: Template
|
||||
showModal: boolean
|
||||
children?: React.ReactNode
|
||||
renderFooterButtons?: (props: {
|
||||
onConfirm: () => void
|
||||
onCancel: () => void
|
||||
isProcessing: boolean
|
||||
}) => React.ReactNode
|
||||
onClearError?: (clear: () => void) => void
|
||||
}
|
||||
|
||||
function TemplateActionModal({
|
||||
title,
|
||||
size,
|
||||
action,
|
||||
actionHandler,
|
||||
handleCloseModal,
|
||||
showModal,
|
||||
template,
|
||||
children,
|
||||
renderFooterButtons,
|
||||
onClearError,
|
||||
}: TemplateActionModalProps) {
|
||||
const { t } = useTranslation()
|
||||
const [error, setError] = useState<false | { name: string; error: unknown }>(false)
|
||||
const [isProcessing, setIsProcessing] = useState(false)
|
||||
const isMounted = useIsMounted()
|
||||
const modalRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
useFocusTrap(modalRef, showModal)
|
||||
|
||||
useEffect(() => {
|
||||
if (onClearError) {
|
||||
onClearError(() => setError(false))
|
||||
}
|
||||
}, [onClearError])
|
||||
|
||||
async function handleActionForTemplate(template: Template) {
|
||||
let errored
|
||||
setIsProcessing(true)
|
||||
setError(false)
|
||||
|
||||
try {
|
||||
await actionHandler(template)
|
||||
} catch (e) {
|
||||
errored = { name: template.name, error: e }
|
||||
}
|
||||
|
||||
if (isMounted.current) {
|
||||
setIsProcessing(false)
|
||||
}
|
||||
|
||||
if (!errored) {
|
||||
handleCloseModal()
|
||||
} else {
|
||||
setError(errored)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (showModal) {
|
||||
eventTracking.sendMB('template-info-page-interaction', {
|
||||
action,
|
||||
isSmallDevice,
|
||||
})
|
||||
} else {
|
||||
setError(false)
|
||||
}
|
||||
}, [action, showModal])
|
||||
|
||||
return (
|
||||
<OLModal
|
||||
size={size}
|
||||
show={showModal}
|
||||
onHide={handleCloseModal}
|
||||
id="action-tempate-modal"
|
||||
backdrop="static"
|
||||
>
|
||||
<div ref={modalRef}>
|
||||
<OLModalHeader>
|
||||
<OLModalTitle>{title}</OLModalTitle>
|
||||
</OLModalHeader>
|
||||
|
||||
<OLModalBody>
|
||||
{children}
|
||||
{!isProcessing && error && (
|
||||
<Notification
|
||||
type="error"
|
||||
title={error.name}
|
||||
content={getUserFacingMessage(error.error) as string}
|
||||
/>
|
||||
)}
|
||||
</OLModalBody>
|
||||
|
||||
<OLModalFooter>
|
||||
{renderFooterButtons ? (
|
||||
renderFooterButtons({
|
||||
onConfirm: () => handleActionForTemplate(template),
|
||||
onCancel: handleCloseModal,
|
||||
isProcessing,
|
||||
})
|
||||
) : (
|
||||
<>
|
||||
<OLButton variant="secondary" onClick={handleCloseModal}>
|
||||
{t('cancel')}
|
||||
</OLButton>
|
||||
<OLButton
|
||||
variant="danger"
|
||||
onClick={() => handleActionForTemplate(template)}
|
||||
disabled={isProcessing}
|
||||
>
|
||||
{t('confirm')}
|
||||
</OLButton>
|
||||
</>
|
||||
)}
|
||||
</OLModalFooter>
|
||||
</div>
|
||||
</OLModal>
|
||||
)
|
||||
}
|
||||
|
||||
export default memo(TemplateActionModal)
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
import { useMemo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import getMeta from '@/utils/meta'
|
||||
import SettingsMenuSelect from './settings-menu-select'
|
||||
import type { Optgroup } from './settings-menu-select'
|
||||
|
||||
interface SettingsLanguageProps {
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
}
|
||||
|
||||
export default function SettingsLanguage({
|
||||
value,
|
||||
onChange,
|
||||
}: SettingsLanguageProps) {
|
||||
const { t } = useTranslation()
|
||||
|
||||
const optgroup: Optgroup = useMemo(() => {
|
||||
const options = (getMeta('ol-languages') ?? [])
|
||||
// only include spell-check languages that are available in the client
|
||||
.filter(language => language.dic !== undefined)
|
||||
|
||||
return {
|
||||
label: 'Language',
|
||||
options: options.map(language => ({
|
||||
value: language.code,
|
||||
label: language.name,
|
||||
})),
|
||||
}
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<SettingsMenuSelect
|
||||
onChange={onChange}
|
||||
value={value}
|
||||
options={[{ value: '', label: t('off') }]}
|
||||
optgroup={optgroup}
|
||||
label={t('spell_check')}
|
||||
name="spellCheckLanguage"
|
||||
/>
|
||||
)
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import SettingsMenuSelect from './settings-menu-select'
|
||||
import type { Option } from './settings-menu-select'
|
||||
|
||||
export const licensesMap = {
|
||||
'cc_by_4.0': 'Creative Commons CC BY 4.0',
|
||||
'lppl_1.3c': 'LaTeX Project Public License 1.3c',
|
||||
'other': 'Other (as stated in the work)',
|
||||
}
|
||||
|
||||
interface SettingsLicenseProps {
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
}
|
||||
|
||||
export default function SettingsLicense({
|
||||
value,
|
||||
onChange,
|
||||
}: SettingsLicenseProps) {
|
||||
const { t } = useTranslation()
|
||||
|
||||
const options = Object.entries(licensesMap).map(([value, label]) => ({ value, label }))
|
||||
|
||||
return (
|
||||
<SettingsMenuSelect
|
||||
name="license"
|
||||
label={t('license')}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
options={options}
|
||||
/>
|
||||
)
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
import { ChangeEventHandler, useCallback, useRef, useEffect } from 'react'
|
||||
import OLFormGroup from '@/shared/components/ol/ol-form-group'
|
||||
import OLFormLabel from '@/shared/components/ol/ol-form-label'
|
||||
import OLFormSelect from '@/shared/components/ol/ol-form-select'
|
||||
|
||||
type PossibleValue = string | number | boolean
|
||||
|
||||
export type Option<T extends PossibleValue = string> = {
|
||||
value: T
|
||||
label: string
|
||||
ariaHidden?: 'true' | 'false'
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
export type Optgroup<T extends PossibleValue = string> = {
|
||||
label: string
|
||||
options: Array<Option<T>>
|
||||
}
|
||||
|
||||
type SettingsMenuSelectProps<T extends PossibleValue = string> = {
|
||||
name: string
|
||||
options: Array<Option<T>>
|
||||
optgroup?: Optgroup<T>
|
||||
onChange: (val: T) => void
|
||||
value?: T
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
export default function SettingsMenuSelect<T extends PossibleValue = string>(
|
||||
props: SettingsMenuSelectProps<T>
|
||||
) {
|
||||
|
||||
const { name, options, optgroup, onChange, value, disabled = false } = props
|
||||
const defaultApplied = useRef(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (value === undefined || value === null) {
|
||||
onChange(options?.[0]?.value || optgroup?.options?.[0]?.value)
|
||||
}
|
||||
}, [value, options, onChange])
|
||||
|
||||
const handleChange: ChangeEventHandler<HTMLSelectElement> = useCallback(
|
||||
event => {
|
||||
const selectedValue = event.target.value
|
||||
let onChangeValue: PossibleValue = selectedValue
|
||||
if (typeof value === 'boolean') {
|
||||
onChangeValue = selectedValue === 'true'
|
||||
} else if (typeof value === 'number') {
|
||||
onChangeValue = parseInt(selectedValue, 10)
|
||||
}
|
||||
onChange(onChangeValue as T)
|
||||
},
|
||||
[onChange, value]
|
||||
)
|
||||
const selectRef = useRef<HTMLSelectElement | null>(null)
|
||||
|
||||
return (
|
||||
<>
|
||||
|
||||
<OLFormSelect
|
||||
onChange={handleChange}
|
||||
value={value?.toString()}
|
||||
disabled={disabled}
|
||||
ref={selectRef}
|
||||
>
|
||||
{options.map(option => (
|
||||
<option
|
||||
key={`${name}-${option.value}`}
|
||||
value={option.value.toString()}
|
||||
aria-hidden={option.ariaHidden}
|
||||
disabled={option.disabled}
|
||||
>
|
||||
{option.label}
|
||||
</option>
|
||||
))}
|
||||
{optgroup ? (
|
||||
<optgroup label={optgroup.label}>
|
||||
{optgroup.options.map(option => (
|
||||
<option
|
||||
value={option.value.toString()}
|
||||
key={option.value.toString()}
|
||||
>
|
||||
{option.label}
|
||||
</option>
|
||||
))}
|
||||
</optgroup>
|
||||
) : null}
|
||||
</OLFormSelect>
|
||||
</>
|
||||
)
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
import React, { useMemo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import getMeta from '@/utils/meta'
|
||||
import SettingsMenuSelect from './settings-menu-select'
|
||||
import type { Option } from './settings-menu-select'
|
||||
|
||||
interface SettingsTemplateCategoryProps {
|
||||
value: string
|
||||
onChange: (value: string) => void
|
||||
}
|
||||
|
||||
const SettingsTemplateCategory: React.FC<SettingsTemplateCategoryProps> = ({
|
||||
value,
|
||||
onChange,
|
||||
}) => {
|
||||
const { t } = useTranslation()
|
||||
|
||||
const options: Option[] = useMemo(() => {
|
||||
const { templateLinks = [] } = getMeta('ol-ExposedSettings') as {
|
||||
templateLinks?: Array<{ name: string; url: string; description: string }>
|
||||
}
|
||||
|
||||
return templateLinks.map(({ name, url }) => ({
|
||||
value: url,
|
||||
label: name,
|
||||
}))
|
||||
}, [])
|
||||
|
||||
if (options.length === 0) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<SettingsMenuSelect
|
||||
name="category"
|
||||
label={`${t('category')}:`}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
options={options}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export default React.memo(SettingsTemplateCategory)
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import getMeta from '@/utils/meta'
|
||||
import OLCol from '@/shared/components/ol/ol-col'
|
||||
import OLRow from '@/shared/components/ol/ol-row'
|
||||
import OLTooltip from '@/shared/components/ol/ol-tooltip'
|
||||
import { formatDate, fromNowDate } from '@/utils/dates'
|
||||
import { cleanHtml } from '../../../../../app/src/CleanHtml.mjs'
|
||||
import { useTemplateContext } from '../context/template-context'
|
||||
import DeleteTemplateButton from './delete-template-button'
|
||||
import EditTemplateButton from './edit-template-button'
|
||||
import { licensesMap } from './settings/settings-license'
|
||||
|
||||
function TemplateDetails() {
|
||||
const { t } = useTranslation()
|
||||
const { template } = useTemplateContext()
|
||||
const lastUpdatedDate = fromNowDate(template.lastUpdated)
|
||||
const tooltipText = formatDate(template.lastUpdated)
|
||||
const loggedInUserId = getMeta('ol-user_id')
|
||||
const loggedInUserCanManageTemplates = getMeta('ol-userIsAdmin')
|
||||
|| getMeta('ol-userIsTemplatesManager')
|
||||
|
||||
const openAsTemplateParams = new URLSearchParams({
|
||||
id: template.version,
|
||||
...(template.brandVariationId && { brandVariationId: template.brandVariationId }),
|
||||
templateName: template.name,
|
||||
latexEngine: template.compiler,
|
||||
mainFile: template.mainFile,
|
||||
language: template.language,
|
||||
...(template.imageName && { texImage: template.imageName })
|
||||
}).toString()
|
||||
|
||||
const sanitizedAuthor = cleanHtml(template.author, 'linksOnly') || t('anonymous')
|
||||
const sanitizedDescription = cleanHtml(template.description, 'reachText')
|
||||
|
||||
const languageName = getMeta('ol-languages')?.find(({ code }) => code === template.language)?.name
|
||||
|
||||
return (
|
||||
<>
|
||||
<OLRow>
|
||||
<OLCol md={12}>
|
||||
<div className={"gallery-item-title"}>
|
||||
<h1 className="h2">{template.name}</h1>
|
||||
</div>
|
||||
</OLCol>
|
||||
</OLRow>
|
||||
<OLRow className="cta-links-container">
|
||||
<OLCol md={12} className="cta-links">
|
||||
<a className="btn btn-primary cta-link" href={`/project/new/template/${template.id}?${openAsTemplateParams}`}>{t('open_as_template')}</a>
|
||||
<a className="btn btn-secondary cta-link" href={`/template/${template.id}/preview?version=${template.version}`}>{t('view_pdf')}</a>
|
||||
</OLCol>
|
||||
</OLRow>
|
||||
<div className="template-details-container">
|
||||
<div className="template-detail">
|
||||
<div>
|
||||
<b>{t('author')}:</b>
|
||||
</div>
|
||||
<div dangerouslySetInnerHTML={{ __html: sanitizedAuthor }} />
|
||||
</div>
|
||||
<div className="template-detail">
|
||||
<div>
|
||||
<b>{t('last_updated')}:</b>
|
||||
</div>
|
||||
<div>
|
||||
<OLTooltip
|
||||
id={`${template.id}`}
|
||||
description={tooltipText}
|
||||
overlayProps={{ placement: 'bottom', trigger: ['hover', 'focus'] }}
|
||||
>
|
||||
<span>
|
||||
{lastUpdatedDate.trim()}
|
||||
</span>
|
||||
</OLTooltip>
|
||||
</div>
|
||||
</div>
|
||||
{languageName && (
|
||||
<div className="template-detail">
|
||||
<div>
|
||||
<b>{t('language')}:</b>
|
||||
</div>
|
||||
<div>
|
||||
{languageName}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="template-detail">
|
||||
<div>
|
||||
<b>{t('license')}:</b>
|
||||
</div>
|
||||
<div>
|
||||
{licensesMap[template.license]}
|
||||
</div>
|
||||
</div>
|
||||
{sanitizedDescription && (
|
||||
<div className="template-detail">
|
||||
<div>
|
||||
<b>{t('abstract')}:</b>
|
||||
</div>
|
||||
<div
|
||||
className="gallery-abstract"
|
||||
data-ol-mathjax=""
|
||||
dangerouslySetInnerHTML={{ __html: sanitizedDescription }}>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{loggedInUserId && (loggedInUserId === template.owner || loggedInUserCanManageTemplates) && (
|
||||
<OLRow className="cta-links-container">
|
||||
<OLCol md={12} className="text-end">
|
||||
<EditTemplateButton />
|
||||
<DeleteTemplateButton />
|
||||
</OLCol>
|
||||
</OLRow>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
export default TemplateDetails
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
import OLCol from '@/shared/components/ol/ol-col'
|
||||
import OLRow from '@/shared/components/ol/ol-row'
|
||||
import { useTemplateContext } from '../context/template-context'
|
||||
|
||||
|
||||
function TemplatePreview() {
|
||||
const { template, setTemplate } = useTemplateContext()
|
||||
return (
|
||||
<div className="entry">
|
||||
<OLRow>
|
||||
<OLCol md={12}>
|
||||
<div className="gallery-large-pdf-preview">
|
||||
<img
|
||||
src={`/template/${template.id}/preview?version=${template.version}&style=preview`}
|
||||
alt={template.name}
|
||||
/>
|
||||
</div>
|
||||
</OLCol>
|
||||
</OLRow>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export default TemplatePreview
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import useWaitForI18n from '@/shared/hooks/use-wait-for-i18n'
|
||||
import withErrorBoundary from '@/infrastructure/error-boundary'
|
||||
import { GenericErrorBoundaryFallback } from '@/shared/components/generic-error-boundary-fallback'
|
||||
import DefaultNavbar from '@/shared/components/navbar/default-navbar'
|
||||
import Footer from '@/shared/components/footer/footer'
|
||||
import getMeta from '@/utils/meta'
|
||||
import OLCol from '@/shared/components/ol/ol-col'
|
||||
import OLRow from '@/shared/components/ol/ol-row'
|
||||
import TemplateDetails from './template-details'
|
||||
import TemplatePreview from './template-preview'
|
||||
import { useTemplateContext, TemplateProvider } from '../context/template-context'
|
||||
|
||||
function TemplateRoot() {
|
||||
const { isReady } = useWaitForI18n()
|
||||
if (!isReady) {
|
||||
return null
|
||||
}
|
||||
return (
|
||||
<TemplateProvider>
|
||||
<TemplatePageContent />
|
||||
</TemplateProvider>
|
||||
)
|
||||
}
|
||||
|
||||
function TemplatePageContent() {
|
||||
const { t } = useTranslation()
|
||||
const navbarProps = getMeta('ol-navbar')
|
||||
const footerProps = getMeta('ol-footer')
|
||||
const { template } = useTemplateContext()
|
||||
const { templateLinks } = getMeta('ol-ExposedSettings') || []
|
||||
const categoryName = templateLinks?.find(link => link.url === template.category)?.name
|
||||
|
||||
return (
|
||||
<>
|
||||
<DefaultNavbar {...navbarProps} />
|
||||
<main id="main-content" className="gallery content content-page">
|
||||
<div className="container">
|
||||
<OLRow className="previous-page-link-container">
|
||||
<OLCol lg={6}>
|
||||
<a className="previous-page-link" href={'/templates/all'}>
|
||||
<i className="material-symbols material-symbols-rounded" aria-hidden="true">arrow_left_alt</i>
|
||||
{t('all_templates')}
|
||||
</a>
|
||||
{categoryName && template.category !== '/templates/all' && (
|
||||
<>
|
||||
<span className="mx-2">/</span>
|
||||
<a className="previous-page-link" href={template.category}>
|
||||
{categoryName}
|
||||
</a>
|
||||
</>
|
||||
)}
|
||||
</OLCol>
|
||||
</OLRow>
|
||||
<OLRow>
|
||||
<OLCol className="template-item-left-section" md={6}>
|
||||
<TemplateDetails />
|
||||
</OLCol>
|
||||
<OLCol className="template-item-right-section" md={6}>
|
||||
<TemplatePreview />
|
||||
</OLCol>
|
||||
</OLRow>
|
||||
</div>
|
||||
</main>
|
||||
<Footer {...footerProps} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default withErrorBoundary(TemplateRoot, GenericErrorBoundaryFallback)
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
import {
|
||||
createContext,
|
||||
FC,
|
||||
useCallback,
|
||||
useContext,
|
||||
useState,
|
||||
useMemo,
|
||||
} from 'react'
|
||||
import useEventListener from '@/shared/hooks/use-event-listener'
|
||||
import getMeta from '@/utils/meta'
|
||||
import { Template } from '../../../../../types/template'
|
||||
|
||||
type TemplateContextType = {
|
||||
template: Template
|
||||
setTemplate: (template: Template) => void
|
||||
}
|
||||
|
||||
export const TemplateContext = createContext<TemplateContextType | undefined>(
|
||||
undefined
|
||||
)
|
||||
|
||||
type TemplateProviderProps = {
|
||||
loadedTemplate: Template
|
||||
}
|
||||
|
||||
export const TemplateProvider: FC<TemplateProviderProps> = ({ children }) => {
|
||||
const loadedTemplate = useMemo(() => getMeta('ol-template'), [])
|
||||
const [template, setTemplate] = useState(loadedTemplate)
|
||||
|
||||
const value = useMemo(
|
||||
() => ({
|
||||
template,
|
||||
setTemplate,
|
||||
}),
|
||||
[template, setTemplate]
|
||||
)
|
||||
|
||||
return (
|
||||
<TemplateContext.Provider value={value}>
|
||||
{children}
|
||||
</TemplateContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export const useTemplateContext = () => {
|
||||
const context = useContext(TemplateContext)
|
||||
if (!context) {
|
||||
throw new Error(
|
||||
`useTemplateContext must be used within a TemplateProvider`
|
||||
)
|
||||
}
|
||||
return context
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
import { useEffect } from 'react'
|
||||
|
||||
export function useFocusTrap(ref: React.RefObject<HTMLElement>, enabled = true) {
|
||||
useEffect(() => {
|
||||
if (!enabled || !ref.current) return
|
||||
|
||||
const element = ref.current
|
||||
const previouslyFocusedElement = document.activeElement as HTMLElement
|
||||
const focusableElements = element.querySelectorAll<HTMLElement>(
|
||||
'a[href], button, textarea, input, select, [tabindex]:not([tabindex="-1"])'
|
||||
)
|
||||
|
||||
const firstElement = focusableElements[0]
|
||||
const lastElement = focusableElements[focusableElements.length - 1]
|
||||
|
||||
// Don't override if something inside already received focus
|
||||
const isAlreadyFocusedInside = element.contains(document.activeElement)
|
||||
|
||||
function handleKeyDown(e: KeyboardEvent) {
|
||||
if (e.key !== 'Tab') return
|
||||
|
||||
if (e.shiftKey) {
|
||||
if (document.activeElement === firstElement) {
|
||||
e.preventDefault()
|
||||
lastElement?.focus()
|
||||
}
|
||||
} else {
|
||||
if (document.activeElement === lastElement) {
|
||||
e.preventDefault()
|
||||
firstElement?.focus()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
element.addEventListener('keydown', handleKeyDown)
|
||||
|
||||
if (!isAlreadyFocusedInside) {
|
||||
firstElement?.focus()
|
||||
}
|
||||
|
||||
return () => {
|
||||
element.removeEventListener('keydown', handleKeyDown)
|
||||
previouslyFocusedElement?.focus()
|
||||
}
|
||||
}, [ref, enabled])
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { deleteJSON, postJSON } from '@/infrastructure/fetch-json'
|
||||
import { Template } from '../../../../../types/template'
|
||||
|
||||
export function deleteTemplate(template: Template) {
|
||||
return deleteJSON(`/template/${template.id}/delete`, {
|
||||
body: {
|
||||
version: template.version,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
type UpdateTemplateOptions = {
|
||||
template: Template
|
||||
editedTemplate: Template
|
||||
}
|
||||
|
||||
export function updateTemplate({
|
||||
template,
|
||||
editedTemplate
|
||||
}: UpdateTemplateOptions): Promise<Template | null> {
|
||||
const updatedFields: Partial<Template> = {
|
||||
name: editedTemplate.name.trim(),
|
||||
license: editedTemplate.license,
|
||||
category: editedTemplate.category,
|
||||
language: editedTemplate.language,
|
||||
authorMD: editedTemplate.authorMD.trim(),
|
||||
descriptionMD: editedTemplate.descriptionMD.trim(),
|
||||
}
|
||||
|
||||
const changedFields = Object.entries(updatedFields).reduce((diff, [key, value]) => {
|
||||
if (value !== undefined && template[key as keyof Template] !== value) {
|
||||
diff[key] = value
|
||||
}
|
||||
return diff
|
||||
}, {} as Partial<Template>)
|
||||
|
||||
if (Object.keys(changedFields).length === 0) {
|
||||
return Promise.resolve(null)
|
||||
}
|
||||
|
||||
return postJSON(`/template/${editedTemplate.id}/edit`, {
|
||||
body: changedFields
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import ReactDOM from 'react-dom/client'
|
||||
import TemplateGalleryRoot from '../features/template-gallery/components/template-gallery-root'
|
||||
|
||||
const element = document.getElementById('template-gallery-root')
|
||||
if (element) {
|
||||
const root = ReactDOM.createRoot(element)
|
||||
root.render(<TemplateGalleryRoot />)
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import ReactDOM from 'react-dom/client'
|
||||
import TemplateRoot from '../features/template/components/template-root'
|
||||
|
||||
const element = document.getElementById('template-root')
|
||||
if (element) {
|
||||
const root = ReactDOM.createRoot(element)
|
||||
root.render(<TemplateRoot />)
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import Settings from '@overleaf/settings'
|
||||
import TemplateGalleryRouter from './app/src/TemplateGalleryRouter.mjs'
|
||||
|
||||
function boolFromEnv(env) {
|
||||
if (env === undefined || env === null) return undefined
|
||||
if (typeof env === "string") {
|
||||
const envLower = env.toLowerCase()
|
||||
if (envLower === 'true') return true
|
||||
if (envLower === 'false') return false
|
||||
}
|
||||
throw new Error("Invalid value for boolean environment variable")
|
||||
}
|
||||
|
||||
let TemplateGalleryModule = {}
|
||||
|
||||
if (process.env.OVERLEAF_TEMPLATE_GALLERY === 'true') {
|
||||
TemplateGalleryModule = {
|
||||
router: TemplateGalleryRouter,
|
||||
}
|
||||
|
||||
Settings.templates = {
|
||||
nonAdminCanManage: boolFromEnv(process.env.OVERLEAF_NON_ADMIN_CAN_PUBLISH_TEMPLATES),
|
||||
user_id: process.env.OVERLEAF_TEMPLATES_USER_ID
|
||||
}
|
||||
|
||||
const templateKeys = process.env.OVERLEAF_TEMPLATE_CATEGORIES
|
||||
? process.env.OVERLEAF_TEMPLATE_CATEGORIES + ' all'
|
||||
: 'all'
|
||||
|
||||
Settings.templateLinks = templateKeys.split(/\s+/).map(key => {
|
||||
const envKeyBase = key.toUpperCase().replace(/-/g, "_")
|
||||
const name = process.env[`TEMPLATE_${envKeyBase}_NAME`] || ( key === 'all' ? 'All templates' : key)
|
||||
const description = process.env[`TEMPLATE_${envKeyBase}_DESCRIPTION`] || ''
|
||||
|
||||
return {
|
||||
name,
|
||||
url: `/templates/${key}`,
|
||||
description
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export default TemplateGalleryModule
|
||||
@@ -0,0 +1,16 @@
|
||||
export type Template = {
|
||||
id: string
|
||||
version: number
|
||||
name: string
|
||||
lastUpdated: Date
|
||||
author: string
|
||||
authorMD: string
|
||||
description: string
|
||||
descriptionMD: string
|
||||
license: string
|
||||
category: string
|
||||
compiler?: string
|
||||
language?: string
|
||||
owner: string
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user