Compare commits
26
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7eafe68e58 | ||
|
|
b54beaa66b | ||
|
|
e542f4bc61 | ||
|
|
a339f71116 | ||
|
|
b695e3900e | ||
|
|
2158ee4db6 | ||
|
|
3090a85726 | ||
|
|
d714a1617f | ||
|
|
2a29bda34f | ||
|
|
ab6edd3196 | ||
|
|
be7e79be55 | ||
|
|
c9e1b8eec5 | ||
|
|
eba93a3b6c | ||
|
|
03e81a0f16 | ||
|
|
f9ac1bd62e | ||
|
|
8aa6aff53a | ||
|
|
458bb641b5 | ||
|
|
247f82b5a7 | ||
|
|
06b4c147bd | ||
|
|
25154e4dbe | ||
|
|
989eea9e24 | ||
|
|
510e1c38eb | ||
|
|
ec05c5c049 | ||
|
|
d86a13cc89 | ||
|
|
85dedf4b28 | ||
|
|
0fa53185f2 |
@@ -192,6 +192,11 @@ return useToolOperation({
|
|||||||
- **Preview System**: Tool results can be previewed without polluting file context (Split tool example)
|
- **Preview System**: Tool results can be previewed without polluting file context (Split tool example)
|
||||||
- **Performance**: Web Worker thumbnails, IndexedDB persistence, background processing
|
- **Performance**: Web Worker thumbnails, IndexedDB persistence, background processing
|
||||||
|
|
||||||
|
## Translation Rules
|
||||||
|
|
||||||
|
- **CRITICAL**: Always update translations in `en-GB` only, never `en-US`
|
||||||
|
- Translation files are located in `frontend/public/locales/`
|
||||||
|
|
||||||
## Important Notes
|
## Important Notes
|
||||||
|
|
||||||
- **Java Version**: Minimum JDK 17, supports and recommends JDK 21
|
- **Java Version**: Minimum JDK 17, supports and recommends JDK 21
|
||||||
|
|||||||
@@ -115,46 +115,46 @@ Stirling-PDF currently supports 40 languages!
|
|||||||
|
|
||||||
| Language | Progress |
|
| Language | Progress |
|
||||||
| -------------------------------------------- | -------------------------------------- |
|
| -------------------------------------------- | -------------------------------------- |
|
||||||
| Arabic (العربية) (ar_AR) |  |
|
| Arabic (العربية) (ar_AR) |  |
|
||||||
| Azerbaijani (Azərbaycan Dili) (az_AZ) |  |
|
| Azerbaijani (Azərbaycan Dili) (az_AZ) |  |
|
||||||
| Basque (Euskara) (eu_ES) |  |
|
| Basque (Euskara) (eu_ES) |  |
|
||||||
| Bulgarian (Български) (bg_BG) |  |
|
| Bulgarian (Български) (bg_BG) |  |
|
||||||
| Catalan (Català) (ca_CA) |  |
|
| Catalan (Català) (ca_CA) |  |
|
||||||
| Croatian (Hrvatski) (hr_HR) |  |
|
| Croatian (Hrvatski) (hr_HR) |  |
|
||||||
| Czech (Česky) (cs_CZ) |  |
|
| Czech (Česky) (cs_CZ) |  |
|
||||||
| Danish (Dansk) (da_DK) |  |
|
| Danish (Dansk) (da_DK) |  |
|
||||||
| Dutch (Nederlands) (nl_NL) |  |
|
| Dutch (Nederlands) (nl_NL) |  |
|
||||||
| English (English) (en_GB) |  |
|
| English (English) (en_GB) |  |
|
||||||
| English (US) (en_US) |  |
|
| English (US) (en_US) |  |
|
||||||
| French (Français) (fr_FR) |  |
|
| French (Français) (fr_FR) |  |
|
||||||
| German (Deutsch) (de_DE) |  |
|
| German (Deutsch) (de_DE) |  |
|
||||||
| Greek (Ελληνικά) (el_GR) |  |
|
| Greek (Ελληνικά) (el_GR) |  |
|
||||||
| Hindi (हिंदी) (hi_IN) |  |
|
| Hindi (हिंदी) (hi_IN) |  |
|
||||||
| Hungarian (Magyar) (hu_HU) |  |
|
| Hungarian (Magyar) (hu_HU) |  |
|
||||||
| Indonesian (Bahasa Indonesia) (id_ID) |  |
|
| Indonesian (Bahasa Indonesia) (id_ID) |  |
|
||||||
| Irish (Gaeilge) (ga_IE) |  |
|
| Irish (Gaeilge) (ga_IE) |  |
|
||||||
| Italian (Italiano) (it_IT) |  |
|
| Italian (Italiano) (it_IT) |  |
|
||||||
| Japanese (日本語) (ja_JP) |  |
|
| Japanese (日本語) (ja_JP) |  |
|
||||||
| Korean (한국어) (ko_KR) |  |
|
| Korean (한국어) (ko_KR) |  |
|
||||||
| Norwegian (Norsk) (no_NB) |  |
|
| Norwegian (Norsk) (no_NB) |  |
|
||||||
| Persian (فارسی) (fa_IR) |  |
|
| Persian (فارسی) (fa_IR) |  |
|
||||||
| Polish (Polski) (pl_PL) |  |
|
| Polish (Polski) (pl_PL) |  |
|
||||||
| Portuguese (Português) (pt_PT) |  |
|
| Portuguese (Português) (pt_PT) |  |
|
||||||
| Portuguese Brazilian (Português) (pt_BR) |  |
|
| Portuguese Brazilian (Português) (pt_BR) |  |
|
||||||
| Romanian (Română) (ro_RO) |  |
|
| Romanian (Română) (ro_RO) |  |
|
||||||
| Russian (Русский) (ru_RU) |  |
|
| Russian (Русский) (ru_RU) |  |
|
||||||
| Serbian Latin alphabet (Srpski) (sr_LATN_RS) |  |
|
| Serbian Latin alphabet (Srpski) (sr_LATN_RS) |  |
|
||||||
| Simplified Chinese (简体中文) (zh_CN) |  |
|
| Simplified Chinese (简体中文) (zh_CN) |  |
|
||||||
| Slovakian (Slovensky) (sk_SK) |  |
|
| Slovakian (Slovensky) (sk_SK) |  |
|
||||||
| Slovenian (Slovenščina) (sl_SI) |  |
|
| Slovenian (Slovenščina) (sl_SI) |  |
|
||||||
| Spanish (Español) (es_ES) |  |
|
| Spanish (Español) (es_ES) |  |
|
||||||
| Swedish (Svenska) (sv_SE) |  |
|
| Swedish (Svenska) (sv_SE) |  |
|
||||||
| Thai (ไทย) (th_TH) |  |
|
| Thai (ไทย) (th_TH) |  |
|
||||||
| Tibetan (བོད་ཡིག་) (bo_CN) |  |
|
| Tibetan (བོད་ཡིག་) (bo_CN) |  |
|
||||||
| Traditional Chinese (繁體中文) (zh_TW) |  |
|
| Traditional Chinese (繁體中文) (zh_TW) |  |
|
||||||
| Turkish (Türkçe) (tr_TR) |  |
|
| Turkish (Türkçe) (tr_TR) |  |
|
||||||
| Ukrainian (Українська) (uk_UA) |  |
|
| Ukrainian (Українська) (uk_UA) |  |
|
||||||
| Vietnamese (Tiếng Việt) (vi_VN) |  |
|
| Vietnamese (Tiếng Việt) (vi_VN) |  |
|
||||||
| Malayalam (മലയാളം) (ml_IN) |  |
|
| Malayalam (മലയാളം) (ml_IN) |  |
|
||||||
|
|
||||||
## Stirling PDF Enterprise
|
## Stirling PDF Enterprise
|
||||||
|
|||||||
@@ -87,7 +87,8 @@ public class AutoJobAspect {
|
|||||||
},
|
},
|
||||||
timeout,
|
timeout,
|
||||||
queueable,
|
queueable,
|
||||||
resourceWeight);
|
resourceWeight,
|
||||||
|
trackProgress);
|
||||||
} else {
|
} else {
|
||||||
// Use retry logic
|
// Use retry logic
|
||||||
return executeWithRetries(
|
return executeWithRetries(
|
||||||
@@ -220,7 +221,8 @@ public class AutoJobAspect {
|
|||||||
},
|
},
|
||||||
timeout,
|
timeout,
|
||||||
queueable,
|
queueable,
|
||||||
resourceWeight);
|
resourceWeight,
|
||||||
|
trackProgress);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -258,12 +258,6 @@ public class AppConfig {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Bean(name = "GoogleDriveEnabled")
|
|
||||||
@Profile("default")
|
|
||||||
public boolean googleDriveEnabled() {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Bean(name = "license")
|
@Bean(name = "license")
|
||||||
@Profile("default")
|
@Profile("default")
|
||||||
public String licenseType() {
|
public String licenseType() {
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package stirling.software.common.context;
|
||||||
|
|
||||||
|
import lombok.AccessLevel;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Holds contextual information for the currently executing job. Backed by a {@link ThreadLocal} so
|
||||||
|
* worker threads can retrieve the job ID and progress tracking preference while processing
|
||||||
|
* asynchronous work dispatched by {@link stirling.software.common.service.JobExecutorService
|
||||||
|
* JobExecutorService}.
|
||||||
|
*/
|
||||||
|
@NoArgsConstructor(access = AccessLevel.PRIVATE)
|
||||||
|
public final class JobContextHolder {
|
||||||
|
|
||||||
|
private static final ThreadLocal<String> JOB_ID = new ThreadLocal<>();
|
||||||
|
private static final ThreadLocal<Boolean> PROGRESS_ENABLED = new ThreadLocal<>();
|
||||||
|
|
||||||
|
/** Store context for the current thread. */
|
||||||
|
public static void setContext(String jobId, boolean progressEnabled) {
|
||||||
|
if (jobId == null) {
|
||||||
|
clear();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
JOB_ID.set(jobId);
|
||||||
|
PROGRESS_ENABLED.set(progressEnabled);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get the job ID bound to the current thread, or {@code null} if none. */
|
||||||
|
public static String getJobId() {
|
||||||
|
return JOB_ID.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether progress tracking is enabled for the current job (defaults to {@code false}). */
|
||||||
|
public static boolean isProgressEnabled() {
|
||||||
|
Boolean enabled = PROGRESS_ENABLED.get();
|
||||||
|
return enabled != null && enabled;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Remove all context associated with the current thread. */
|
||||||
|
public static void clear() {
|
||||||
|
JOB_ID.remove();
|
||||||
|
PROGRESS_ENABLED.remove();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -530,7 +530,6 @@ public class ApplicationProperties {
|
|||||||
private boolean ssoAutoLogin;
|
private boolean ssoAutoLogin;
|
||||||
private boolean database;
|
private boolean database;
|
||||||
private CustomMetadata customMetadata = new CustomMetadata();
|
private CustomMetadata customMetadata = new CustomMetadata();
|
||||||
private GoogleDrive googleDrive = new GoogleDrive();
|
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
public static class CustomMetadata {
|
public static class CustomMetadata {
|
||||||
@@ -549,26 +548,6 @@ public class ApplicationProperties {
|
|||||||
: producer;
|
: producer;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Data
|
|
||||||
public static class GoogleDrive {
|
|
||||||
private boolean enabled;
|
|
||||||
private String clientId;
|
|
||||||
private String apiKey;
|
|
||||||
private String appId;
|
|
||||||
|
|
||||||
public String getClientId() {
|
|
||||||
return clientId == null || clientId.trim().isEmpty() ? "" : clientId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getApiKey() {
|
|
||||||
return apiKey == null || apiKey.trim().isEmpty() ? "" : apiKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getAppId() {
|
|
||||||
return appId == null || appId.trim().isEmpty() ? "" : appId;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
|
|||||||
@@ -41,6 +41,18 @@ public class JobResult {
|
|||||||
/** The actual result object, if not a file */
|
/** The actual result object, if not a file */
|
||||||
private Object result;
|
private Object result;
|
||||||
|
|
||||||
|
/** Whether detailed progress tracking is enabled for this job. */
|
||||||
|
@Builder.Default private boolean trackProgress = true;
|
||||||
|
|
||||||
|
/** Most recent percentage update (0-100) if progress tracking is enabled. */
|
||||||
|
private Integer progressPercent;
|
||||||
|
|
||||||
|
/** Human readable progress message (e.g. current stage) when progress is enabled. */
|
||||||
|
private String progressMessage;
|
||||||
|
|
||||||
|
/** Timestamp of the last progress update. */
|
||||||
|
private LocalDateTime progressUpdatedAt;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Notes attached to this job for tracking purposes. Uses CopyOnWriteArrayList for thread safety
|
* Notes attached to this job for tracking purposes. Uses CopyOnWriteArrayList for thread safety
|
||||||
* when notes are added concurrently.
|
* when notes are added concurrently.
|
||||||
@@ -54,11 +66,28 @@ public class JobResult {
|
|||||||
* @return A new JobResult
|
* @return A new JobResult
|
||||||
*/
|
*/
|
||||||
public static JobResult createNew(String jobId) {
|
public static JobResult createNew(String jobId) {
|
||||||
return JobResult.builder()
|
return createNew(jobId, true);
|
||||||
.jobId(jobId)
|
}
|
||||||
.complete(false)
|
|
||||||
.createdAt(LocalDateTime.now())
|
/**
|
||||||
.build();
|
* Create a new JobResult with the given job ID and progress tracking preference.
|
||||||
|
*
|
||||||
|
* @param jobId The job ID
|
||||||
|
* @param trackProgress Whether detailed progress should be tracked
|
||||||
|
* @return A new JobResult
|
||||||
|
*/
|
||||||
|
public static JobResult createNew(String jobId, boolean trackProgress) {
|
||||||
|
JobResult result =
|
||||||
|
JobResult.builder()
|
||||||
|
.jobId(jobId)
|
||||||
|
.complete(false)
|
||||||
|
.createdAt(LocalDateTime.now())
|
||||||
|
.trackProgress(trackProgress)
|
||||||
|
.build();
|
||||||
|
if (trackProgress) {
|
||||||
|
result.updateProgressInternal(0, "Pending");
|
||||||
|
}
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -70,6 +99,9 @@ public class JobResult {
|
|||||||
this.complete = true;
|
this.complete = true;
|
||||||
this.result = result;
|
this.result = result;
|
||||||
this.completedAt = LocalDateTime.now();
|
this.completedAt = LocalDateTime.now();
|
||||||
|
if (trackProgress) {
|
||||||
|
updateProgressInternal(100, "Completed");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -81,6 +113,9 @@ public class JobResult {
|
|||||||
this.complete = true;
|
this.complete = true;
|
||||||
this.error = error;
|
this.error = error;
|
||||||
this.completedAt = LocalDateTime.now();
|
this.completedAt = LocalDateTime.now();
|
||||||
|
if (trackProgress) {
|
||||||
|
updateProgressInternal(100, error != null ? error : "Failed");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -92,6 +127,9 @@ public class JobResult {
|
|||||||
this.complete = true;
|
this.complete = true;
|
||||||
this.resultFiles = new ArrayList<>(resultFiles);
|
this.resultFiles = new ArrayList<>(resultFiles);
|
||||||
this.completedAt = LocalDateTime.now();
|
this.completedAt = LocalDateTime.now();
|
||||||
|
if (trackProgress) {
|
||||||
|
updateProgressInternal(100, "Completed");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -161,4 +199,26 @@ public class JobResult {
|
|||||||
public List<String> getNotes() {
|
public List<String> getNotes() {
|
||||||
return Collections.unmodifiableList(notes);
|
return Collections.unmodifiableList(notes);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update the progress information if tracking is enabled.
|
||||||
|
*
|
||||||
|
* @param percent The percent complete (0-100)
|
||||||
|
* @param message Optional descriptive message
|
||||||
|
*/
|
||||||
|
public void updateProgress(int percent, String message) {
|
||||||
|
if (!trackProgress) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
updateProgressInternal(percent, message);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void updateProgressInternal(int percent, String message) {
|
||||||
|
int clamped = Math.min(100, Math.max(0, percent));
|
||||||
|
this.progressPercent = clamped;
|
||||||
|
if (message != null && !message.isBlank()) {
|
||||||
|
this.progressMessage = message;
|
||||||
|
}
|
||||||
|
this.progressUpdatedAt = LocalDateTime.now();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+120
-24
@@ -20,6 +20,7 @@ import jakarta.servlet.http.HttpServletRequest;
|
|||||||
|
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
|
||||||
|
import stirling.software.common.context.JobContextHolder;
|
||||||
import stirling.software.common.model.job.JobResponse;
|
import stirling.software.common.model.job.JobResponse;
|
||||||
import stirling.software.common.util.ExecutorFactory;
|
import stirling.software.common.util.ExecutorFactory;
|
||||||
|
|
||||||
@@ -65,7 +66,7 @@ public class JobExecutorService {
|
|||||||
* @return The response
|
* @return The response
|
||||||
*/
|
*/
|
||||||
public ResponseEntity<?> runJobGeneric(boolean async, Supplier<Object> work) {
|
public ResponseEntity<?> runJobGeneric(boolean async, Supplier<Object> work) {
|
||||||
return runJobGeneric(async, work, -1);
|
return runJobGeneric(async, work, -1, false, 50, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -78,7 +79,7 @@ public class JobExecutorService {
|
|||||||
*/
|
*/
|
||||||
public ResponseEntity<?> runJobGeneric(
|
public ResponseEntity<?> runJobGeneric(
|
||||||
boolean async, Supplier<Object> work, long customTimeoutMs) {
|
boolean async, Supplier<Object> work, long customTimeoutMs) {
|
||||||
return runJobGeneric(async, work, customTimeoutMs, false, 50);
|
return runJobGeneric(async, work, customTimeoutMs, false, 50, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -96,7 +97,8 @@ public class JobExecutorService {
|
|||||||
Supplier<Object> work,
|
Supplier<Object> work,
|
||||||
long customTimeoutMs,
|
long customTimeoutMs,
|
||||||
boolean queueable,
|
boolean queueable,
|
||||||
int resourceWeight) {
|
int resourceWeight,
|
||||||
|
boolean trackProgress) {
|
||||||
String jobId = UUID.randomUUID().toString();
|
String jobId = UUID.randomUUID().toString();
|
||||||
|
|
||||||
// Store the job ID in the request for potential use by other components
|
// Store the job ID in the request for potential use by other components
|
||||||
@@ -138,6 +140,8 @@ public class JobExecutorService {
|
|||||||
&& // Only async jobs can be queued
|
&& // Only async jobs can be queued
|
||||||
resourceMonitor.shouldQueueJob(resourceWeight);
|
resourceMonitor.shouldQueueJob(resourceWeight);
|
||||||
|
|
||||||
|
boolean enableProgress = async && trackProgress;
|
||||||
|
|
||||||
if (shouldQueue) {
|
if (shouldQueue) {
|
||||||
// Queue the job instead of executing immediately
|
// Queue the job instead of executing immediately
|
||||||
log.debug(
|
log.debug(
|
||||||
@@ -145,13 +149,18 @@ public class JobExecutorService {
|
|||||||
jobId,
|
jobId,
|
||||||
resourceWeight);
|
resourceWeight);
|
||||||
|
|
||||||
taskManager.createTask(jobId);
|
taskManager.createTask(jobId, trackProgress);
|
||||||
|
|
||||||
|
Supplier<Object> contextualWork = withJobContext(jobId, enableProgress, work);
|
||||||
|
|
||||||
// Create a specialized wrapper that updates the TaskManager
|
// Create a specialized wrapper that updates the TaskManager
|
||||||
Supplier<Object> wrappedWork =
|
Supplier<Object> wrappedWork =
|
||||||
() -> {
|
() -> {
|
||||||
try {
|
try {
|
||||||
Object result = work.get();
|
if (enableProgress) {
|
||||||
|
taskManager.updateProgress(jobId, 5, null);
|
||||||
|
}
|
||||||
|
Object result = contextualWork.get();
|
||||||
processJobResult(jobId, result);
|
processJobResult(jobId, result);
|
||||||
return result;
|
return result;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
@@ -169,24 +178,49 @@ public class JobExecutorService {
|
|||||||
// Return immediately with job ID
|
// Return immediately with job ID
|
||||||
return ResponseEntity.ok().body(new JobResponse<>(true, jobId, null));
|
return ResponseEntity.ok().body(new JobResponse<>(true, jobId, null));
|
||||||
} else if (async) {
|
} else if (async) {
|
||||||
taskManager.createTask(jobId);
|
taskManager.createTask(jobId, trackProgress);
|
||||||
executor.execute(
|
executor.execute(
|
||||||
() -> {
|
() ->
|
||||||
try {
|
runWithJobContext(
|
||||||
log.debug(
|
jobId,
|
||||||
"Running async job {} with timeout {} ms", jobId, timeoutToUse);
|
enableProgress,
|
||||||
|
() -> {
|
||||||
|
try {
|
||||||
|
log.debug(
|
||||||
|
"Running async job {} with timeout {} ms",
|
||||||
|
jobId,
|
||||||
|
timeoutToUse);
|
||||||
|
|
||||||
// Execute with timeout
|
Supplier<Object> contextualWork =
|
||||||
Object result = executeWithTimeout(() -> work.get(), timeoutToUse);
|
withJobContext(jobId, enableProgress, work);
|
||||||
processJobResult(jobId, result);
|
|
||||||
} catch (TimeoutException te) {
|
if (enableProgress) {
|
||||||
log.error("Job {} timed out after {} ms", jobId, timeoutToUse);
|
taskManager.updateProgress(jobId, 5, null);
|
||||||
taskManager.setError(jobId, "Job timed out");
|
}
|
||||||
} catch (Exception e) {
|
|
||||||
log.error("Error executing job {}: {}", jobId, e.getMessage(), e);
|
// Execute with timeout
|
||||||
taskManager.setError(jobId, e.getMessage());
|
Object result =
|
||||||
}
|
executeWithTimeout(
|
||||||
});
|
contextualWork,
|
||||||
|
timeoutToUse,
|
||||||
|
jobId,
|
||||||
|
enableProgress);
|
||||||
|
processJobResult(jobId, result);
|
||||||
|
} catch (TimeoutException te) {
|
||||||
|
log.error(
|
||||||
|
"Job {} timed out after {} ms",
|
||||||
|
jobId,
|
||||||
|
timeoutToUse);
|
||||||
|
taskManager.setError(jobId, "Job timed out");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error(
|
||||||
|
"Error executing job {}: {}",
|
||||||
|
jobId,
|
||||||
|
e.getMessage(),
|
||||||
|
e);
|
||||||
|
taskManager.setError(jobId, e.getMessage());
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
return ResponseEntity.ok().body(new JobResponse<>(true, jobId, null));
|
return ResponseEntity.ok().body(new JobResponse<>(true, jobId, null));
|
||||||
} else {
|
} else {
|
||||||
@@ -194,7 +228,9 @@ public class JobExecutorService {
|
|||||||
log.debug("Running sync job with timeout {} ms", timeoutToUse);
|
log.debug("Running sync job with timeout {} ms", timeoutToUse);
|
||||||
|
|
||||||
// Execute with timeout
|
// Execute with timeout
|
||||||
Object result = executeWithTimeout(() -> work.get(), timeoutToUse);
|
Supplier<Object> contextualWork = withJobContext(jobId, enableProgress, work);
|
||||||
|
Object result =
|
||||||
|
executeWithTimeout(contextualWork, timeoutToUse, jobId, enableProgress);
|
||||||
|
|
||||||
// If the result is already a ResponseEntity, return it directly
|
// If the result is already a ResponseEntity, return it directly
|
||||||
if (result instanceof ResponseEntity) {
|
if (result instanceof ResponseEntity) {
|
||||||
@@ -452,12 +488,14 @@ public class JobExecutorService {
|
|||||||
* @throws TimeoutException If the execution times out
|
* @throws TimeoutException If the execution times out
|
||||||
* @throws Exception If the supplier throws an exception
|
* @throws Exception If the supplier throws an exception
|
||||||
*/
|
*/
|
||||||
private <T> T executeWithTimeout(Supplier<T> supplier, long timeoutMs)
|
private <T> T executeWithTimeout(
|
||||||
|
Supplier<T> supplier, long timeoutMs, String jobId, boolean progressEnabled)
|
||||||
throws TimeoutException, Exception {
|
throws TimeoutException, Exception {
|
||||||
// Use the same executor as other async jobs for consistency
|
// Use the same executor as other async jobs for consistency
|
||||||
// This ensures all operations run on the same thread pool
|
// This ensures all operations run on the same thread pool
|
||||||
java.util.concurrent.CompletableFuture<T> future =
|
java.util.concurrent.CompletableFuture<T> future =
|
||||||
java.util.concurrent.CompletableFuture.supplyAsync(supplier, executor);
|
java.util.concurrent.CompletableFuture.supplyAsync(
|
||||||
|
withJobContext(jobId, progressEnabled, supplier), executor);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return future.get(timeoutMs, TimeUnit.MILLISECONDS);
|
return future.get(timeoutMs, TimeUnit.MILLISECONDS);
|
||||||
@@ -473,4 +511,62 @@ public class JobExecutorService {
|
|||||||
throw new Exception("Execution was interrupted", e);
|
throw new Exception("Execution was interrupted", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Backwards compatible helper used by tests via reflection. */
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
private <T> T executeWithTimeout(Supplier<T> supplier, long timeoutMs)
|
||||||
|
throws TimeoutException, Exception {
|
||||||
|
return executeWithTimeout(
|
||||||
|
supplier,
|
||||||
|
timeoutMs,
|
||||||
|
JobContextHolder.getJobId(),
|
||||||
|
JobContextHolder.isProgressEnabled());
|
||||||
|
}
|
||||||
|
|
||||||
|
private <T> Supplier<T> withJobContext(
|
||||||
|
String jobId, boolean progressEnabled, Supplier<T> delegate) {
|
||||||
|
if (jobId == null) {
|
||||||
|
return delegate;
|
||||||
|
}
|
||||||
|
return () -> {
|
||||||
|
String previousJobId = JobContextHolder.getJobId();
|
||||||
|
boolean previousProgress = JobContextHolder.isProgressEnabled();
|
||||||
|
|
||||||
|
JobContextHolder.setContext(jobId, progressEnabled);
|
||||||
|
try {
|
||||||
|
return delegate.get();
|
||||||
|
} finally {
|
||||||
|
if (previousJobId == null) {
|
||||||
|
JobContextHolder.clear();
|
||||||
|
} else {
|
||||||
|
JobContextHolder.setContext(previousJobId, previousProgress);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private void runWithJobContext(String jobId, boolean progressEnabled, Runnable runnable) {
|
||||||
|
if (jobId == null) {
|
||||||
|
runnable.run();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Runnable contextualRunnable =
|
||||||
|
() -> {
|
||||||
|
String previousJobId = JobContextHolder.getJobId();
|
||||||
|
boolean previousProgress = JobContextHolder.isProgressEnabled();
|
||||||
|
|
||||||
|
JobContextHolder.setContext(jobId, progressEnabled);
|
||||||
|
try {
|
||||||
|
runnable.run();
|
||||||
|
} finally {
|
||||||
|
if (previousJobId == null) {
|
||||||
|
JobContextHolder.clear();
|
||||||
|
} else {
|
||||||
|
JobContextHolder.setContext(previousJobId, previousProgress);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
contextualRunnable.run();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
package stirling.software.common.service;
|
||||||
|
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
|
||||||
|
import stirling.software.common.context.JobContextHolder;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convenience service that exposes a simple API for updating progress information from within job
|
||||||
|
* handlers executed through {@link JobExecutorService}. The service automatically ties progress
|
||||||
|
* updates to the current job (if any) and no-ops when progress tracking is disabled.
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class JobProgressService {
|
||||||
|
|
||||||
|
private final TaskManager taskManager;
|
||||||
|
|
||||||
|
/** Update the progress percentage for the current job. */
|
||||||
|
public boolean updateProgress(int percent, String message) {
|
||||||
|
String jobId = JobContextHolder.getJobId();
|
||||||
|
if (jobId == null || !JobContextHolder.isProgressEnabled()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return taskManager.updateProgress(jobId, percent, message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a simple tracker that can be used to report progress across a fixed number of steps.
|
||||||
|
* When progress tracking is disabled for the current job, the returned tracker will be a
|
||||||
|
* lightweight no-op implementation.
|
||||||
|
*/
|
||||||
|
public JobProgressTracker tracker(int totalSteps) {
|
||||||
|
return tracker(totalSteps, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a tracker and optionally publish an initial message. Useful for multi-stage pipelines
|
||||||
|
* where the initial state should be visible to clients.
|
||||||
|
*/
|
||||||
|
public JobProgressTracker tracker(int totalSteps, String initialMessage) {
|
||||||
|
String jobId = JobContextHolder.getJobId();
|
||||||
|
boolean enabled = JobContextHolder.isProgressEnabled();
|
||||||
|
|
||||||
|
if (jobId == null || !enabled || totalSteps <= 0) {
|
||||||
|
return JobProgressTracker.disabled();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (initialMessage != null && !initialMessage.isBlank()) {
|
||||||
|
taskManager.updateProgress(jobId, 0, initialMessage);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new JobProgressTracker(taskManager, jobId, totalSteps, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
package stirling.software.common.service;
|
||||||
|
|
||||||
|
import lombok.AccessLevel;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Utility that helps controllers report progress in a structured way by distributing the 0-100%
|
||||||
|
* range across a finite number of logical steps.
|
||||||
|
*/
|
||||||
|
@RequiredArgsConstructor(access = AccessLevel.PACKAGE)
|
||||||
|
public class JobProgressTracker {
|
||||||
|
|
||||||
|
private final TaskManager taskManager;
|
||||||
|
private final String jobId;
|
||||||
|
private final int totalSteps;
|
||||||
|
private final boolean enabled;
|
||||||
|
|
||||||
|
private int completedSteps;
|
||||||
|
|
||||||
|
static JobProgressTracker disabled() {
|
||||||
|
return new JobProgressTracker(null, null, 1, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether the tracker will emit updates. */
|
||||||
|
public boolean isEnabled() {
|
||||||
|
return enabled;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Advance the tracker by one step. */
|
||||||
|
public void advance() {
|
||||||
|
advanceBy(1, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Advance the tracker by {@code steps} steps. */
|
||||||
|
public void advanceBy(int steps, String message) {
|
||||||
|
if (!enabled) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
int safeSteps = Math.max(0, steps);
|
||||||
|
completedSteps = Math.min(totalSteps, completedSteps + safeSteps);
|
||||||
|
publish(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Advance the tracker by {@code steps} steps without a message. */
|
||||||
|
public void advanceBy(int steps) {
|
||||||
|
advanceBy(steps, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Explicitly set the completed steps count. */
|
||||||
|
public void setStepsCompleted(int stepsCompleted, String message) {
|
||||||
|
if (!enabled) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
completedSteps = Math.max(0, Math.min(totalSteps, stepsCompleted));
|
||||||
|
publish(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Explicitly set completed steps without a message. */
|
||||||
|
public void setStepsCompleted(int stepsCompleted) {
|
||||||
|
setStepsCompleted(stepsCompleted, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mark the tracker as complete and emit a final message. */
|
||||||
|
public void complete(String message) {
|
||||||
|
if (!enabled) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
completedSteps = totalSteps;
|
||||||
|
taskManager.updateProgress(jobId, 100, message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mark the tracker as complete without a message. */
|
||||||
|
public void complete() {
|
||||||
|
complete(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void publish(String message) {
|
||||||
|
int percent = (int) Math.floor(((double) completedSteps / (double) totalSteps) * 100);
|
||||||
|
taskManager.updateProgress(jobId, percent, message);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -65,7 +65,17 @@ public class TaskManager {
|
|||||||
* @param jobId The job ID
|
* @param jobId The job ID
|
||||||
*/
|
*/
|
||||||
public void createTask(String jobId) {
|
public void createTask(String jobId) {
|
||||||
jobResults.put(jobId, JobResult.createNew(jobId));
|
createTask(jobId, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new task with the given job ID and progress tracking preference
|
||||||
|
*
|
||||||
|
* @param jobId The job ID
|
||||||
|
* @param trackProgress Whether detailed progress updates should be stored
|
||||||
|
*/
|
||||||
|
public void createTask(String jobId, boolean trackProgress) {
|
||||||
|
jobResults.put(jobId, JobResult.createNew(jobId, trackProgress));
|
||||||
log.debug("Created task with job ID: {}", jobId);
|
log.debug("Created task with job ID: {}", jobId);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -165,6 +175,11 @@ public class TaskManager {
|
|||||||
&& jobResult.getError() == null) {
|
&& jobResult.getError() == null) {
|
||||||
// If no result or error has been set, mark it as complete with an empty result
|
// If no result or error has been set, mark it as complete with an empty result
|
||||||
jobResult.completeWithResult("Task completed successfully");
|
jobResult.completeWithResult("Task completed successfully");
|
||||||
|
} else {
|
||||||
|
// Ensure progress is set to 100% with "Completed" message
|
||||||
|
if (jobResult.isTrackProgress()) {
|
||||||
|
jobResult.updateProgress(100, "Completed");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
log.debug("Marked job ID: {} as complete", jobId);
|
log.debug("Marked job ID: {} as complete", jobId);
|
||||||
}
|
}
|
||||||
@@ -209,6 +224,33 @@ public class TaskManager {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update the progress information for a task.
|
||||||
|
*
|
||||||
|
* @param jobId The job ID
|
||||||
|
* @param percent Percentage complete (0-100)
|
||||||
|
* @param message Descriptive message for the current stage
|
||||||
|
* @return true if the progress update was accepted
|
||||||
|
*/
|
||||||
|
public boolean updateProgress(String jobId, int percent, String message) {
|
||||||
|
JobResult jobResult = jobResults.get(jobId);
|
||||||
|
if (jobResult == null) {
|
||||||
|
log.debug("Ignoring progress update for unknown job ID: {}", jobId);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!jobResult.isTrackProgress()) {
|
||||||
|
log.trace("Progress tracking disabled for job ID: {}", jobId);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
jobResult.updateProgress(percent, message);
|
||||||
|
log.debug(
|
||||||
|
"Updated progress for job {} to {}% with message: {}",
|
||||||
|
jobId, jobResult.getProgressPercent(), message);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get statistics about all jobs in the system
|
* Get statistics about all jobs in the system
|
||||||
*
|
*
|
||||||
|
|||||||
+34
-4
@@ -1,6 +1,7 @@
|
|||||||
package stirling.software.common.annotations;
|
package stirling.software.common.annotations;
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
@@ -72,6 +73,8 @@ class AutoJobPostMappingIntegrationTest {
|
|||||||
|
|
||||||
@Captor private ArgumentCaptor<Integer> resourceWeightCaptor;
|
@Captor private ArgumentCaptor<Integer> resourceWeightCaptor;
|
||||||
|
|
||||||
|
@Captor private ArgumentCaptor<Boolean> trackProgressCaptor;
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void shouldExecuteWithCustomParameters() throws Throwable {
|
void shouldExecuteWithCustomParameters() throws Throwable {
|
||||||
// Given
|
// Given
|
||||||
@@ -91,7 +94,12 @@ class AutoJobPostMappingIntegrationTest {
|
|||||||
when(fileStorage.retrieveFile("test-file-id")).thenReturn(mockFile);
|
when(fileStorage.retrieveFile("test-file-id")).thenReturn(mockFile);
|
||||||
|
|
||||||
when(jobExecutorService.runJobGeneric(
|
when(jobExecutorService.runJobGeneric(
|
||||||
anyBoolean(), any(Supplier.class), anyLong(), anyBoolean(), anyInt()))
|
anyBoolean(),
|
||||||
|
any(Supplier.class),
|
||||||
|
anyLong(),
|
||||||
|
anyBoolean(),
|
||||||
|
anyInt(),
|
||||||
|
anyBoolean()))
|
||||||
.thenReturn(ResponseEntity.ok("success"));
|
.thenReturn(ResponseEntity.ok("success"));
|
||||||
|
|
||||||
// When
|
// When
|
||||||
@@ -106,12 +114,14 @@ class AutoJobPostMappingIntegrationTest {
|
|||||||
workCaptor.capture(),
|
workCaptor.capture(),
|
||||||
timeoutCaptor.capture(),
|
timeoutCaptor.capture(),
|
||||||
queueableCaptor.capture(),
|
queueableCaptor.capture(),
|
||||||
resourceWeightCaptor.capture());
|
resourceWeightCaptor.capture(),
|
||||||
|
trackProgressCaptor.capture());
|
||||||
|
|
||||||
assertTrue(asyncCaptor.getValue(), "Async should be true");
|
assertTrue(asyncCaptor.getValue(), "Async should be true");
|
||||||
assertEquals(60000L, timeoutCaptor.getValue(), "Timeout should be 60000ms");
|
assertEquals(60000L, timeoutCaptor.getValue(), "Timeout should be 60000ms");
|
||||||
assertTrue(queueableCaptor.getValue(), "Queueable should be true");
|
assertTrue(queueableCaptor.getValue(), "Queueable should be true");
|
||||||
assertEquals(75, resourceWeightCaptor.getValue(), "Resource weight should be 75");
|
assertEquals(75, resourceWeightCaptor.getValue(), "Resource weight should be 75");
|
||||||
|
assertTrue(trackProgressCaptor.getValue(), "Track progress should propagate");
|
||||||
|
|
||||||
// Test that file was resolved
|
// Test that file was resolved
|
||||||
assertNotNull(pdfFile.getFileInput(), "File input should be set");
|
assertNotNull(pdfFile.getFileInput(), "File input should be set");
|
||||||
@@ -135,7 +145,12 @@ class AutoJobPostMappingIntegrationTest {
|
|||||||
|
|
||||||
// Mock jobExecutorService to execute the work immediately
|
// Mock jobExecutorService to execute the work immediately
|
||||||
when(jobExecutorService.runJobGeneric(
|
when(jobExecutorService.runJobGeneric(
|
||||||
anyBoolean(), any(Supplier.class), anyLong(), anyBoolean(), anyInt()))
|
anyBoolean(),
|
||||||
|
any(Supplier.class),
|
||||||
|
anyLong(),
|
||||||
|
anyBoolean(),
|
||||||
|
anyInt(),
|
||||||
|
anyBoolean()))
|
||||||
.thenAnswer(
|
.thenAnswer(
|
||||||
invocation -> {
|
invocation -> {
|
||||||
Supplier<Object> work = invocation.getArgument(1);
|
Supplier<Object> work = invocation.getArgument(1);
|
||||||
@@ -150,6 +165,16 @@ class AutoJobPostMappingIntegrationTest {
|
|||||||
|
|
||||||
// Verify that proceed was called twice (initial attempt + 1 retry)
|
// Verify that proceed was called twice (initial attempt + 1 retry)
|
||||||
verify(joinPoint, times(2)).proceed(any());
|
verify(joinPoint, times(2)).proceed(any());
|
||||||
|
|
||||||
|
verify(jobExecutorService)
|
||||||
|
.runJobGeneric(
|
||||||
|
asyncCaptor.capture(),
|
||||||
|
workCaptor.capture(),
|
||||||
|
timeoutCaptor.capture(),
|
||||||
|
queueableCaptor.capture(),
|
||||||
|
resourceWeightCaptor.capture(),
|
||||||
|
trackProgressCaptor.capture());
|
||||||
|
assertFalse(trackProgressCaptor.getValue(), "Track progress should be false when disabled");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -168,7 +193,12 @@ class AutoJobPostMappingIntegrationTest {
|
|||||||
|
|
||||||
// Mock job executor to return a successful response
|
// Mock job executor to return a successful response
|
||||||
when(jobExecutorService.runJobGeneric(
|
when(jobExecutorService.runJobGeneric(
|
||||||
anyBoolean(), any(Supplier.class), anyLong(), anyBoolean(), anyInt()))
|
anyBoolean(),
|
||||||
|
any(Supplier.class),
|
||||||
|
anyLong(),
|
||||||
|
anyBoolean(),
|
||||||
|
anyInt(),
|
||||||
|
anyBoolean()))
|
||||||
.thenReturn(ResponseEntity.ok("success"));
|
.thenReturn(ResponseEntity.ok("success"));
|
||||||
|
|
||||||
// When
|
// When
|
||||||
|
|||||||
-16
@@ -109,22 +109,6 @@ class ApplicationPropertiesLogicTest {
|
|||||||
assertTrue(ex.getMessage().toLowerCase().contains("not supported"));
|
assertTrue(ex.getMessage().toLowerCase().contains("not supported"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
|
||||||
void premium_google_drive_getters_return_empty_string_on_null_or_blank() {
|
|
||||||
Premium.ProFeatures.GoogleDrive gd = new Premium.ProFeatures.GoogleDrive();
|
|
||||||
|
|
||||||
assertEquals("", gd.getClientId());
|
|
||||||
assertEquals("", gd.getApiKey());
|
|
||||||
assertEquals("", gd.getAppId());
|
|
||||||
|
|
||||||
gd.setClientId(" id ");
|
|
||||||
gd.setApiKey(" key ");
|
|
||||||
gd.setAppId(" app ");
|
|
||||||
assertEquals(" id ", gd.getClientId());
|
|
||||||
assertEquals(" key ", gd.getApiKey());
|
|
||||||
assertEquals(" app ", gd.getAppId());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void ui_getters_return_null_for_blank() {
|
void ui_getters_return_null_for_blank() {
|
||||||
ApplicationProperties.Ui ui = new ApplicationProperties.Ui();
|
ApplicationProperties.Ui ui = new ApplicationProperties.Ui();
|
||||||
|
|||||||
+4
-3
@@ -94,7 +94,7 @@ class JobExecutorServiceTest {
|
|||||||
assertNotNull(jobResponse.getJobId());
|
assertNotNull(jobResponse.getJobId());
|
||||||
|
|
||||||
// Verify task manager was called
|
// Verify task manager was called
|
||||||
verify(taskManager).createTask(jobIdCaptor.capture());
|
verify(taskManager).createTask(jobIdCaptor.capture(), eq(true));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -129,7 +129,8 @@ class JobExecutorServiceTest {
|
|||||||
when(jobQueue.queueJob(anyString(), eq(80), any(), anyLong())).thenReturn(future);
|
when(jobQueue.queueJob(anyString(), eq(80), any(), anyLong())).thenReturn(future);
|
||||||
|
|
||||||
// When
|
// When
|
||||||
ResponseEntity<?> response = jobExecutorService.runJobGeneric(true, work, 5000, true, 80);
|
ResponseEntity<?> response =
|
||||||
|
jobExecutorService.runJobGeneric(true, work, 5000, true, 80, true);
|
||||||
|
|
||||||
// Then
|
// Then
|
||||||
assertEquals(HttpStatus.OK, response.getStatusCode());
|
assertEquals(HttpStatus.OK, response.getStatusCode());
|
||||||
@@ -137,7 +138,7 @@ class JobExecutorServiceTest {
|
|||||||
|
|
||||||
// Verify job was queued
|
// Verify job was queued
|
||||||
verify(jobQueue).queueJob(anyString(), eq(80), any(), eq(5000L));
|
verify(jobQueue).queueJob(anyString(), eq(80), any(), eq(5000L));
|
||||||
verify(taskManager).createTask(anyString());
|
verify(taskManager).createTask(anyString(), eq(true));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
@@ -0,0 +1,83 @@
|
|||||||
|
package stirling.software.common.service;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.AfterEach;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.MockitoAnnotations;
|
||||||
|
|
||||||
|
import stirling.software.common.context.JobContextHolder;
|
||||||
|
|
||||||
|
class JobProgressServiceTest {
|
||||||
|
|
||||||
|
@Mock private TaskManager taskManager;
|
||||||
|
|
||||||
|
private JobProgressService jobProgressService;
|
||||||
|
|
||||||
|
private AutoCloseable mocks;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
mocks = MockitoAnnotations.openMocks(this);
|
||||||
|
jobProgressService = new JobProgressService(taskManager);
|
||||||
|
JobContextHolder.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterEach
|
||||||
|
void tearDown() throws Exception {
|
||||||
|
JobContextHolder.clear();
|
||||||
|
mocks.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void updateProgressReturnsFalseWhenNoContext() {
|
||||||
|
boolean updated = jobProgressService.updateProgress(10, "Stage");
|
||||||
|
assertFalse(updated);
|
||||||
|
verify(taskManager, never()).updateProgress(anyString(), anyInt(), anyString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void updateProgressDelegatesToTaskManager() {
|
||||||
|
JobContextHolder.setContext("job-123", true);
|
||||||
|
when(taskManager.updateProgress("job-123", 20, "Processing")).thenReturn(true);
|
||||||
|
|
||||||
|
boolean updated = jobProgressService.updateProgress(20, "Processing");
|
||||||
|
|
||||||
|
assertTrue(updated);
|
||||||
|
verify(taskManager).updateProgress("job-123", 20, "Processing");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void trackerNoOpsWhenDisabled() {
|
||||||
|
JobContextHolder.setContext("job-123", false);
|
||||||
|
JobProgressTracker tracker = jobProgressService.tracker(5, "Start");
|
||||||
|
|
||||||
|
assertFalse(tracker.isEnabled());
|
||||||
|
tracker.advanceBy(1, "Step");
|
||||||
|
tracker.complete("Done");
|
||||||
|
|
||||||
|
verify(taskManager, never()).updateProgress(anyString(), anyInt(), anyString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void trackerPublishesProgress() {
|
||||||
|
JobContextHolder.setContext("job-123", true);
|
||||||
|
JobProgressTracker tracker = jobProgressService.tracker(4, "Starting");
|
||||||
|
|
||||||
|
assertTrue(tracker.isEnabled());
|
||||||
|
verify(taskManager).updateProgress("job-123", 0, "Starting");
|
||||||
|
|
||||||
|
tracker.advanceBy(1, "25 percent");
|
||||||
|
tracker.advanceBy(1, "50 percent");
|
||||||
|
tracker.setStepsCompleted(3, "75 percent");
|
||||||
|
tracker.complete("Done");
|
||||||
|
|
||||||
|
verify(taskManager).updateProgress("job-123", 25, "25 percent");
|
||||||
|
verify(taskManager).updateProgress("job-123", 50, "50 percent");
|
||||||
|
verify(taskManager).updateProgress("job-123", 75, "75 percent");
|
||||||
|
verify(taskManager).updateProgress("job-123", 100, "Done");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -50,6 +50,9 @@ class TaskManagerTest {
|
|||||||
assertEquals(jobId, result.getJobId());
|
assertEquals(jobId, result.getJobId());
|
||||||
assertFalse(result.isComplete());
|
assertFalse(result.isComplete());
|
||||||
assertNotNull(result.getCreatedAt());
|
assertNotNull(result.getCreatedAt());
|
||||||
|
assertTrue(result.isTrackProgress());
|
||||||
|
assertEquals(0, result.getProgressPercent());
|
||||||
|
assertEquals("Pending", result.getProgressMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -68,6 +71,8 @@ class TaskManagerTest {
|
|||||||
assertTrue(result.isComplete());
|
assertTrue(result.isComplete());
|
||||||
assertEquals(resultObject, result.getResult());
|
assertEquals(resultObject, result.getResult());
|
||||||
assertNotNull(result.getCompletedAt());
|
assertNotNull(result.getCompletedAt());
|
||||||
|
assertEquals(100, result.getProgressPercent());
|
||||||
|
assertEquals("Completed", result.getProgressMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -120,6 +125,8 @@ class TaskManagerTest {
|
|||||||
assertTrue(result.isComplete());
|
assertTrue(result.isComplete());
|
||||||
assertEquals(errorMessage, result.getError());
|
assertEquals(errorMessage, result.getError());
|
||||||
assertNotNull(result.getCompletedAt());
|
assertNotNull(result.getCompletedAt());
|
||||||
|
assertEquals(100, result.getProgressPercent());
|
||||||
|
assertEquals(errorMessage, result.getProgressMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -138,6 +145,7 @@ class TaskManagerTest {
|
|||||||
assertNotNull(result);
|
assertNotNull(result);
|
||||||
assertTrue(result.isComplete());
|
assertTrue(result.isComplete());
|
||||||
assertEquals(resultObject, result.getResult());
|
assertEquals(resultObject, result.getResult());
|
||||||
|
assertEquals(100, result.getProgressPercent());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -154,6 +162,8 @@ class TaskManagerTest {
|
|||||||
assertNotNull(result);
|
assertNotNull(result);
|
||||||
assertTrue(result.isComplete());
|
assertTrue(result.isComplete());
|
||||||
assertEquals("Task completed successfully", result.getResult());
|
assertEquals("Task completed successfully", result.getResult());
|
||||||
|
assertEquals(100, result.getProgressPercent());
|
||||||
|
assertEquals("Completed", result.getProgressMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -305,4 +315,45 @@ class TaskManagerTest {
|
|||||||
// Assert
|
// Assert
|
||||||
assertFalse(result);
|
assertFalse(result);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testCreateTaskWithoutProgressTracking() {
|
||||||
|
String jobId = UUID.randomUUID().toString();
|
||||||
|
taskManager.createTask(jobId, false);
|
||||||
|
|
||||||
|
JobResult result = taskManager.getJobResult(jobId);
|
||||||
|
assertNotNull(result);
|
||||||
|
assertFalse(result.isTrackProgress());
|
||||||
|
assertNull(result.getProgressPercent());
|
||||||
|
assertNull(result.getProgressMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testUpdateProgress() {
|
||||||
|
String jobId = UUID.randomUUID().toString();
|
||||||
|
taskManager.createTask(jobId);
|
||||||
|
|
||||||
|
boolean updated = taskManager.updateProgress(jobId, 50, "Halfway there");
|
||||||
|
|
||||||
|
assertTrue(updated);
|
||||||
|
JobResult result = taskManager.getJobResult(jobId);
|
||||||
|
assertEquals(50, result.getProgressPercent());
|
||||||
|
assertEquals("Halfway there", result.getProgressMessage());
|
||||||
|
assertNotNull(result.getProgressUpdatedAt());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testUpdateProgressReturnsFalseWhenJobMissing() {
|
||||||
|
boolean updated = taskManager.updateProgress("missing", 10, "Stage");
|
||||||
|
assertFalse(updated);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testUpdateProgressIgnoredWhenTrackingDisabled() {
|
||||||
|
String jobId = UUID.randomUUID().toString();
|
||||||
|
taskManager.createTask(jobId, false);
|
||||||
|
|
||||||
|
boolean updated = taskManager.updateProgress(jobId, 75, "Stage");
|
||||||
|
assertFalse(updated);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+38
-2
@@ -22,12 +22,15 @@ import stirling.software.common.annotations.AutoJobPostMapping;
|
|||||||
import stirling.software.common.annotations.api.AnalysisApi;
|
import stirling.software.common.annotations.api.AnalysisApi;
|
||||||
import stirling.software.common.model.api.PDFFile;
|
import stirling.software.common.model.api.PDFFile;
|
||||||
import stirling.software.common.service.CustomPDFDocumentFactory;
|
import stirling.software.common.service.CustomPDFDocumentFactory;
|
||||||
|
import stirling.software.common.service.JobProgressService;
|
||||||
|
import stirling.software.common.service.JobProgressTracker;
|
||||||
|
|
||||||
@AnalysisApi
|
@AnalysisApi
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class AnalysisController {
|
public class AnalysisController {
|
||||||
|
|
||||||
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
||||||
|
private final JobProgressService jobProgressService;
|
||||||
|
|
||||||
@AutoJobPostMapping(value = "/page-count", consumes = "multipart/form-data")
|
@AutoJobPostMapping(value = "/page-count", consumes = "multipart/form-data")
|
||||||
@JsonDataResponse
|
@JsonDataResponse
|
||||||
@@ -89,12 +92,22 @@ public class AnalysisController {
|
|||||||
try (PDDocument document = pdfDocumentFactory.load(file.getFileInput())) {
|
try (PDDocument document = pdfDocumentFactory.load(file.getFileInput())) {
|
||||||
List<Map<String, Float>> dimensions = new ArrayList<>();
|
List<Map<String, Float>> dimensions = new ArrayList<>();
|
||||||
PDPageTree pages = document.getPages();
|
PDPageTree pages = document.getPages();
|
||||||
|
JobProgressTracker progressTracker =
|
||||||
|
jobProgressService.tracker(Math.max(1, pages.getCount()));
|
||||||
|
boolean trackProgress = progressTracker.isEnabled();
|
||||||
|
|
||||||
for (PDPage page : pages) {
|
for (PDPage page : pages) {
|
||||||
Map<String, Float> pageDim = new HashMap<>();
|
Map<String, Float> pageDim = new HashMap<>();
|
||||||
pageDim.put("width", page.getBBox().getWidth());
|
pageDim.put("width", page.getBBox().getWidth());
|
||||||
pageDim.put("height", page.getBBox().getHeight());
|
pageDim.put("height", page.getBBox().getHeight());
|
||||||
dimensions.add(pageDim);
|
dimensions.add(pageDim);
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.complete();
|
||||||
}
|
}
|
||||||
return dimensions;
|
return dimensions;
|
||||||
}
|
}
|
||||||
@@ -134,13 +147,24 @@ public class AnalysisController {
|
|||||||
Map<String, Object> annotInfo = new HashMap<>();
|
Map<String, Object> annotInfo = new HashMap<>();
|
||||||
int totalAnnotations = 0;
|
int totalAnnotations = 0;
|
||||||
Map<String, Integer> annotationTypes = new HashMap<>();
|
Map<String, Integer> annotationTypes = new HashMap<>();
|
||||||
|
PDPageTree pages = document.getPages();
|
||||||
|
JobProgressTracker progressTracker =
|
||||||
|
jobProgressService.tracker(Math.max(1, pages.getCount()));
|
||||||
|
boolean trackProgress = progressTracker.isEnabled();
|
||||||
|
|
||||||
for (PDPage page : document.getPages()) {
|
for (PDPage page : pages) {
|
||||||
for (PDAnnotation annot : page.getAnnotations()) {
|
for (PDAnnotation annot : page.getAnnotations()) {
|
||||||
totalAnnotations++;
|
totalAnnotations++;
|
||||||
String subType = annot.getSubtype();
|
String subType = annot.getSubtype();
|
||||||
annotationTypes.merge(subType, 1, Integer::sum);
|
annotationTypes.merge(subType, 1, Integer::sum);
|
||||||
}
|
}
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.complete();
|
||||||
}
|
}
|
||||||
|
|
||||||
annotInfo.put("totalCount", totalAnnotations);
|
annotInfo.put("totalCount", totalAnnotations);
|
||||||
@@ -160,10 +184,22 @@ public class AnalysisController {
|
|||||||
Map<String, Object> fontInfo = new HashMap<>();
|
Map<String, Object> fontInfo = new HashMap<>();
|
||||||
Set<String> fontNames = new HashSet<>();
|
Set<String> fontNames = new HashSet<>();
|
||||||
|
|
||||||
for (PDPage page : document.getPages()) {
|
PDPageTree pages = document.getPages();
|
||||||
|
JobProgressTracker progressTracker =
|
||||||
|
jobProgressService.tracker(Math.max(1, pages.getCount()));
|
||||||
|
boolean trackProgress = progressTracker.isEnabled();
|
||||||
|
|
||||||
|
for (PDPage page : pages) {
|
||||||
for (COSName font : page.getResources().getFontNames()) {
|
for (COSName font : page.getResources().getFontNames()) {
|
||||||
fontNames.add(font.getName());
|
fontNames.add(font.getName());
|
||||||
}
|
}
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.complete();
|
||||||
}
|
}
|
||||||
|
|
||||||
fontInfo.put("fontCount", fontNames.size());
|
fontInfo.put("fontCount", fontNames.size());
|
||||||
|
|||||||
+23
-6
@@ -28,6 +28,8 @@ import lombok.RequiredArgsConstructor;
|
|||||||
import stirling.software.SPDF.model.api.general.BookletImpositionRequest;
|
import stirling.software.SPDF.model.api.general.BookletImpositionRequest;
|
||||||
import stirling.software.common.annotations.AutoJobPostMapping;
|
import stirling.software.common.annotations.AutoJobPostMapping;
|
||||||
import stirling.software.common.service.CustomPDFDocumentFactory;
|
import stirling.software.common.service.CustomPDFDocumentFactory;
|
||||||
|
import stirling.software.common.service.JobProgressService;
|
||||||
|
import stirling.software.common.service.JobProgressTracker;
|
||||||
import stirling.software.common.util.WebResponseUtils;
|
import stirling.software.common.util.WebResponseUtils;
|
||||||
|
|
||||||
@RestController
|
@RestController
|
||||||
@@ -37,6 +39,7 @@ import stirling.software.common.util.WebResponseUtils;
|
|||||||
public class BookletImpositionController {
|
public class BookletImpositionController {
|
||||||
|
|
||||||
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
||||||
|
private final JobProgressService jobProgressService;
|
||||||
|
|
||||||
@AutoJobPostMapping(value = "/booklet-imposition", consumes = "multipart/form-data")
|
@AutoJobPostMapping(value = "/booklet-imposition", consumes = "multipart/form-data")
|
||||||
@Operation(
|
@Operation(
|
||||||
@@ -68,21 +71,31 @@ public class BookletImpositionController {
|
|||||||
PDDocument sourceDocument = pdfDocumentFactory.load(file);
|
PDDocument sourceDocument = pdfDocumentFactory.load(file);
|
||||||
int totalPages = sourceDocument.getNumberOfPages();
|
int totalPages = sourceDocument.getNumberOfPages();
|
||||||
|
|
||||||
|
List<Side> sides = saddleStitchSides(totalPages, doubleSided, duplexPass, flipOnShortEdge);
|
||||||
|
JobProgressTracker progressTracker = jobProgressService.tracker(Math.max(1, sides.size()));
|
||||||
|
boolean trackProgress = progressTracker.isEnabled();
|
||||||
|
|
||||||
// Create proper booklet with signature-based page ordering
|
// Create proper booklet with signature-based page ordering
|
||||||
PDDocument newDocument =
|
PDDocument newDocument =
|
||||||
createSaddleBooklet(
|
createSaddleBooklet(
|
||||||
sourceDocument,
|
sourceDocument,
|
||||||
totalPages,
|
|
||||||
addBorder,
|
addBorder,
|
||||||
spineLocation,
|
spineLocation,
|
||||||
addGutter,
|
addGutter,
|
||||||
gutterSize,
|
gutterSize,
|
||||||
doubleSided,
|
doubleSided,
|
||||||
duplexPass,
|
duplexPass,
|
||||||
flipOnShortEdge);
|
flipOnShortEdge,
|
||||||
|
sides,
|
||||||
|
progressTracker,
|
||||||
|
trackProgress);
|
||||||
|
|
||||||
sourceDocument.close();
|
sourceDocument.close();
|
||||||
|
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.complete();
|
||||||
|
}
|
||||||
|
|
||||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||||
newDocument.save(baos);
|
newDocument.save(baos);
|
||||||
newDocument.close();
|
newDocument.close();
|
||||||
@@ -154,14 +167,16 @@ public class BookletImpositionController {
|
|||||||
|
|
||||||
private PDDocument createSaddleBooklet(
|
private PDDocument createSaddleBooklet(
|
||||||
PDDocument src,
|
PDDocument src,
|
||||||
int totalPages,
|
|
||||||
boolean addBorder,
|
boolean addBorder,
|
||||||
String spineLocation,
|
String spineLocation,
|
||||||
boolean addGutter,
|
boolean addGutter,
|
||||||
float gutterSize,
|
float gutterSize,
|
||||||
boolean doubleSided,
|
boolean doubleSided,
|
||||||
String duplexPass,
|
String duplexPass,
|
||||||
boolean flipOnShortEdge)
|
boolean flipOnShortEdge,
|
||||||
|
List<Side> sides,
|
||||||
|
JobProgressTracker progressTracker,
|
||||||
|
boolean trackProgress)
|
||||||
throws IOException {
|
throws IOException {
|
||||||
|
|
||||||
PDDocument dst = pdfDocumentFactory.createNewDocumentBasedOnOldDocument(src);
|
PDDocument dst = pdfDocumentFactory.createNewDocumentBasedOnOldDocument(src);
|
||||||
@@ -176,8 +191,6 @@ public class BookletImpositionController {
|
|||||||
if (gutterSize < 0) gutterSize = 0;
|
if (gutterSize < 0) gutterSize = 0;
|
||||||
if (gutterSize >= pageSize.getWidth() / 2f) gutterSize = pageSize.getWidth() / 2f - 1f;
|
if (gutterSize >= pageSize.getWidth() / 2f) gutterSize = pageSize.getWidth() / 2f - 1f;
|
||||||
|
|
||||||
List<Side> sides = saddleStitchSides(totalPages, doubleSided, duplexPass, flipOnShortEdge);
|
|
||||||
|
|
||||||
for (Side side : sides) {
|
for (Side side : sides) {
|
||||||
PDPage out = new PDPage(pageSize);
|
PDPage out = new PDPage(pageSize);
|
||||||
dst.addPage(out);
|
dst.addPage(out);
|
||||||
@@ -234,6 +247,10 @@ public class BookletImpositionController {
|
|||||||
cellH,
|
cellH,
|
||||||
addBorder);
|
addBorder);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return dst;
|
return dst;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,6 +22,8 @@ import stirling.software.SPDF.model.api.general.CropPdfForm;
|
|||||||
import stirling.software.common.annotations.AutoJobPostMapping;
|
import stirling.software.common.annotations.AutoJobPostMapping;
|
||||||
import stirling.software.common.annotations.api.GeneralApi;
|
import stirling.software.common.annotations.api.GeneralApi;
|
||||||
import stirling.software.common.service.CustomPDFDocumentFactory;
|
import stirling.software.common.service.CustomPDFDocumentFactory;
|
||||||
|
import stirling.software.common.service.JobProgressService;
|
||||||
|
import stirling.software.common.service.JobProgressTracker;
|
||||||
import stirling.software.common.util.WebResponseUtils;
|
import stirling.software.common.util.WebResponseUtils;
|
||||||
|
|
||||||
@GeneralApi
|
@GeneralApi
|
||||||
@@ -29,6 +31,7 @@ import stirling.software.common.util.WebResponseUtils;
|
|||||||
public class CropController {
|
public class CropController {
|
||||||
|
|
||||||
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
||||||
|
private final JobProgressService jobProgressService;
|
||||||
|
|
||||||
@AutoJobPostMapping(value = "/crop", consumes = "multipart/form-data")
|
@AutoJobPostMapping(value = "/crop", consumes = "multipart/form-data")
|
||||||
@StandardPdfResponse
|
@StandardPdfResponse
|
||||||
@@ -44,6 +47,8 @@ public class CropController {
|
|||||||
pdfDocumentFactory.createNewDocumentBasedOnOldDocument(sourceDocument);
|
pdfDocumentFactory.createNewDocumentBasedOnOldDocument(sourceDocument);
|
||||||
|
|
||||||
int totalPages = sourceDocument.getNumberOfPages();
|
int totalPages = sourceDocument.getNumberOfPages();
|
||||||
|
JobProgressTracker progressTracker = jobProgressService.tracker(Math.max(1, totalPages));
|
||||||
|
boolean trackProgress = progressTracker.isEnabled();
|
||||||
|
|
||||||
LayerUtility layerUtility = new LayerUtility(newDocument);
|
LayerUtility layerUtility = new LayerUtility(newDocument);
|
||||||
|
|
||||||
@@ -80,6 +85,10 @@ public class CropController {
|
|||||||
request.getY(),
|
request.getY(),
|
||||||
request.getWidth(),
|
request.getWidth(),
|
||||||
request.getHeight()));
|
request.getHeight()));
|
||||||
|
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||||
@@ -87,6 +96,10 @@ public class CropController {
|
|||||||
newDocument.close();
|
newDocument.close();
|
||||||
sourceDocument.close();
|
sourceDocument.close();
|
||||||
|
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.complete();
|
||||||
|
}
|
||||||
|
|
||||||
byte[] pdfContent = baos.toByteArray();
|
byte[] pdfContent = baos.toByteArray();
|
||||||
return WebResponseUtils.bytesToWebResponse(
|
return WebResponseUtils.bytesToWebResponse(
|
||||||
pdfContent,
|
pdfContent,
|
||||||
|
|||||||
@@ -37,6 +37,8 @@ import stirling.software.SPDF.model.api.general.MergePdfsRequest;
|
|||||||
import stirling.software.common.annotations.AutoJobPostMapping;
|
import stirling.software.common.annotations.AutoJobPostMapping;
|
||||||
import stirling.software.common.annotations.api.GeneralApi;
|
import stirling.software.common.annotations.api.GeneralApi;
|
||||||
import stirling.software.common.service.CustomPDFDocumentFactory;
|
import stirling.software.common.service.CustomPDFDocumentFactory;
|
||||||
|
import stirling.software.common.service.JobProgressService;
|
||||||
|
import stirling.software.common.service.JobProgressTracker;
|
||||||
import stirling.software.common.util.ExceptionUtils;
|
import stirling.software.common.util.ExceptionUtils;
|
||||||
import stirling.software.common.util.GeneralUtils;
|
import stirling.software.common.util.GeneralUtils;
|
||||||
import stirling.software.common.util.PdfErrorUtils;
|
import stirling.software.common.util.PdfErrorUtils;
|
||||||
@@ -48,6 +50,7 @@ import stirling.software.common.util.WebResponseUtils;
|
|||||||
public class MergeController {
|
public class MergeController {
|
||||||
|
|
||||||
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
||||||
|
private final JobProgressService jobProgressService;
|
||||||
|
|
||||||
// Merges a list of PDDocument objects into a single PDDocument
|
// Merges a list of PDDocument objects into a single PDDocument
|
||||||
public PDDocument mergeDocuments(List<PDDocument> documents) throws IOException {
|
public PDDocument mergeDocuments(List<PDDocument> documents) throws IOException {
|
||||||
@@ -204,6 +207,10 @@ public class MergeController {
|
|||||||
getSortComparator(
|
getSortComparator(
|
||||||
request.getSortType())); // Sort files based on the given sort type
|
request.getSortType())); // Sort files based on the given sort type
|
||||||
|
|
||||||
|
JobProgressTracker progressTracker =
|
||||||
|
jobProgressService.tracker(Math.max(1, files.length) + 4);
|
||||||
|
boolean trackProgress = progressTracker.isEnabled();
|
||||||
|
|
||||||
PDFMergerUtility mergerUtility = new PDFMergerUtility();
|
PDFMergerUtility mergerUtility = new PDFMergerUtility();
|
||||||
long totalSize = 0;
|
long totalSize = 0;
|
||||||
List<Integer> invalidIndexes = new ArrayList<>();
|
List<Integer> invalidIndexes = new ArrayList<>();
|
||||||
@@ -224,6 +231,10 @@ public class MergeController {
|
|||||||
invalidIndexes.add(index);
|
invalidIndexes.add(index);
|
||||||
}
|
}
|
||||||
mergerUtility.addSource(tempFile); // Add source file to the merger utility
|
mergerUtility.addSource(tempFile); // Add source file to the merger utility
|
||||||
|
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!invalidIndexes.isEmpty()) {
|
if (!invalidIndexes.isEmpty()) {
|
||||||
@@ -243,6 +254,8 @@ public class MergeController {
|
|||||||
"{\"errorFileIds\":%s,\"message\":\"Some of the selected files can't be merged\"}",
|
"{\"errorFileIds\":%s,\"message\":\"Some of the selected files can't be merged\"}",
|
||||||
errorFileIds.toString());
|
errorFileIds.toString());
|
||||||
|
|
||||||
|
jobProgressService.updateProgress(100, null);
|
||||||
|
|
||||||
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY)
|
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY)
|
||||||
.header("Content-Type", MediaType.APPLICATION_JSON_VALUE)
|
.header("Content-Type", MediaType.APPLICATION_JSON_VALUE)
|
||||||
.body(payload.getBytes(StandardCharsets.UTF_8));
|
.body(payload.getBytes(StandardCharsets.UTF_8));
|
||||||
@@ -251,6 +264,10 @@ public class MergeController {
|
|||||||
mergedTempFile = Files.createTempFile("merged-", ".pdf").toFile();
|
mergedTempFile = Files.createTempFile("merged-", ".pdf").toFile();
|
||||||
mergerUtility.setDestinationFileName(mergedTempFile.getAbsolutePath());
|
mergerUtility.setDestinationFileName(mergedTempFile.getAbsolutePath());
|
||||||
|
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
mergerUtility.mergeDocuments(
|
mergerUtility.mergeDocuments(
|
||||||
pdfDocumentFactory.getStreamCacheFunction(
|
pdfDocumentFactory.getStreamCacheFunction(
|
||||||
@@ -289,10 +306,18 @@ public class MergeController {
|
|||||||
addTableOfContents(mergedDocument, files);
|
addTableOfContents(mergedDocument, files);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
}
|
||||||
|
|
||||||
// Save the modified document to a new ByteArrayOutputStream
|
// Save the modified document to a new ByteArrayOutputStream
|
||||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||||
mergedDocument.save(baos);
|
mergedDocument.save(baos);
|
||||||
|
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.complete();
|
||||||
|
}
|
||||||
|
|
||||||
String mergedFileName =
|
String mergedFileName =
|
||||||
files[0].getOriginalFilename().replaceFirst("[.][^.]+$", "")
|
files[0].getOriginalFilename().replaceFirst("[.][^.]+$", "")
|
||||||
+ "_merged_unsigned.pdf";
|
+ "_merged_unsigned.pdf";
|
||||||
|
|||||||
+13
@@ -25,6 +25,8 @@ import stirling.software.SPDF.model.api.general.MergeMultiplePagesRequest;
|
|||||||
import stirling.software.common.annotations.AutoJobPostMapping;
|
import stirling.software.common.annotations.AutoJobPostMapping;
|
||||||
import stirling.software.common.annotations.api.GeneralApi;
|
import stirling.software.common.annotations.api.GeneralApi;
|
||||||
import stirling.software.common.service.CustomPDFDocumentFactory;
|
import stirling.software.common.service.CustomPDFDocumentFactory;
|
||||||
|
import stirling.software.common.service.JobProgressService;
|
||||||
|
import stirling.software.common.service.JobProgressTracker;
|
||||||
import stirling.software.common.util.WebResponseUtils;
|
import stirling.software.common.util.WebResponseUtils;
|
||||||
|
|
||||||
@GeneralApi
|
@GeneralApi
|
||||||
@@ -32,6 +34,7 @@ import stirling.software.common.util.WebResponseUtils;
|
|||||||
public class MultiPageLayoutController {
|
public class MultiPageLayoutController {
|
||||||
|
|
||||||
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
||||||
|
private final JobProgressService jobProgressService;
|
||||||
|
|
||||||
@AutoJobPostMapping(value = "/multi-page-layout", consumes = "multipart/form-data")
|
@AutoJobPostMapping(value = "/multi-page-layout", consumes = "multipart/form-data")
|
||||||
@StandardPdfResponse
|
@StandardPdfResponse
|
||||||
@@ -66,6 +69,8 @@ public class MultiPageLayoutController {
|
|||||||
newDocument.addPage(newPage);
|
newDocument.addPage(newPage);
|
||||||
|
|
||||||
int totalPages = sourceDocument.getNumberOfPages();
|
int totalPages = sourceDocument.getNumberOfPages();
|
||||||
|
JobProgressTracker progressTracker = jobProgressService.tracker(Math.max(1, totalPages));
|
||||||
|
boolean trackProgress = progressTracker.isEnabled();
|
||||||
float cellWidth = newPage.getMediaBox().getWidth() / cols;
|
float cellWidth = newPage.getMediaBox().getWidth() / cols;
|
||||||
float cellHeight = newPage.getMediaBox().getHeight() / rows;
|
float cellHeight = newPage.getMediaBox().getHeight() / rows;
|
||||||
|
|
||||||
@@ -126,6 +131,10 @@ public class MultiPageLayoutController {
|
|||||||
contentStream.addRect(borderX, borderY, cellWidth, cellHeight);
|
contentStream.addRect(borderX, borderY, cellWidth, cellHeight);
|
||||||
contentStream.stroke();
|
contentStream.stroke();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
contentStream.close(); // Close the final content stream
|
contentStream.close(); // Close the final content stream
|
||||||
@@ -135,6 +144,10 @@ public class MultiPageLayoutController {
|
|||||||
newDocument.save(baos);
|
newDocument.save(baos);
|
||||||
newDocument.close();
|
newDocument.close();
|
||||||
|
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.complete();
|
||||||
|
}
|
||||||
|
|
||||||
byte[] result = baos.toByteArray();
|
byte[] result = baos.toByteArray();
|
||||||
return WebResponseUtils.bytesToWebResponse(
|
return WebResponseUtils.bytesToWebResponse(
|
||||||
result,
|
result,
|
||||||
|
|||||||
+14
-1
@@ -17,6 +17,8 @@ import stirling.software.common.annotations.AutoJobPostMapping;
|
|||||||
import stirling.software.common.annotations.api.GeneralApi;
|
import stirling.software.common.annotations.api.GeneralApi;
|
||||||
import stirling.software.common.model.api.PDFFile;
|
import stirling.software.common.model.api.PDFFile;
|
||||||
import stirling.software.common.service.CustomPDFDocumentFactory;
|
import stirling.software.common.service.CustomPDFDocumentFactory;
|
||||||
|
import stirling.software.common.service.JobProgressService;
|
||||||
|
import stirling.software.common.service.JobProgressTracker;
|
||||||
import stirling.software.common.util.WebResponseUtils;
|
import stirling.software.common.util.WebResponseUtils;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -32,6 +34,8 @@ public class PdfImageRemovalController {
|
|||||||
|
|
||||||
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
||||||
|
|
||||||
|
private final JobProgressService jobProgressService;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Endpoint to remove images from a PDF file.
|
* Endpoint to remove images from a PDF file.
|
||||||
*
|
*
|
||||||
@@ -54,8 +58,13 @@ public class PdfImageRemovalController {
|
|||||||
// Load the PDF document
|
// Load the PDF document
|
||||||
PDDocument document = pdfDocumentFactory.load(file);
|
PDDocument document = pdfDocumentFactory.load(file);
|
||||||
|
|
||||||
|
int pageCount = Math.max(1, document.getNumberOfPages());
|
||||||
|
JobProgressTracker progressTracker = jobProgressService.tracker(pageCount + 1);
|
||||||
|
boolean trackProgress = progressTracker.isEnabled();
|
||||||
|
|
||||||
// Remove images from the PDF document using the service
|
// Remove images from the PDF document using the service
|
||||||
PDDocument modifiedDocument = pdfImageRemovalService.removeImagesFromPdf(document);
|
PDDocument modifiedDocument =
|
||||||
|
pdfImageRemovalService.removeImagesFromPdf(document, progressTracker);
|
||||||
|
|
||||||
// Create a ByteArrayOutputStream to hold the modified PDF data
|
// Create a ByteArrayOutputStream to hold the modified PDF data
|
||||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||||
@@ -69,6 +78,10 @@ public class PdfImageRemovalController {
|
|||||||
file.getFileInput().getOriginalFilename().replaceFirst("[.][^.]+$", "")
|
file.getFileInput().getOriginalFilename().replaceFirst("[.][^.]+$", "")
|
||||||
+ "_removed_images.pdf";
|
+ "_removed_images.pdf";
|
||||||
|
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.complete();
|
||||||
|
}
|
||||||
|
|
||||||
// Convert the byte array to a web response and return it
|
// Convert the byte array to a web response and return it
|
||||||
return WebResponseUtils.bytesToWebResponse(outputStream.toByteArray(), mergedFileName);
|
return WebResponseUtils.bytesToWebResponse(outputStream.toByteArray(), mergedFileName);
|
||||||
}
|
}
|
||||||
|
|||||||
+51
-8
@@ -27,6 +27,8 @@ import stirling.software.SPDF.model.api.general.OverlayPdfsRequest;
|
|||||||
import stirling.software.common.annotations.AutoJobPostMapping;
|
import stirling.software.common.annotations.AutoJobPostMapping;
|
||||||
import stirling.software.common.annotations.api.GeneralApi;
|
import stirling.software.common.annotations.api.GeneralApi;
|
||||||
import stirling.software.common.service.CustomPDFDocumentFactory;
|
import stirling.software.common.service.CustomPDFDocumentFactory;
|
||||||
|
import stirling.software.common.service.JobProgressService;
|
||||||
|
import stirling.software.common.service.JobProgressTracker;
|
||||||
import stirling.software.common.util.GeneralUtils;
|
import stirling.software.common.util.GeneralUtils;
|
||||||
import stirling.software.common.util.WebResponseUtils;
|
import stirling.software.common.util.WebResponseUtils;
|
||||||
|
|
||||||
@@ -35,6 +37,7 @@ import stirling.software.common.util.WebResponseUtils;
|
|||||||
public class PdfOverlayController {
|
public class PdfOverlayController {
|
||||||
|
|
||||||
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
||||||
|
private final JobProgressService jobProgressService;
|
||||||
|
|
||||||
@AutoJobPostMapping(value = "/overlay-pdfs", consumes = "multipart/form-data")
|
@AutoJobPostMapping(value = "/overlay-pdfs", consumes = "multipart/form-data")
|
||||||
@StandardPdfResponse
|
@StandardPdfResponse
|
||||||
@@ -63,13 +66,17 @@ public class PdfOverlayController {
|
|||||||
|
|
||||||
try (PDDocument basePdf = pdfDocumentFactory.load(baseFile);
|
try (PDDocument basePdf = pdfDocumentFactory.load(baseFile);
|
||||||
Overlay overlay = new Overlay()) {
|
Overlay overlay = new Overlay()) {
|
||||||
|
JobProgressTracker progressTracker =
|
||||||
|
jobProgressService.tracker(basePdf.getNumberOfPages() + 1);
|
||||||
|
boolean trackProgress = progressTracker.isEnabled();
|
||||||
Map<Integer, String> overlayGuide =
|
Map<Integer, String> overlayGuide =
|
||||||
prepareOverlayGuide(
|
prepareOverlayGuide(
|
||||||
basePdf.getNumberOfPages(),
|
basePdf.getNumberOfPages(),
|
||||||
overlayPdfFiles,
|
overlayPdfFiles,
|
||||||
mode,
|
mode,
|
||||||
counts,
|
counts,
|
||||||
tempFiles);
|
tempFiles,
|
||||||
|
progressTracker);
|
||||||
|
|
||||||
overlay.setInputPDF(basePdf);
|
overlay.setInputPDF(basePdf);
|
||||||
if (overlayPos == 0) {
|
if (overlayPos == 0) {
|
||||||
@@ -80,6 +87,13 @@ public class PdfOverlayController {
|
|||||||
|
|
||||||
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||||
overlay.overlay(overlayGuide).save(outputStream);
|
overlay.overlay(overlayGuide).save(outputStream);
|
||||||
|
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
progressTracker.complete();
|
||||||
|
} else {
|
||||||
|
jobProgressService.updateProgress(100, null);
|
||||||
|
}
|
||||||
byte[] data = outputStream.toByteArray();
|
byte[] data = outputStream.toByteArray();
|
||||||
String outputFilename =
|
String outputFilename =
|
||||||
Filenames.toSimpleFileName(baseFile.getOriginalFilename())
|
Filenames.toSimpleFileName(baseFile.getOriginalFilename())
|
||||||
@@ -104,18 +118,25 @@ public class PdfOverlayController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private Map<Integer, String> prepareOverlayGuide(
|
private Map<Integer, String> prepareOverlayGuide(
|
||||||
int basePageCount, File[] overlayFiles, String mode, int[] counts, List<File> tempFiles)
|
int basePageCount,
|
||||||
|
File[] overlayFiles,
|
||||||
|
String mode,
|
||||||
|
int[] counts,
|
||||||
|
List<File> tempFiles,
|
||||||
|
JobProgressTracker progressTracker)
|
||||||
throws IOException {
|
throws IOException {
|
||||||
Map<Integer, String> overlayGuide = new HashMap<>();
|
Map<Integer, String> overlayGuide = new HashMap<>();
|
||||||
switch (mode) {
|
switch (mode) {
|
||||||
case "SequentialOverlay":
|
case "SequentialOverlay":
|
||||||
sequentialOverlay(overlayGuide, overlayFiles, basePageCount, tempFiles);
|
sequentialOverlay(
|
||||||
|
overlayGuide, overlayFiles, basePageCount, tempFiles, progressTracker);
|
||||||
break;
|
break;
|
||||||
case "InterleavedOverlay":
|
case "InterleavedOverlay":
|
||||||
interleavedOverlay(overlayGuide, overlayFiles, basePageCount);
|
interleavedOverlay(overlayGuide, overlayFiles, basePageCount, progressTracker);
|
||||||
break;
|
break;
|
||||||
case "FixedRepeatOverlay":
|
case "FixedRepeatOverlay":
|
||||||
fixedRepeatOverlay(overlayGuide, overlayFiles, counts, basePageCount);
|
fixedRepeatOverlay(
|
||||||
|
overlayGuide, overlayFiles, counts, basePageCount, progressTracker);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
throw new IllegalArgumentException("Invalid overlay mode");
|
throw new IllegalArgumentException("Invalid overlay mode");
|
||||||
@@ -127,10 +148,12 @@ public class PdfOverlayController {
|
|||||||
Map<Integer, String> overlayGuide,
|
Map<Integer, String> overlayGuide,
|
||||||
File[] overlayFiles,
|
File[] overlayFiles,
|
||||||
int basePageCount,
|
int basePageCount,
|
||||||
List<File> tempFiles)
|
List<File> tempFiles,
|
||||||
|
JobProgressTracker progressTracker)
|
||||||
throws IOException {
|
throws IOException {
|
||||||
int overlayFileIndex = 0;
|
int overlayFileIndex = 0;
|
||||||
int pageCountInCurrentOverlay = 0;
|
int pageCountInCurrentOverlay = 0;
|
||||||
|
boolean trackProgress = progressTracker.isEnabled();
|
||||||
|
|
||||||
for (int basePageIndex = 1; basePageIndex <= basePageCount; basePageIndex++) {
|
for (int basePageIndex = 1; basePageIndex <= basePageCount; basePageIndex++) {
|
||||||
if (pageCountInCurrentOverlay == 0
|
if (pageCountInCurrentOverlay == 0
|
||||||
@@ -152,6 +175,10 @@ public class PdfOverlayController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pageCountInCurrentOverlay++;
|
pageCountInCurrentOverlay++;
|
||||||
|
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -162,8 +189,12 @@ public class PdfOverlayController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void interleavedOverlay(
|
private void interleavedOverlay(
|
||||||
Map<Integer, String> overlayGuide, File[] overlayFiles, int basePageCount)
|
Map<Integer, String> overlayGuide,
|
||||||
|
File[] overlayFiles,
|
||||||
|
int basePageCount,
|
||||||
|
JobProgressTracker progressTracker)
|
||||||
throws IOException {
|
throws IOException {
|
||||||
|
boolean trackProgress = progressTracker.isEnabled();
|
||||||
for (int basePageIndex = 1; basePageIndex <= basePageCount; basePageIndex++) {
|
for (int basePageIndex = 1; basePageIndex <= basePageCount; basePageIndex++) {
|
||||||
File overlayFile = overlayFiles[(basePageIndex - 1) % overlayFiles.length];
|
File overlayFile = overlayFiles[(basePageIndex - 1) % overlayFiles.length];
|
||||||
|
|
||||||
@@ -174,17 +205,26 @@ public class PdfOverlayController {
|
|||||||
overlayGuide.put(basePageIndex, overlayFile.getAbsolutePath());
|
overlayGuide.put(basePageIndex, overlayFile.getAbsolutePath());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void fixedRepeatOverlay(
|
private void fixedRepeatOverlay(
|
||||||
Map<Integer, String> overlayGuide, File[] overlayFiles, int[] counts, int basePageCount)
|
Map<Integer, String> overlayGuide,
|
||||||
|
File[] overlayFiles,
|
||||||
|
int[] counts,
|
||||||
|
int basePageCount,
|
||||||
|
JobProgressTracker progressTracker)
|
||||||
throws IOException {
|
throws IOException {
|
||||||
if (overlayFiles.length != counts.length) {
|
if (overlayFiles.length != counts.length) {
|
||||||
throw new IllegalArgumentException(
|
throw new IllegalArgumentException(
|
||||||
"Counts array length must match the number of overlay files");
|
"Counts array length must match the number of overlay files");
|
||||||
}
|
}
|
||||||
int currentPage = 1;
|
int currentPage = 1;
|
||||||
|
boolean trackProgress = progressTracker.isEnabled();
|
||||||
for (int i = 0; i < overlayFiles.length; i++) {
|
for (int i = 0; i < overlayFiles.length; i++) {
|
||||||
File overlayFile = overlayFiles[i];
|
File overlayFile = overlayFiles[i];
|
||||||
int repeatCount = counts[i];
|
int repeatCount = counts[i];
|
||||||
@@ -196,6 +236,9 @@ public class PdfOverlayController {
|
|||||||
for (int page = 0; page < overlayPageCount; page++) {
|
for (int page = 0; page < overlayPageCount; page++) {
|
||||||
if (currentPage > basePageCount) break;
|
if (currentPage > basePageCount) break;
|
||||||
overlayGuide.put(currentPage++, overlayFile.getAbsolutePath());
|
overlayGuide.put(currentPage++, overlayFile.getAbsolutePath());
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+30
@@ -24,6 +24,8 @@ import stirling.software.SPDF.model.api.general.RearrangePagesRequest;
|
|||||||
import stirling.software.common.annotations.AutoJobPostMapping;
|
import stirling.software.common.annotations.AutoJobPostMapping;
|
||||||
import stirling.software.common.annotations.api.GeneralApi;
|
import stirling.software.common.annotations.api.GeneralApi;
|
||||||
import stirling.software.common.service.CustomPDFDocumentFactory;
|
import stirling.software.common.service.CustomPDFDocumentFactory;
|
||||||
|
import stirling.software.common.service.JobProgressService;
|
||||||
|
import stirling.software.common.service.JobProgressTracker;
|
||||||
import stirling.software.common.util.ExceptionUtils;
|
import stirling.software.common.util.ExceptionUtils;
|
||||||
import stirling.software.common.util.GeneralUtils;
|
import stirling.software.common.util.GeneralUtils;
|
||||||
import stirling.software.common.util.WebResponseUtils;
|
import stirling.software.common.util.WebResponseUtils;
|
||||||
@@ -34,6 +36,7 @@ import stirling.software.common.util.WebResponseUtils;
|
|||||||
public class RearrangePagesPDFController {
|
public class RearrangePagesPDFController {
|
||||||
|
|
||||||
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
||||||
|
private final JobProgressService jobProgressService;
|
||||||
|
|
||||||
@AutoJobPostMapping(consumes = "multipart/form-data", value = "/remove-pages")
|
@AutoJobPostMapping(consumes = "multipart/form-data", value = "/remove-pages")
|
||||||
@StandardPdfResponse
|
@StandardPdfResponse
|
||||||
@@ -59,9 +62,20 @@ public class RearrangePagesPDFController {
|
|||||||
|
|
||||||
Collections.sort(pagesToRemove);
|
Collections.sort(pagesToRemove);
|
||||||
|
|
||||||
|
JobProgressTracker progressTracker =
|
||||||
|
jobProgressService.tracker(Math.max(1, pagesToRemove.size()));
|
||||||
|
boolean trackProgress = progressTracker.isEnabled();
|
||||||
|
|
||||||
for (int i = pagesToRemove.size() - 1; i >= 0; i--) {
|
for (int i = pagesToRemove.size() - 1; i >= 0; i--) {
|
||||||
int pageIndex = pagesToRemove.get(i);
|
int pageIndex = pagesToRemove.get(i);
|
||||||
document.removePage(pageIndex);
|
document.removePage(pageIndex);
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.complete();
|
||||||
}
|
}
|
||||||
return WebResponseUtils.pdfDocToWebResponse(
|
return WebResponseUtils.pdfDocToWebResponse(
|
||||||
document,
|
document,
|
||||||
@@ -272,14 +286,30 @@ public class RearrangePagesPDFController {
|
|||||||
newPages.add(document.getPage(newPageOrder.get(i)));
|
newPages.add(document.getPage(newPageOrder.get(i)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
int removalSteps = document.getNumberOfPages();
|
||||||
|
int additionSteps = newPages.size();
|
||||||
|
JobProgressTracker progressTracker =
|
||||||
|
jobProgressService.tracker(Math.max(1, removalSteps + additionSteps));
|
||||||
|
boolean trackProgress = progressTracker.isEnabled();
|
||||||
|
|
||||||
// Remove all the pages from the original document
|
// Remove all the pages from the original document
|
||||||
for (int i = document.getNumberOfPages() - 1; i >= 0; i--) {
|
for (int i = document.getNumberOfPages() - 1; i >= 0; i--) {
|
||||||
document.removePage(i);
|
document.removePage(i);
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add the pages in the new order
|
// Add the pages in the new order
|
||||||
for (PDPage page : newPages) {
|
for (PDPage page : newPages) {
|
||||||
document.addPage(page);
|
document.addPage(page);
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.complete();
|
||||||
}
|
}
|
||||||
|
|
||||||
return WebResponseUtils.pdfDocToWebResponse(
|
return WebResponseUtils.pdfDocToWebResponse(
|
||||||
|
|||||||
@@ -19,6 +19,8 @@ import stirling.software.SPDF.model.api.general.RotatePDFRequest;
|
|||||||
import stirling.software.common.annotations.AutoJobPostMapping;
|
import stirling.software.common.annotations.AutoJobPostMapping;
|
||||||
import stirling.software.common.annotations.api.GeneralApi;
|
import stirling.software.common.annotations.api.GeneralApi;
|
||||||
import stirling.software.common.service.CustomPDFDocumentFactory;
|
import stirling.software.common.service.CustomPDFDocumentFactory;
|
||||||
|
import stirling.software.common.service.JobProgressService;
|
||||||
|
import stirling.software.common.service.JobProgressTracker;
|
||||||
import stirling.software.common.util.ExceptionUtils;
|
import stirling.software.common.util.ExceptionUtils;
|
||||||
import stirling.software.common.util.WebResponseUtils;
|
import stirling.software.common.util.WebResponseUtils;
|
||||||
|
|
||||||
@@ -27,6 +29,7 @@ import stirling.software.common.util.WebResponseUtils;
|
|||||||
public class RotationController {
|
public class RotationController {
|
||||||
|
|
||||||
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
||||||
|
private final JobProgressService jobProgressService;
|
||||||
|
|
||||||
@AutoJobPostMapping(consumes = "multipart/form-data", value = "/rotate-pdf")
|
@AutoJobPostMapping(consumes = "multipart/form-data", value = "/rotate-pdf")
|
||||||
@StandardPdfResponse
|
@StandardPdfResponse
|
||||||
@@ -51,9 +54,19 @@ public class RotationController {
|
|||||||
|
|
||||||
// Get the list of pages in the document
|
// Get the list of pages in the document
|
||||||
PDPageTree pages = document.getPages();
|
PDPageTree pages = document.getPages();
|
||||||
|
int totalPages = Math.max(1, pages.getCount());
|
||||||
|
JobProgressTracker progressTracker = jobProgressService.tracker(totalPages);
|
||||||
|
boolean trackProgress = progressTracker.isEnabled();
|
||||||
|
|
||||||
for (PDPage page : pages) {
|
for (PDPage page : pages) {
|
||||||
page.setRotation(page.getRotation() + angle);
|
page.setRotation(page.getRotation() + angle);
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.complete();
|
||||||
}
|
}
|
||||||
|
|
||||||
return WebResponseUtils.pdfDocToWebResponse(
|
return WebResponseUtils.pdfDocToWebResponse(
|
||||||
|
|||||||
+13
@@ -26,6 +26,8 @@ import stirling.software.SPDF.model.api.general.ScalePagesRequest;
|
|||||||
import stirling.software.common.annotations.AutoJobPostMapping;
|
import stirling.software.common.annotations.AutoJobPostMapping;
|
||||||
import stirling.software.common.annotations.api.GeneralApi;
|
import stirling.software.common.annotations.api.GeneralApi;
|
||||||
import stirling.software.common.service.CustomPDFDocumentFactory;
|
import stirling.software.common.service.CustomPDFDocumentFactory;
|
||||||
|
import stirling.software.common.service.JobProgressService;
|
||||||
|
import stirling.software.common.service.JobProgressTracker;
|
||||||
import stirling.software.common.util.ExceptionUtils;
|
import stirling.software.common.util.ExceptionUtils;
|
||||||
import stirling.software.common.util.WebResponseUtils;
|
import stirling.software.common.util.WebResponseUtils;
|
||||||
|
|
||||||
@@ -34,6 +36,7 @@ import stirling.software.common.util.WebResponseUtils;
|
|||||||
public class ScalePagesController {
|
public class ScalePagesController {
|
||||||
|
|
||||||
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
||||||
|
private final JobProgressService jobProgressService;
|
||||||
|
|
||||||
@AutoJobPostMapping(value = "/scale-pages", consumes = "multipart/form-data")
|
@AutoJobPostMapping(value = "/scale-pages", consumes = "multipart/form-data")
|
||||||
@StandardPdfResponse
|
@StandardPdfResponse
|
||||||
@@ -55,6 +58,8 @@ public class ScalePagesController {
|
|||||||
PDRectangle targetSize = getTargetSize(targetPDRectangle, sourceDocument);
|
PDRectangle targetSize = getTargetSize(targetPDRectangle, sourceDocument);
|
||||||
|
|
||||||
int totalPages = sourceDocument.getNumberOfPages();
|
int totalPages = sourceDocument.getNumberOfPages();
|
||||||
|
JobProgressTracker progressTracker = jobProgressService.tracker(Math.max(1, totalPages));
|
||||||
|
boolean trackProgress = progressTracker.isEnabled();
|
||||||
for (int i = 0; i < totalPages; i++) {
|
for (int i = 0; i < totalPages; i++) {
|
||||||
PDPage sourcePage = sourceDocument.getPage(i);
|
PDPage sourcePage = sourceDocument.getPage(i);
|
||||||
PDRectangle sourceSize = sourcePage.getMediaBox();
|
PDRectangle sourceSize = sourcePage.getMediaBox();
|
||||||
@@ -87,6 +92,10 @@ public class ScalePagesController {
|
|||||||
|
|
||||||
contentStream.restoreGraphicsState();
|
contentStream.restoreGraphicsState();
|
||||||
contentStream.close();
|
contentStream.close();
|
||||||
|
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||||
@@ -94,6 +103,10 @@ public class ScalePagesController {
|
|||||||
outputDocument.close();
|
outputDocument.close();
|
||||||
sourceDocument.close();
|
sourceDocument.close();
|
||||||
|
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.complete();
|
||||||
|
}
|
||||||
|
|
||||||
return WebResponseUtils.bytesToWebResponse(
|
return WebResponseUtils.bytesToWebResponse(
|
||||||
baos.toByteArray(),
|
baos.toByteArray(),
|
||||||
Filenames.toSimpleFileName(file.getOriginalFilename()).replaceFirst("[.][^.]+$", "")
|
Filenames.toSimpleFileName(file.getOriginalFilename()).replaceFirst("[.][^.]+$", "")
|
||||||
|
|||||||
@@ -28,6 +28,8 @@ import stirling.software.SPDF.model.api.PDFWithPageNums;
|
|||||||
import stirling.software.common.annotations.AutoJobPostMapping;
|
import stirling.software.common.annotations.AutoJobPostMapping;
|
||||||
import stirling.software.common.annotations.api.GeneralApi;
|
import stirling.software.common.annotations.api.GeneralApi;
|
||||||
import stirling.software.common.service.CustomPDFDocumentFactory;
|
import stirling.software.common.service.CustomPDFDocumentFactory;
|
||||||
|
import stirling.software.common.service.JobProgressService;
|
||||||
|
import stirling.software.common.service.JobProgressTracker;
|
||||||
import stirling.software.common.util.ExceptionUtils;
|
import stirling.software.common.util.ExceptionUtils;
|
||||||
import stirling.software.common.util.WebResponseUtils;
|
import stirling.software.common.util.WebResponseUtils;
|
||||||
|
|
||||||
@@ -37,6 +39,7 @@ import stirling.software.common.util.WebResponseUtils;
|
|||||||
public class SplitPDFController {
|
public class SplitPDFController {
|
||||||
|
|
||||||
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
||||||
|
private final JobProgressService jobProgressService;
|
||||||
|
|
||||||
@AutoJobPostMapping(consumes = "multipart/form-data", value = "/split-pages")
|
@AutoJobPostMapping(consumes = "multipart/form-data", value = "/split-pages")
|
||||||
@MultiFileResponse
|
@MultiFileResponse
|
||||||
@@ -77,6 +80,8 @@ public class SplitPDFController {
|
|||||||
// split the document
|
// split the document
|
||||||
splitDocumentsBoas = new ArrayList<>();
|
splitDocumentsBoas = new ArrayList<>();
|
||||||
int previousPageNumber = 0;
|
int previousPageNumber = 0;
|
||||||
|
JobProgressTracker progressTracker = jobProgressService.tracker(pageNumbers.size() + 2);
|
||||||
|
boolean trackProgress = progressTracker.isEnabled();
|
||||||
for (int splitPoint : pageNumbers) {
|
for (int splitPoint : pageNumbers) {
|
||||||
try (PDDocument splitDocument =
|
try (PDDocument splitDocument =
|
||||||
pdfDocumentFactory.createNewDocumentBasedOnOldDocument(document)) {
|
pdfDocumentFactory.createNewDocumentBasedOnOldDocument(document)) {
|
||||||
@@ -94,6 +99,10 @@ public class SplitPDFController {
|
|||||||
splitDocument.save(baos);
|
splitDocument.save(baos);
|
||||||
|
|
||||||
splitDocumentsBoas.add(baos);
|
splitDocumentsBoas.add(baos);
|
||||||
|
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
ExceptionUtils.logException("document splitting and saving", e);
|
ExceptionUtils.logException("document splitting and saving", e);
|
||||||
throw e;
|
throw e;
|
||||||
@@ -128,11 +137,18 @@ public class SplitPDFController {
|
|||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
}
|
||||||
|
|
||||||
log.debug("Successfully created zip file with split documents: {}", zipFile.toString());
|
log.debug("Successfully created zip file with split documents: {}", zipFile.toString());
|
||||||
byte[] data = Files.readAllBytes(zipFile);
|
byte[] data = Files.readAllBytes(zipFile);
|
||||||
Files.deleteIfExists(zipFile);
|
Files.deleteIfExists(zipFile);
|
||||||
|
|
||||||
// return the Resource in the response
|
// return the Resource in the response
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.complete();
|
||||||
|
}
|
||||||
return WebResponseUtils.bytesToWebResponse(
|
return WebResponseUtils.bytesToWebResponse(
|
||||||
data, filename + ".zip", MediaType.APPLICATION_OCTET_STREAM);
|
data, filename + ".zip", MediaType.APPLICATION_OCTET_STREAM);
|
||||||
|
|
||||||
|
|||||||
+24
-2
@@ -33,6 +33,8 @@ import stirling.software.common.annotations.AutoJobPostMapping;
|
|||||||
import stirling.software.common.annotations.api.GeneralApi;
|
import stirling.software.common.annotations.api.GeneralApi;
|
||||||
import stirling.software.common.model.PdfMetadata;
|
import stirling.software.common.model.PdfMetadata;
|
||||||
import stirling.software.common.service.CustomPDFDocumentFactory;
|
import stirling.software.common.service.CustomPDFDocumentFactory;
|
||||||
|
import stirling.software.common.service.JobProgressService;
|
||||||
|
import stirling.software.common.service.JobProgressTracker;
|
||||||
import stirling.software.common.service.PdfMetadataService;
|
import stirling.software.common.service.PdfMetadataService;
|
||||||
import stirling.software.common.util.ExceptionUtils;
|
import stirling.software.common.util.ExceptionUtils;
|
||||||
import stirling.software.common.util.WebResponseUtils;
|
import stirling.software.common.util.WebResponseUtils;
|
||||||
@@ -45,6 +47,7 @@ public class SplitPdfByChaptersController {
|
|||||||
private final PdfMetadataService pdfMetadataService;
|
private final PdfMetadataService pdfMetadataService;
|
||||||
|
|
||||||
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
||||||
|
private final JobProgressService jobProgressService;
|
||||||
|
|
||||||
private static List<Bookmark> extractOutlineItems(
|
private static List<Bookmark> extractOutlineItems(
|
||||||
PDDocument sourceDocument,
|
PDDocument sourceDocument,
|
||||||
@@ -178,8 +181,12 @@ public class SplitPdfByChaptersController {
|
|||||||
bookmark.getStartPage(),
|
bookmark.getStartPage(),
|
||||||
bookmark.getEndPage());
|
bookmark.getEndPage());
|
||||||
}
|
}
|
||||||
|
JobProgressTracker progressTracker = jobProgressService.tracker(bookmarks.size() + 1);
|
||||||
|
boolean trackProgress = progressTracker.isEnabled();
|
||||||
|
|
||||||
List<ByteArrayOutputStream> splitDocumentsBoas =
|
List<ByteArrayOutputStream> splitDocumentsBoas =
|
||||||
getSplitDocumentsBoas(sourceDocument, bookmarks, includeMetadata);
|
getSplitDocumentsBoas(
|
||||||
|
sourceDocument, bookmarks, includeMetadata, progressTracker);
|
||||||
|
|
||||||
zipFile = createZipFile(bookmarks, splitDocumentsBoas);
|
zipFile = createZipFile(bookmarks, splitDocumentsBoas);
|
||||||
|
|
||||||
@@ -190,6 +197,14 @@ public class SplitPdfByChaptersController {
|
|||||||
Filenames.toSimpleFileName(file.getOriginalFilename())
|
Filenames.toSimpleFileName(file.getOriginalFilename())
|
||||||
.replaceFirst("[.][^.]+$", "");
|
.replaceFirst("[.][^.]+$", "");
|
||||||
sourceDocument.close();
|
sourceDocument.close();
|
||||||
|
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
progressTracker.complete();
|
||||||
|
} else {
|
||||||
|
jobProgressService.updateProgress(100, null);
|
||||||
|
}
|
||||||
|
|
||||||
return WebResponseUtils.bytesToWebResponse(
|
return WebResponseUtils.bytesToWebResponse(
|
||||||
data, filename + ".zip", MediaType.APPLICATION_OCTET_STREAM);
|
data, filename + ".zip", MediaType.APPLICATION_OCTET_STREAM);
|
||||||
} finally {
|
} finally {
|
||||||
@@ -265,13 +280,17 @@ public class SplitPdfByChaptersController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public List<ByteArrayOutputStream> getSplitDocumentsBoas(
|
public List<ByteArrayOutputStream> getSplitDocumentsBoas(
|
||||||
PDDocument sourceDocument, List<Bookmark> bookmarks, boolean includeMetadata)
|
PDDocument sourceDocument,
|
||||||
|
List<Bookmark> bookmarks,
|
||||||
|
boolean includeMetadata,
|
||||||
|
JobProgressTracker progressTracker)
|
||||||
throws Exception {
|
throws Exception {
|
||||||
List<ByteArrayOutputStream> splitDocumentsBoas = new ArrayList<>();
|
List<ByteArrayOutputStream> splitDocumentsBoas = new ArrayList<>();
|
||||||
PdfMetadata metadata = null;
|
PdfMetadata metadata = null;
|
||||||
if (includeMetadata) {
|
if (includeMetadata) {
|
||||||
metadata = pdfMetadataService.extractMetadataFromPdf(sourceDocument);
|
metadata = pdfMetadataService.extractMetadataFromPdf(sourceDocument);
|
||||||
}
|
}
|
||||||
|
boolean trackProgress = progressTracker.isEnabled();
|
||||||
for (Bookmark bookmark : bookmarks) {
|
for (Bookmark bookmark : bookmarks) {
|
||||||
try (PDDocument splitDocument = new PDDocument()) {
|
try (PDDocument splitDocument = new PDDocument()) {
|
||||||
boolean isSinglePage = (bookmark.getStartPage() == bookmark.getEndPage());
|
boolean isSinglePage = (bookmark.getStartPage() == bookmark.getEndPage());
|
||||||
@@ -291,6 +310,9 @@ public class SplitPdfByChaptersController {
|
|||||||
splitDocument.save(baos);
|
splitDocument.save(baos);
|
||||||
|
|
||||||
splitDocumentsBoas.add(baos);
|
splitDocumentsBoas.add(baos);
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
ExceptionUtils.logException("document splitting and saving", e);
|
ExceptionUtils.logException("document splitting and saving", e);
|
||||||
throw e;
|
throw e;
|
||||||
|
|||||||
+44
-4
@@ -32,6 +32,8 @@ import stirling.software.SPDF.model.api.SplitPdfBySectionsRequest;
|
|||||||
import stirling.software.common.annotations.AutoJobPostMapping;
|
import stirling.software.common.annotations.AutoJobPostMapping;
|
||||||
import stirling.software.common.annotations.api.GeneralApi;
|
import stirling.software.common.annotations.api.GeneralApi;
|
||||||
import stirling.software.common.service.CustomPDFDocumentFactory;
|
import stirling.software.common.service.CustomPDFDocumentFactory;
|
||||||
|
import stirling.software.common.service.JobProgressService;
|
||||||
|
import stirling.software.common.service.JobProgressTracker;
|
||||||
import stirling.software.common.util.WebResponseUtils;
|
import stirling.software.common.util.WebResponseUtils;
|
||||||
|
|
||||||
@GeneralApi
|
@GeneralApi
|
||||||
@@ -39,6 +41,7 @@ import stirling.software.common.util.WebResponseUtils;
|
|||||||
public class SplitPdfBySectionsController {
|
public class SplitPdfBySectionsController {
|
||||||
|
|
||||||
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
||||||
|
private final JobProgressService jobProgressService;
|
||||||
|
|
||||||
@AutoJobPostMapping(value = "/split-pdf-by-sections", consumes = "multipart/form-data")
|
@AutoJobPostMapping(value = "/split-pdf-by-sections", consumes = "multipart/form-data")
|
||||||
@MultiFileResponse
|
@MultiFileResponse
|
||||||
@@ -59,15 +62,27 @@ public class SplitPdfBySectionsController {
|
|||||||
int horiz = request.getHorizontalDivisions() + 1;
|
int horiz = request.getHorizontalDivisions() + 1;
|
||||||
int verti = request.getVerticalDivisions() + 1;
|
int verti = request.getVerticalDivisions() + 1;
|
||||||
boolean merge = Boolean.TRUE.equals(request.getMerge());
|
boolean merge = Boolean.TRUE.equals(request.getMerge());
|
||||||
List<PDDocument> splitDocuments = splitPdfPages(sourceDocument, verti, horiz);
|
int totalSections = sourceDocument.getNumberOfPages() * horiz * verti;
|
||||||
|
JobProgressTracker progressTracker = jobProgressService.tracker(totalSections + 1);
|
||||||
|
boolean trackProgress = progressTracker.isEnabled();
|
||||||
|
List<PDDocument> splitDocuments =
|
||||||
|
splitPdfPages(sourceDocument, verti, horiz, progressTracker);
|
||||||
|
|
||||||
String filename =
|
String filename =
|
||||||
Filenames.toSimpleFileName(file.getOriginalFilename())
|
Filenames.toSimpleFileName(file.getOriginalFilename())
|
||||||
.replaceFirst("[.][^.]+$", "");
|
.replaceFirst("[.][^.]+$", "");
|
||||||
if (merge) {
|
if (merge) {
|
||||||
MergeController mergeController = new MergeController(pdfDocumentFactory);
|
|
||||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||||
mergeController.mergeDocuments(splitDocuments).save(baos);
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
}
|
||||||
|
mergeDocuments(splitDocuments).save(baos);
|
||||||
|
for (PDDocument doc : splitDocuments) {
|
||||||
|
doc.close();
|
||||||
|
}
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.complete();
|
||||||
|
}
|
||||||
return WebResponseUtils.bytesToWebResponse(baos.toByteArray(), filename + "_split.pdf");
|
return WebResponseUtils.bytesToWebResponse(baos.toByteArray(), filename + "_split.pdf");
|
||||||
}
|
}
|
||||||
for (PDDocument doc : splitDocuments) {
|
for (PDDocument doc : splitDocuments) {
|
||||||
@@ -99,6 +114,10 @@ public class SplitPdfBySectionsController {
|
|||||||
|
|
||||||
zipOut.finish();
|
zipOut.finish();
|
||||||
data = Files.readAllBytes(zipFile);
|
data = Files.readAllBytes(zipFile);
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
progressTracker.complete();
|
||||||
|
}
|
||||||
return WebResponseUtils.bytesToWebResponse(
|
return WebResponseUtils.bytesToWebResponse(
|
||||||
data, filename + "_split.zip", MediaType.APPLICATION_OCTET_STREAM);
|
data, filename + "_split.zip", MediaType.APPLICATION_OCTET_STREAM);
|
||||||
|
|
||||||
@@ -107,11 +126,28 @@ public class SplitPdfBySectionsController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private PDDocument mergeDocuments(List<PDDocument> documents) throws IOException {
|
||||||
|
PDDocument merged = pdfDocumentFactory.createNewDocument();
|
||||||
|
for (PDDocument doc : documents) {
|
||||||
|
for (PDPage page : doc.getPages()) {
|
||||||
|
merged.addPage(page);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return merged;
|
||||||
|
}
|
||||||
|
|
||||||
public List<PDDocument> splitPdfPages(
|
public List<PDDocument> splitPdfPages(
|
||||||
PDDocument document, int horizontalDivisions, int verticalDivisions)
|
PDDocument document,
|
||||||
|
int horizontalDivisions,
|
||||||
|
int verticalDivisions,
|
||||||
|
JobProgressTracker progressTracker)
|
||||||
throws IOException {
|
throws IOException {
|
||||||
List<PDDocument> splitDocuments = new ArrayList<>();
|
List<PDDocument> splitDocuments = new ArrayList<>();
|
||||||
|
|
||||||
|
int totalSections = document.getNumberOfPages() * horizontalDivisions * verticalDivisions;
|
||||||
|
int sectionCounter = 0;
|
||||||
|
boolean trackProgress = progressTracker.isEnabled();
|
||||||
|
|
||||||
for (PDPage originalPage : document.getPages()) {
|
for (PDPage originalPage : document.getPages()) {
|
||||||
PDRectangle originalMediaBox = originalPage.getMediaBox();
|
PDRectangle originalMediaBox = originalPage.getMediaBox();
|
||||||
float width = originalMediaBox.getWidth();
|
float width = originalMediaBox.getWidth();
|
||||||
@@ -151,6 +187,10 @@ public class SplitPdfBySectionsController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
splitDocuments.add(subDoc);
|
splitDocuments.add(subDoc);
|
||||||
|
sectionCounter++;
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+51
-6
@@ -25,6 +25,8 @@ import stirling.software.SPDF.model.api.general.SplitPdfBySizeOrCountRequest;
|
|||||||
import stirling.software.common.annotations.AutoJobPostMapping;
|
import stirling.software.common.annotations.AutoJobPostMapping;
|
||||||
import stirling.software.common.annotations.api.GeneralApi;
|
import stirling.software.common.annotations.api.GeneralApi;
|
||||||
import stirling.software.common.service.CustomPDFDocumentFactory;
|
import stirling.software.common.service.CustomPDFDocumentFactory;
|
||||||
|
import stirling.software.common.service.JobProgressService;
|
||||||
|
import stirling.software.common.service.JobProgressTracker;
|
||||||
import stirling.software.common.util.ExceptionUtils;
|
import stirling.software.common.util.ExceptionUtils;
|
||||||
import stirling.software.common.util.GeneralUtils;
|
import stirling.software.common.util.GeneralUtils;
|
||||||
import stirling.software.common.util.WebResponseUtils;
|
import stirling.software.common.util.WebResponseUtils;
|
||||||
@@ -35,6 +37,7 @@ import stirling.software.common.util.WebResponseUtils;
|
|||||||
public class SplitPdfBySizeController {
|
public class SplitPdfBySizeController {
|
||||||
|
|
||||||
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
||||||
|
private final JobProgressService jobProgressService;
|
||||||
|
|
||||||
@AutoJobPostMapping(value = "/split-by-size-or-count", consumes = "multipart/form-data")
|
@AutoJobPostMapping(value = "/split-by-size-or-count", consumes = "multipart/form-data")
|
||||||
@MultiFileResponse
|
@MultiFileResponse
|
||||||
@@ -78,21 +81,28 @@ public class SplitPdfBySizeController {
|
|||||||
String value = request.getSplitValue();
|
String value = request.getSplitValue();
|
||||||
log.debug("Split type: {}, Split value: {}", type, value);
|
log.debug("Split type: {}, Split value: {}", type, value);
|
||||||
|
|
||||||
|
JobProgressTracker progressTracker =
|
||||||
|
jobProgressService.tracker(sourceDocument.getNumberOfPages() + 2);
|
||||||
|
boolean trackProgress = progressTracker.isEnabled();
|
||||||
|
|
||||||
if (type == 0) {
|
if (type == 0) {
|
||||||
log.debug("Processing split by size");
|
log.debug("Processing split by size");
|
||||||
long maxBytes = GeneralUtils.convertSizeToBytes(value);
|
long maxBytes = GeneralUtils.convertSizeToBytes(value);
|
||||||
log.debug("Max bytes per document: {}", maxBytes);
|
log.debug("Max bytes per document: {}", maxBytes);
|
||||||
handleSplitBySize(sourceDocument, maxBytes, zipOut, filename);
|
handleSplitBySize(
|
||||||
|
sourceDocument, maxBytes, zipOut, filename, progressTracker);
|
||||||
} else if (type == 1) {
|
} else if (type == 1) {
|
||||||
log.debug("Processing split by page count");
|
log.debug("Processing split by page count");
|
||||||
int pageCount = Integer.parseInt(value);
|
int pageCount = Integer.parseInt(value);
|
||||||
log.debug("Pages per document: {}", pageCount);
|
log.debug("Pages per document: {}", pageCount);
|
||||||
handleSplitByPageCount(sourceDocument, pageCount, zipOut, filename);
|
handleSplitByPageCount(
|
||||||
|
sourceDocument, pageCount, zipOut, filename, progressTracker);
|
||||||
} else if (type == 2) {
|
} else if (type == 2) {
|
||||||
log.debug("Processing split by document count");
|
log.debug("Processing split by document count");
|
||||||
int documentCount = Integer.parseInt(value);
|
int documentCount = Integer.parseInt(value);
|
||||||
log.debug("Total number of documents: {}", documentCount);
|
log.debug("Total number of documents: {}", documentCount);
|
||||||
handleSplitByDocCount(sourceDocument, documentCount, zipOut, filename);
|
handleSplitByDocCount(
|
||||||
|
sourceDocument, documentCount, zipOut, filename, progressTracker);
|
||||||
} else {
|
} else {
|
||||||
log.error("Invalid split type: {}", type);
|
log.error("Invalid split type: {}", type);
|
||||||
throw ExceptionUtils.createIllegalArgumentException(
|
throw ExceptionUtils.createIllegalArgumentException(
|
||||||
@@ -102,6 +112,13 @@ public class SplitPdfBySizeController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
log.debug("PDF splitting completed successfully");
|
log.debug("PDF splitting completed successfully");
|
||||||
|
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
progressTracker.complete();
|
||||||
|
} else {
|
||||||
|
jobProgressService.updateProgress(100, null);
|
||||||
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
ExceptionUtils.logException("PDF document loading or processing", e);
|
ExceptionUtils.logException("PDF document loading or processing", e);
|
||||||
throw e;
|
throw e;
|
||||||
@@ -138,7 +155,11 @@ public class SplitPdfBySizeController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void handleSplitBySize(
|
private void handleSplitBySize(
|
||||||
PDDocument sourceDocument, long maxBytes, ZipOutputStream zipOut, String baseFilename)
|
PDDocument sourceDocument,
|
||||||
|
long maxBytes,
|
||||||
|
ZipOutputStream zipOut,
|
||||||
|
String baseFilename,
|
||||||
|
JobProgressTracker progressTracker)
|
||||||
throws IOException {
|
throws IOException {
|
||||||
log.debug("Starting handleSplitBySize with maxBytes={}", maxBytes);
|
log.debug("Starting handleSplitBySize with maxBytes={}", maxBytes);
|
||||||
|
|
||||||
@@ -147,6 +168,7 @@ public class SplitPdfBySizeController {
|
|||||||
int fileIndex = 1;
|
int fileIndex = 1;
|
||||||
int totalPages = sourceDocument.getNumberOfPages();
|
int totalPages = sourceDocument.getNumberOfPages();
|
||||||
int pageAdded = 0;
|
int pageAdded = 0;
|
||||||
|
boolean trackProgress = progressTracker.isEnabled();
|
||||||
|
|
||||||
// Smart size check frequency - check more often with larger documents
|
// Smart size check frequency - check more often with larger documents
|
||||||
int baseCheckFrequency = 5;
|
int baseCheckFrequency = 5;
|
||||||
@@ -251,6 +273,9 @@ public class SplitPdfBySizeController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.setStepsCompleted(Math.min(totalPages, pageIndex + 1));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Save final document if it has any pages
|
// Save final document if it has any pages
|
||||||
@@ -260,13 +285,20 @@ public class SplitPdfBySizeController {
|
|||||||
currentDoc.getNumberOfPages(),
|
currentDoc.getNumberOfPages(),
|
||||||
fileIndex);
|
fileIndex);
|
||||||
saveDocumentToZip(currentDoc, zipOut, baseFilename, fileIndex++);
|
saveDocumentToZip(currentDoc, zipOut, baseFilename, fileIndex++);
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.setStepsCompleted(totalPages);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
log.debug("Completed handleSplitBySize with {} document parts created", fileIndex - 1);
|
log.debug("Completed handleSplitBySize with {} document parts created", fileIndex - 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void handleSplitByPageCount(
|
private void handleSplitByPageCount(
|
||||||
PDDocument sourceDocument, int pageCount, ZipOutputStream zipOut, String baseFilename)
|
PDDocument sourceDocument,
|
||||||
|
int pageCount,
|
||||||
|
ZipOutputStream zipOut,
|
||||||
|
String baseFilename,
|
||||||
|
JobProgressTracker progressTracker)
|
||||||
throws IOException {
|
throws IOException {
|
||||||
log.debug("Starting handleSplitByPageCount with pageCount={}", pageCount);
|
log.debug("Starting handleSplitByPageCount with pageCount={}", pageCount);
|
||||||
int currentPageCount = 0;
|
int currentPageCount = 0;
|
||||||
@@ -284,12 +316,17 @@ public class SplitPdfBySizeController {
|
|||||||
int pageIndex = 0;
|
int pageIndex = 0;
|
||||||
int totalPages = sourceDocument.getNumberOfPages();
|
int totalPages = sourceDocument.getNumberOfPages();
|
||||||
log.debug("Processing {} pages", totalPages);
|
log.debug("Processing {} pages", totalPages);
|
||||||
|
boolean trackProgress = progressTracker.isEnabled();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
for (PDPage page : sourceDocument.getPages()) {
|
for (PDPage page : sourceDocument.getPages()) {
|
||||||
pageIndex++;
|
pageIndex++;
|
||||||
log.debug("Processing page {} of {}", pageIndex, totalPages);
|
log.debug("Processing page {} of {}", pageIndex, totalPages);
|
||||||
|
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.setStepsCompleted(pageIndex);
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
log.debug("Adding page {} to current document", pageIndex);
|
log.debug("Adding page {} to current document", pageIndex);
|
||||||
currentDoc.addPage(page);
|
currentDoc.addPage(page);
|
||||||
@@ -347,6 +384,9 @@ public class SplitPdfBySizeController {
|
|||||||
log.error("Error saving final document part {}", fileIndex - 1, e);
|
log.error("Error saving final document part {}", fileIndex - 1, e);
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.setStepsCompleted(totalPages);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
log.debug("Final document has no pages, skipping");
|
log.debug("Final document has no pages, skipping");
|
||||||
}
|
}
|
||||||
@@ -370,7 +410,8 @@ public class SplitPdfBySizeController {
|
|||||||
PDDocument sourceDocument,
|
PDDocument sourceDocument,
|
||||||
int documentCount,
|
int documentCount,
|
||||||
ZipOutputStream zipOut,
|
ZipOutputStream zipOut,
|
||||||
String baseFilename)
|
String baseFilename,
|
||||||
|
JobProgressTracker progressTracker)
|
||||||
throws IOException {
|
throws IOException {
|
||||||
log.debug("Starting handleSplitByDocCount with documentCount={}", documentCount);
|
log.debug("Starting handleSplitByDocCount with documentCount={}", documentCount);
|
||||||
int totalPageCount = sourceDocument.getNumberOfPages();
|
int totalPageCount = sourceDocument.getNumberOfPages();
|
||||||
@@ -382,6 +423,7 @@ public class SplitPdfBySizeController {
|
|||||||
|
|
||||||
int currentPageIndex = 0;
|
int currentPageIndex = 0;
|
||||||
int fileIndex = 1;
|
int fileIndex = 1;
|
||||||
|
boolean trackProgress = progressTracker.isEnabled();
|
||||||
|
|
||||||
for (int i = 0; i < documentCount; i++) {
|
for (int i = 0; i < documentCount; i++) {
|
||||||
log.debug("Creating document {} of {}", i + 1, documentCount);
|
log.debug("Creating document {} of {}", i + 1, documentCount);
|
||||||
@@ -407,6 +449,9 @@ public class SplitPdfBySizeController {
|
|||||||
currentDoc.addPage(sourceDocument.getPage(currentPageIndex));
|
currentDoc.addPage(sourceDocument.getPage(currentPageIndex));
|
||||||
log.debug("Successfully added page {} to document {}", j + 1, i + 1);
|
log.debug("Successfully added page {} to document {}", j + 1, i + 1);
|
||||||
currentPageIndex++;
|
currentPageIndex++;
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.setStepsCompleted(currentPageIndex);
|
||||||
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("Error adding page {} to document {}", j + 1, i + 1, e);
|
log.error("Error adding page {} to document {}", j + 1, i + 1, e);
|
||||||
throw ExceptionUtils.createFileProcessingException("split", e);
|
throw ExceptionUtils.createFileProcessingException("split", e);
|
||||||
|
|||||||
+14
@@ -22,6 +22,8 @@ import stirling.software.common.annotations.AutoJobPostMapping;
|
|||||||
import stirling.software.common.annotations.api.GeneralApi;
|
import stirling.software.common.annotations.api.GeneralApi;
|
||||||
import stirling.software.common.model.api.PDFFile;
|
import stirling.software.common.model.api.PDFFile;
|
||||||
import stirling.software.common.service.CustomPDFDocumentFactory;
|
import stirling.software.common.service.CustomPDFDocumentFactory;
|
||||||
|
import stirling.software.common.service.JobProgressService;
|
||||||
|
import stirling.software.common.service.JobProgressTracker;
|
||||||
import stirling.software.common.util.WebResponseUtils;
|
import stirling.software.common.util.WebResponseUtils;
|
||||||
|
|
||||||
@GeneralApi
|
@GeneralApi
|
||||||
@@ -29,6 +31,7 @@ import stirling.software.common.util.WebResponseUtils;
|
|||||||
public class ToSinglePageController {
|
public class ToSinglePageController {
|
||||||
|
|
||||||
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
||||||
|
private final JobProgressService jobProgressService;
|
||||||
|
|
||||||
@AutoJobPostMapping(consumes = "multipart/form-data", value = "/pdf-to-single-page")
|
@AutoJobPostMapping(consumes = "multipart/form-data", value = "/pdf-to-single-page")
|
||||||
@StandardPdfResponse
|
@StandardPdfResponse
|
||||||
@@ -45,6 +48,10 @@ public class ToSinglePageController {
|
|||||||
// Load the source document
|
// Load the source document
|
||||||
PDDocument sourceDocument = pdfDocumentFactory.load(request);
|
PDDocument sourceDocument = pdfDocumentFactory.load(request);
|
||||||
|
|
||||||
|
int totalPages = Math.max(1, sourceDocument.getNumberOfPages());
|
||||||
|
JobProgressTracker progressTracker = jobProgressService.tracker(totalPages + 1);
|
||||||
|
boolean trackProgress = progressTracker.isEnabled();
|
||||||
|
|
||||||
// Calculate total height and max width
|
// Calculate total height and max width
|
||||||
float totalHeight = 0;
|
float totalHeight = 0;
|
||||||
float maxWidth = 0;
|
float maxWidth = 0;
|
||||||
@@ -79,6 +86,9 @@ public class ToSinglePageController {
|
|||||||
layerUtility.appendFormAsLayer(newPage, form, af, defaultLayerName);
|
layerUtility.appendFormAsLayer(newPage, form, af, defaultLayerName);
|
||||||
yOffset -= page.getMediaBox().getHeight();
|
yOffset -= page.getMediaBox().getHeight();
|
||||||
pageIndex++;
|
pageIndex++;
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||||
@@ -86,6 +96,10 @@ public class ToSinglePageController {
|
|||||||
newDocument.close();
|
newDocument.close();
|
||||||
sourceDocument.close();
|
sourceDocument.close();
|
||||||
|
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.complete();
|
||||||
|
}
|
||||||
|
|
||||||
byte[] result = baos.toByteArray();
|
byte[] result = baos.toByteArray();
|
||||||
return WebResponseUtils.bytesToWebResponse(
|
return WebResponseUtils.bytesToWebResponse(
|
||||||
result,
|
result,
|
||||||
|
|||||||
-5
@@ -98,11 +98,6 @@ public class ConfigController {
|
|||||||
if (applicationContext.containsBean("license")) {
|
if (applicationContext.containsBean("license")) {
|
||||||
configData.put("license", applicationContext.getBean("license", String.class));
|
configData.put("license", applicationContext.getBean("license", String.class));
|
||||||
}
|
}
|
||||||
if (applicationContext.containsBean("GoogleDriveEnabled")) {
|
|
||||||
configData.put(
|
|
||||||
"GoogleDriveEnabled",
|
|
||||||
applicationContext.getBean("GoogleDriveEnabled", Boolean.class));
|
|
||||||
}
|
|
||||||
if (applicationContext.containsBean("SSOAutoLogin")) {
|
if (applicationContext.containsBean("SSOAutoLogin")) {
|
||||||
configData.put(
|
configData.put(
|
||||||
"SSOAutoLogin",
|
"SSOAutoLogin",
|
||||||
|
|||||||
+56
-8
@@ -35,6 +35,8 @@ import stirling.software.SPDF.model.api.security.SanitizePdfRequest;
|
|||||||
import stirling.software.common.annotations.AutoJobPostMapping;
|
import stirling.software.common.annotations.AutoJobPostMapping;
|
||||||
import stirling.software.common.annotations.api.SecurityApi;
|
import stirling.software.common.annotations.api.SecurityApi;
|
||||||
import stirling.software.common.service.CustomPDFDocumentFactory;
|
import stirling.software.common.service.CustomPDFDocumentFactory;
|
||||||
|
import stirling.software.common.service.JobProgressService;
|
||||||
|
import stirling.software.common.service.JobProgressTracker;
|
||||||
import stirling.software.common.util.WebResponseUtils;
|
import stirling.software.common.util.WebResponseUtils;
|
||||||
|
|
||||||
@SecurityApi
|
@SecurityApi
|
||||||
@@ -42,6 +44,7 @@ import stirling.software.common.util.WebResponseUtils;
|
|||||||
public class SanitizeController {
|
public class SanitizeController {
|
||||||
|
|
||||||
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
||||||
|
private final JobProgressService jobProgressService;
|
||||||
|
|
||||||
@AutoJobPostMapping(consumes = "multipart/form-data", value = "/sanitize-pdf")
|
@AutoJobPostMapping(consumes = "multipart/form-data", value = "/sanitize-pdf")
|
||||||
@StandardPdfResponse
|
@StandardPdfResponse
|
||||||
@@ -61,28 +64,54 @@ public class SanitizeController {
|
|||||||
boolean removeFonts = Boolean.TRUE.equals(request.getRemoveFonts());
|
boolean removeFonts = Boolean.TRUE.equals(request.getRemoveFonts());
|
||||||
|
|
||||||
PDDocument document = pdfDocumentFactory.load(inputFile, true);
|
PDDocument document = pdfDocumentFactory.load(inputFile, true);
|
||||||
|
|
||||||
|
int pageCount = Math.max(1, document.getNumberOfPages());
|
||||||
|
int pageSteps = 0;
|
||||||
|
if (removeJavaScript) pageSteps += pageCount;
|
||||||
|
if (removeEmbeddedFiles) pageSteps += pageCount;
|
||||||
|
if (removeLinks) pageSteps += pageCount;
|
||||||
|
if (removeFonts) pageSteps += pageCount;
|
||||||
|
|
||||||
|
int metadataSteps = 0;
|
||||||
|
if (removeXMPMetadata) metadataSteps++;
|
||||||
|
if (removeMetadata) metadataSteps++;
|
||||||
|
|
||||||
|
int totalSteps = Math.max(1, pageSteps + metadataSteps);
|
||||||
|
JobProgressTracker progressTracker = jobProgressService.tracker(totalSteps);
|
||||||
|
boolean trackProgress = progressTracker.isEnabled();
|
||||||
|
|
||||||
if (removeJavaScript) {
|
if (removeJavaScript) {
|
||||||
sanitizeJavaScript(document);
|
sanitizeJavaScript(document, progressTracker, trackProgress);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (removeEmbeddedFiles) {
|
if (removeEmbeddedFiles) {
|
||||||
sanitizeEmbeddedFiles(document);
|
sanitizeEmbeddedFiles(document, progressTracker, trackProgress);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (removeXMPMetadata) {
|
if (removeXMPMetadata) {
|
||||||
sanitizeXMPMetadata(document);
|
sanitizeXMPMetadata(document);
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (removeMetadata) {
|
if (removeMetadata) {
|
||||||
sanitizeDocumentInfoMetadata(document);
|
sanitizeDocumentInfoMetadata(document);
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (removeLinks) {
|
if (removeLinks) {
|
||||||
sanitizeLinks(document);
|
sanitizeLinks(document, progressTracker, trackProgress);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (removeFonts) {
|
if (removeFonts) {
|
||||||
sanitizeFonts(document);
|
sanitizeFonts(document, progressTracker, trackProgress);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.complete();
|
||||||
}
|
}
|
||||||
|
|
||||||
return WebResponseUtils.pdfDocToWebResponse(
|
return WebResponseUtils.pdfDocToWebResponse(
|
||||||
@@ -92,7 +121,9 @@ public class SanitizeController {
|
|||||||
+ "_sanitized.pdf");
|
+ "_sanitized.pdf");
|
||||||
}
|
}
|
||||||
|
|
||||||
private void sanitizeJavaScript(PDDocument document) throws IOException {
|
private void sanitizeJavaScript(
|
||||||
|
PDDocument document, JobProgressTracker progressTracker, boolean trackProgress)
|
||||||
|
throws IOException {
|
||||||
// Get the root dictionary (catalog) of the PDF
|
// Get the root dictionary (catalog) of the PDF
|
||||||
PDDocumentCatalog catalog = document.getDocumentCatalog();
|
PDDocumentCatalog catalog = document.getDocumentCatalog();
|
||||||
|
|
||||||
@@ -140,10 +171,15 @@ public class SanitizeController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void sanitizeEmbeddedFiles(PDDocument document) {
|
private void sanitizeEmbeddedFiles(
|
||||||
|
PDDocument document, JobProgressTracker progressTracker, boolean trackProgress) {
|
||||||
PDPageTree allPages = document.getPages();
|
PDPageTree allPages = document.getPages();
|
||||||
|
|
||||||
for (PDPage page : allPages) {
|
for (PDPage page : allPages) {
|
||||||
@@ -151,6 +187,9 @@ public class SanitizeController {
|
|||||||
if (res != null && res.getCOSObject() != null) {
|
if (res != null && res.getCOSObject() != null) {
|
||||||
res.getCOSObject().removeItem(COSName.getPDFName("EmbeddedFiles"));
|
res.getCOSObject().removeItem(COSName.getPDFName("EmbeddedFiles"));
|
||||||
}
|
}
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -171,7 +210,9 @@ public class SanitizeController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void sanitizeLinks(PDDocument document) throws IOException {
|
private void sanitizeLinks(
|
||||||
|
PDDocument document, JobProgressTracker progressTracker, boolean trackProgress)
|
||||||
|
throws IOException {
|
||||||
for (PDPage page : document.getPages()) {
|
for (PDPage page : document.getPages()) {
|
||||||
for (PDAnnotation annotation : page.getAnnotations()) {
|
for (PDAnnotation annotation : page.getAnnotations()) {
|
||||||
if (annotation != null && annotation instanceof PDAnnotationLink linkAnnotation) {
|
if (annotation != null && annotation instanceof PDAnnotationLink linkAnnotation) {
|
||||||
@@ -183,16 +224,23 @@ public class SanitizeController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void sanitizeFonts(PDDocument document) {
|
private void sanitizeFonts(
|
||||||
|
PDDocument document, JobProgressTracker progressTracker, boolean trackProgress) {
|
||||||
for (PDPage page : document.getPages()) {
|
for (PDPage page : document.getPages()) {
|
||||||
if (page != null
|
if (page != null
|
||||||
&& page.getResources() != null
|
&& page.getResources() != null
|
||||||
&& page.getResources().getCOSObject() != null) {
|
&& page.getResources().getCOSObject() != null) {
|
||||||
page.getResources().getCOSObject().removeItem(COSName.getPDFName("Font"));
|
page.getResources().getCOSObject().removeItem(COSName.getPDFName("Font"));
|
||||||
}
|
}
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+15
@@ -40,6 +40,8 @@ import stirling.software.SPDF.model.api.security.AddWatermarkRequest;
|
|||||||
import stirling.software.common.annotations.AutoJobPostMapping;
|
import stirling.software.common.annotations.AutoJobPostMapping;
|
||||||
import stirling.software.common.annotations.api.SecurityApi;
|
import stirling.software.common.annotations.api.SecurityApi;
|
||||||
import stirling.software.common.service.CustomPDFDocumentFactory;
|
import stirling.software.common.service.CustomPDFDocumentFactory;
|
||||||
|
import stirling.software.common.service.JobProgressService;
|
||||||
|
import stirling.software.common.service.JobProgressTracker;
|
||||||
import stirling.software.common.util.PdfUtils;
|
import stirling.software.common.util.PdfUtils;
|
||||||
import stirling.software.common.util.WebResponseUtils;
|
import stirling.software.common.util.WebResponseUtils;
|
||||||
|
|
||||||
@@ -48,6 +50,7 @@ import stirling.software.common.util.WebResponseUtils;
|
|||||||
public class WatermarkController {
|
public class WatermarkController {
|
||||||
|
|
||||||
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
private final CustomPDFDocumentFactory pdfDocumentFactory;
|
||||||
|
private final JobProgressService jobProgressService;
|
||||||
|
|
||||||
@InitBinder
|
@InitBinder
|
||||||
public void initBinder(WebDataBinder binder) {
|
public void initBinder(WebDataBinder binder) {
|
||||||
@@ -100,6 +103,10 @@ public class WatermarkController {
|
|||||||
PDDocument document = pdfDocumentFactory.load(pdfFile);
|
PDDocument document = pdfDocumentFactory.load(pdfFile);
|
||||||
|
|
||||||
// Create a page in the document
|
// Create a page in the document
|
||||||
|
int totalPages = Math.max(1, document.getNumberOfPages());
|
||||||
|
JobProgressTracker progressTracker = jobProgressService.tracker(totalPages);
|
||||||
|
boolean trackProgress = progressTracker.isEnabled();
|
||||||
|
|
||||||
for (PDPage page : document.getPages()) {
|
for (PDPage page : document.getPages()) {
|
||||||
|
|
||||||
// Get the page's content stream
|
// Get the page's content stream
|
||||||
@@ -138,6 +145,10 @@ public class WatermarkController {
|
|||||||
|
|
||||||
// Close the content stream
|
// Close the content stream
|
||||||
contentStream.close();
|
contentStream.close();
|
||||||
|
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (convertPdfToImage) {
|
if (convertPdfToImage) {
|
||||||
@@ -146,6 +157,10 @@ public class WatermarkController {
|
|||||||
document = convertedPdf;
|
document = convertedPdf;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.complete();
|
||||||
|
}
|
||||||
|
|
||||||
return WebResponseUtils.pdfDocToWebResponse(
|
return WebResponseUtils.pdfDocToWebResponse(
|
||||||
document,
|
document,
|
||||||
Filenames.toSimpleFileName(pdfFile.getOriginalFilename())
|
Filenames.toSimpleFileName(pdfFile.getOriginalFilename())
|
||||||
|
|||||||
@@ -11,6 +11,8 @@ import org.apache.pdfbox.pdmodel.PDResources;
|
|||||||
import org.apache.pdfbox.pdmodel.graphics.PDXObject;
|
import org.apache.pdfbox.pdmodel.graphics.PDXObject;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import stirling.software.common.service.JobProgressTracker;
|
||||||
|
|
||||||
/** Service class responsible for removing image objects from a PDF document. */
|
/** Service class responsible for removing image objects from a PDF document. */
|
||||||
@Service
|
@Service
|
||||||
public class PdfImageRemovalService {
|
public class PdfImageRemovalService {
|
||||||
@@ -26,6 +28,13 @@ public class PdfImageRemovalService {
|
|||||||
* @throws IOException If an error occurs while processing the PDF document.
|
* @throws IOException If an error occurs while processing the PDF document.
|
||||||
*/
|
*/
|
||||||
public PDDocument removeImagesFromPdf(PDDocument document) throws IOException {
|
public PDDocument removeImagesFromPdf(PDDocument document) throws IOException {
|
||||||
|
return removeImagesFromPdf(document, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public PDDocument removeImagesFromPdf(PDDocument document, JobProgressTracker progressTracker)
|
||||||
|
throws IOException {
|
||||||
|
boolean trackProgress = progressTracker != null && progressTracker.isEnabled();
|
||||||
|
|
||||||
// Iterate over each page in the PDF document
|
// Iterate over each page in the PDF document
|
||||||
for (PDPage page : document.getPages()) {
|
for (PDPage page : document.getPages()) {
|
||||||
PDResources resources = page.getResources();
|
PDResources resources = page.getResources();
|
||||||
@@ -45,6 +54,10 @@ public class PdfImageRemovalService {
|
|||||||
for (COSName name : namesToRemove) {
|
for (COSName name : namesToRemove) {
|
||||||
resources.put(name, (PDXObject) null);
|
resources.put(name, (PDXObject) null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (trackProgress) {
|
||||||
|
progressTracker.advance();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return document;
|
return document;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1916,6 +1916,7 @@ fileManager.storageError=Storage error occurred
|
|||||||
fileManager.storageLow=Storage is running low. Consider removing old files.
|
fileManager.storageLow=Storage is running low. Consider removing old files.
|
||||||
fileManager.uploadError=Failed to upload some files.
|
fileManager.uploadError=Failed to upload some files.
|
||||||
fileManager.supportMessage=Powered by browser database storage for unlimited capacity
|
fileManager.supportMessage=Powered by browser database storage for unlimited capacity
|
||||||
|
fileManager.loadingFiles=Loading files...
|
||||||
|
|
||||||
# Page Editor
|
# Page Editor
|
||||||
pageEditor.title=Page Editor
|
pageEditor.title=Page Editor
|
||||||
@@ -1945,6 +1946,25 @@ viewer.zoomIn=Zoom in
|
|||||||
# Tool Picker
|
# Tool Picker
|
||||||
toolPicker.searchPlaceholder=Search tools...
|
toolPicker.searchPlaceholder=Search tools...
|
||||||
toolPicker.noToolsFound=No tools found
|
toolPicker.noToolsFound=No tools found
|
||||||
|
toolPanel.toggle.legacy=Switch to legacy mode
|
||||||
|
toolPanel.toggle.sidebar=Switch to sidebar mode
|
||||||
|
toolPanel.placeholder=Choose a tool to get started
|
||||||
|
toolPanel.legacy.heading=All tools (legacy view)
|
||||||
|
toolPanel.legacy.tagline=Browse and launch tools while keeping the classic full-width gallery.
|
||||||
|
toolPanel.legacy.descriptionsOn=Showing descriptions
|
||||||
|
toolPanel.legacy.descriptionsOff=Descriptions hidden
|
||||||
|
toolPanel.legacy.noResults=Try adjusting your search or toggle descriptions to find what you need.
|
||||||
|
toolPanel.legacy.matchedSynonym=Matches "{{text}}"
|
||||||
|
toolPanel.modePrompt.title=Choose how you browse tools
|
||||||
|
toolPanel.modePrompt.description=Preview both layouts and decide how you want to explore Stirling PDF tools.
|
||||||
|
toolPanel.modePrompt.sidebarTitle=Advanced sidebar
|
||||||
|
toolPanel.modePrompt.sidebarDescription=Keep tools alongside your workspace for quick switching.
|
||||||
|
toolPanel.modePrompt.recommended=Recommended
|
||||||
|
toolPanel.modePrompt.chooseSidebar=Use advanced sidebar
|
||||||
|
toolPanel.modePrompt.legacyTitle=Legacy fullscreen
|
||||||
|
toolPanel.modePrompt.legacyDescription=Browse every tool in a catalogue that covers the workspace until you pick one.
|
||||||
|
toolPanel.modePrompt.chooseLegacy=Use legacy fullscreen
|
||||||
|
toolPanel.modePrompt.dismiss=Maybe later
|
||||||
pageEditor.reset=Reset Changes
|
pageEditor.reset=Reset Changes
|
||||||
pageEditor.zoomIn=Zoom In
|
pageEditor.zoomIn=Zoom In
|
||||||
pageEditor.zoomOut=Zoom Out
|
pageEditor.zoomOut=Zoom Out
|
||||||
@@ -1957,3 +1977,39 @@ viewer.nextPage=Next Page
|
|||||||
viewer.pageNavigation=Page Navigation
|
viewer.pageNavigation=Page Navigation
|
||||||
viewer.currentPage=Current Page
|
viewer.currentPage=Current Page
|
||||||
viewer.totalPages=Total Pages
|
viewer.totalPages=Total Pages
|
||||||
|
toolPanel.legacy.favorites=Favourites
|
||||||
|
toolPanel.legacy.recent=Recently used
|
||||||
|
toolPanel.legacy.favorite=Add to favourites
|
||||||
|
toolPanel.legacy.unfavorite=Remove from favourites
|
||||||
|
toolPanel.legacy.settings.title=Customise appearance
|
||||||
|
toolPanel.legacy.settings.iconBackground.label=Tool icon background
|
||||||
|
toolPanel.legacy.settings.iconBackground.description=When to show coloured backgrounds behind tool icons
|
||||||
|
toolPanel.legacy.settings.iconBackground.none=None
|
||||||
|
toolPanel.legacy.settings.iconBackground.hover=On hover
|
||||||
|
toolPanel.legacy.settings.iconBackground.always=Always
|
||||||
|
toolPanel.legacy.settings.iconColor.label=Tool icon colour
|
||||||
|
toolPanel.legacy.settings.iconColor.description=Colour scheme for tool icons
|
||||||
|
toolPanel.legacy.settings.iconColor.colored=Coloured
|
||||||
|
toolPanel.legacy.settings.iconColor.vibrant=Vibrant
|
||||||
|
toolPanel.legacy.settings.iconColor.monochrome=Monochrome
|
||||||
|
toolPanel.legacy.settings.sectionTitle.label=Section titles
|
||||||
|
toolPanel.legacy.settings.sectionTitle.description=Colour for category section titles
|
||||||
|
toolPanel.legacy.settings.sectionTitle.colored=Coloured
|
||||||
|
toolPanel.legacy.settings.sectionTitle.neutral=Neutral
|
||||||
|
toolPanel.legacy.settings.headerIcon.label=Section header icons
|
||||||
|
toolPanel.legacy.settings.headerIcon.description=Colour for Favourites/Recent icons
|
||||||
|
toolPanel.legacy.settings.headerIcon.colored=Coloured
|
||||||
|
toolPanel.legacy.settings.headerIcon.monochrome=Monochrome
|
||||||
|
toolPanel.legacy.settings.headerBadge.label=Section header badges
|
||||||
|
toolPanel.legacy.settings.headerBadge.description=Colour for count badges in section headers
|
||||||
|
toolPanel.legacy.settings.headerBadge.colored=Coloured
|
||||||
|
toolPanel.legacy.settings.headerBadge.neutral=Neutral
|
||||||
|
toolPanel.legacy.settings.border.label=Tool item borders
|
||||||
|
toolPanel.legacy.settings.border.description=Show borders around tool items
|
||||||
|
toolPanel.legacy.settings.border.visible=Visible
|
||||||
|
toolPanel.legacy.settings.border.hidden=Hidden
|
||||||
|
toolPanel.legacy.settings.hover.label=Hover effect intensity
|
||||||
|
toolPanel.legacy.settings.hover.description=How prominent the hover effect should be
|
||||||
|
toolPanel.legacy.settings.hover.subtle=Subtle
|
||||||
|
toolPanel.legacy.settings.hover.moderate=Moderate
|
||||||
|
toolPanel.legacy.settings.hover.prominent=Prominent
|
||||||
|
|||||||
@@ -76,11 +76,6 @@ premium:
|
|||||||
author: username
|
author: username
|
||||||
creator: Stirling-PDF
|
creator: Stirling-PDF
|
||||||
producer: Stirling-PDF
|
producer: Stirling-PDF
|
||||||
googleDrive:
|
|
||||||
enabled: false
|
|
||||||
clientId: ''
|
|
||||||
apiKey: ''
|
|
||||||
appId: ''
|
|
||||||
enterpriseFeatures:
|
enterpriseFeatures:
|
||||||
audit:
|
audit:
|
||||||
enabled: true # Enable audit logging
|
enabled: true # Enable audit logging
|
||||||
|
|||||||
@@ -422,10 +422,6 @@
|
|||||||
<span th:text="#{fileChooser.or}" style="margin: 0 5px;"></span>
|
<span th:text="#{fileChooser.or}" style="margin: 0 5px;"></span>
|
||||||
<span th:text="#{fileChooser.dragAndDrop}" id="dragAndDrop"></span>
|
<span th:text="#{fileChooser.dragAndDrop}" id="dragAndDrop"></span>
|
||||||
</div>
|
</div>
|
||||||
<hr th:if="${@GoogleDriveEnabled == true}" class="horizontal-divider" >
|
|
||||||
</div>
|
|
||||||
<div th:if="${@GoogleDriveEnabled == true}" th:id="${name}+'-google-drive-button'" class="google-drive-button" th:attr="data-name=${name}, data-multiple=${!disableMultipleFiles}, data-accept=${accept}" >
|
|
||||||
<img th:src="@{'/images/google-drive.svg'}" alt="google drive">
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="selected-files flex-wrap"></div>
|
<div class="selected-files flex-wrap"></div>
|
||||||
@@ -443,16 +439,4 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script th:src="@{'/js/fileInput.js'}" type="module"></script>
|
<script th:src="@{'/js/fileInput.js'}" type="module"></script>
|
||||||
|
|
||||||
<div th:if="${@GoogleDriveEnabled == true}" >
|
|
||||||
<script type="text/javascript" th:src="@{'/js/googleFilePicker.js'}"></script>
|
|
||||||
<script async defer src="https://apis.google.com/js/api.js" onload="gapiLoaded()"></script>
|
|
||||||
<script async defer src="https://accounts.google.com/gsi/client" onload="gisLoaded()"></script>
|
|
||||||
|
|
||||||
<script th:inline="javascript">
|
|
||||||
window.stirlingPDF.GoogleDriveClientId = /*[[${@GoogleDriveConfig.getClientId()}]]*/ null;
|
|
||||||
window.stirlingPDF.GoogleDriveApiKey = /*[[${@GoogleDriveConfig.getApiKey()}]]*/ null;
|
|
||||||
window.stirlingPDF.GoogleDriveAppId = /*[[${@GoogleDriveConfig.getAppId()}]]*/ null;
|
|
||||||
</script>
|
|
||||||
</div>
|
|
||||||
</th:block>
|
</th:block>
|
||||||
|
|||||||
+3
-1
@@ -14,17 +14,19 @@ import org.mockito.Mock;
|
|||||||
import org.mockito.MockitoAnnotations;
|
import org.mockito.MockitoAnnotations;
|
||||||
|
|
||||||
import stirling.software.common.service.CustomPDFDocumentFactory;
|
import stirling.software.common.service.CustomPDFDocumentFactory;
|
||||||
|
import stirling.software.common.service.JobProgressService;
|
||||||
|
|
||||||
class RearrangePagesPDFControllerTest {
|
class RearrangePagesPDFControllerTest {
|
||||||
|
|
||||||
@Mock private CustomPDFDocumentFactory mockPdfDocumentFactory;
|
@Mock private CustomPDFDocumentFactory mockPdfDocumentFactory;
|
||||||
|
@Mock private JobProgressService mockJobProgressService;
|
||||||
|
|
||||||
private RearrangePagesPDFController sut;
|
private RearrangePagesPDFController sut;
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
void setUp() {
|
void setUp() {
|
||||||
MockitoAnnotations.openMocks(this);
|
MockitoAnnotations.openMocks(this);
|
||||||
sut = new RearrangePagesPDFController(mockPdfDocumentFactory);
|
sut = new RearrangePagesPDFController(mockPdfDocumentFactory, mockJobProgressService);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Tests the behavior of the oddEvenMerge method when there are no pages in the document. */
|
/** Tests the behavior of the oddEvenMerge method when there are no pages in the document. */
|
||||||
|
|||||||
+7
@@ -22,11 +22,14 @@ import org.springframework.mock.web.MockMultipartFile;
|
|||||||
|
|
||||||
import stirling.software.SPDF.model.api.general.RotatePDFRequest;
|
import stirling.software.SPDF.model.api.general.RotatePDFRequest;
|
||||||
import stirling.software.common.service.CustomPDFDocumentFactory;
|
import stirling.software.common.service.CustomPDFDocumentFactory;
|
||||||
|
import stirling.software.common.service.JobProgressService;
|
||||||
|
import stirling.software.common.service.JobProgressTracker;
|
||||||
|
|
||||||
@ExtendWith(MockitoExtension.class)
|
@ExtendWith(MockitoExtension.class)
|
||||||
public class RotationControllerTest {
|
public class RotationControllerTest {
|
||||||
|
|
||||||
@Mock private CustomPDFDocumentFactory pdfDocumentFactory;
|
@Mock private CustomPDFDocumentFactory pdfDocumentFactory;
|
||||||
|
@Mock private JobProgressService jobProgressService;
|
||||||
|
|
||||||
@InjectMocks private RotationController rotationController;
|
@InjectMocks private RotationController rotationController;
|
||||||
|
|
||||||
@@ -42,12 +45,16 @@ public class RotationControllerTest {
|
|||||||
PDDocument mockDocument = mock(PDDocument.class);
|
PDDocument mockDocument = mock(PDDocument.class);
|
||||||
PDPageTree mockPages = mock(PDPageTree.class);
|
PDPageTree mockPages = mock(PDPageTree.class);
|
||||||
PDPage mockPage = mock(PDPage.class);
|
PDPage mockPage = mock(PDPage.class);
|
||||||
|
JobProgressTracker mockTracker = mock(JobProgressTracker.class);
|
||||||
|
|
||||||
when(pdfDocumentFactory.load(request)).thenReturn(mockDocument);
|
when(pdfDocumentFactory.load(request)).thenReturn(mockDocument);
|
||||||
when(mockDocument.getPages()).thenReturn(mockPages);
|
when(mockDocument.getPages()).thenReturn(mockPages);
|
||||||
|
when(mockPages.getCount()).thenReturn(1);
|
||||||
when(mockPages.iterator())
|
when(mockPages.iterator())
|
||||||
.thenReturn(java.util.Collections.singletonList(mockPage).iterator());
|
.thenReturn(java.util.Collections.singletonList(mockPage).iterator());
|
||||||
when(mockPage.getRotation()).thenReturn(0);
|
when(mockPage.getRotation()).thenReturn(0);
|
||||||
|
when(jobProgressService.tracker(1)).thenReturn(mockTracker);
|
||||||
|
when(mockTracker.isEnabled()).thenReturn(false);
|
||||||
|
|
||||||
// Act
|
// Act
|
||||||
ResponseEntity<byte[]> response = rotationController.rotatePDF(request);
|
ResponseEntity<byte[]> response = rotationController.rotatePDF(request);
|
||||||
|
|||||||
-14
@@ -12,7 +12,6 @@ import org.springframework.core.annotation.Order;
|
|||||||
import stirling.software.common.model.ApplicationProperties;
|
import stirling.software.common.model.ApplicationProperties;
|
||||||
import stirling.software.common.model.ApplicationProperties.EnterpriseEdition;
|
import stirling.software.common.model.ApplicationProperties.EnterpriseEdition;
|
||||||
import stirling.software.common.model.ApplicationProperties.Premium;
|
import stirling.software.common.model.ApplicationProperties.Premium;
|
||||||
import stirling.software.common.model.ApplicationProperties.Premium.ProFeatures.GoogleDrive;
|
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
@Order(Ordered.HIGHEST_PRECEDENCE)
|
@Order(Ordered.HIGHEST_PRECEDENCE)
|
||||||
@@ -55,19 +54,6 @@ public class EEAppConfig {
|
|||||||
return applicationProperties.getPremium().getProFeatures().isSsoAutoLogin();
|
return applicationProperties.getPremium().getProFeatures().isSsoAutoLogin();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Profile("security")
|
|
||||||
@Bean(name = "GoogleDriveEnabled")
|
|
||||||
@Primary
|
|
||||||
public boolean googleDriveEnabled() {
|
|
||||||
return runningProOrHigher()
|
|
||||||
&& applicationProperties.getPremium().getProFeatures().getGoogleDrive().isEnabled();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Bean(name = "GoogleDriveConfig")
|
|
||||||
public GoogleDrive googleDriveConfig() {
|
|
||||||
return applicationProperties.getPremium().getProFeatures().getGoogleDrive();
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: Remove post migration
|
// TODO: Remove post migration
|
||||||
@SuppressWarnings("deprecation")
|
@SuppressWarnings("deprecation")
|
||||||
public void migrateEnterpriseSettingsToPremium(ApplicationProperties applicationProperties) {
|
public void migrateEnterpriseSettingsToPremium(ApplicationProperties applicationProperties) {
|
||||||
|
|||||||
@@ -50,7 +50,14 @@ docker-compose -f docker/compose/docker-compose.fat.yml up --build
|
|||||||
- **Custom Ports**: Modify port mappings in docker-compose files
|
- **Custom Ports**: Modify port mappings in docker-compose files
|
||||||
- **Memory Limits**: Adjust memory limits per variant (2G ultra-lite, 4G standard, 6G fat)
|
- **Memory Limits**: Adjust memory limits per variant (2G ultra-lite, 4G standard, 6G fat)
|
||||||
|
|
||||||
|
### [Google Drive Integration](https://developers.google.com/workspace/drive/picker/guides/overview)
|
||||||
|
|
||||||
|
- **VITE_GOOGLE_DRIVE_CLIENT_ID**: [OAuth 2.0 Client ID](https://console.cloud.google.com/auth/clients/create)
|
||||||
|
- **VITE_GOOGLE_DRIVE_API_KEY**: [Create New API](https://console.cloud.google.com/apis)
|
||||||
|
- **VITE_GOOGLE_DRIVE_APP_ID**: This is your [project number](https://console.cloud.google.com/iam-admin/settings) in the GoogleCloud Settings
|
||||||
|
|
||||||
## Development vs Production
|
## Development vs Production
|
||||||
|
|
||||||
- **Development**: Keep backend port 8080 exposed for debugging
|
- **Development**: Keep backend port 8080 exposed for debugging
|
||||||
- **Production**: Remove backend port exposure, use only frontend proxy
|
- **Production**: Remove backend port exposure, use only frontend proxy
|
||||||
|
|
||||||
|
|||||||
@@ -47,6 +47,9 @@ services:
|
|||||||
- "3000:80"
|
- "3000:80"
|
||||||
environment:
|
environment:
|
||||||
BACKEND_URL: http://backend:8080
|
BACKEND_URL: http://backend:8080
|
||||||
|
#VITE_GOOGLE_DRIVE_CLIENT_ID: <INSERT_YOUR_CLIENT_ID_HERE>
|
||||||
|
#VITE_GOOGLE_DRIVE_API_KEY: <INSERT_YOUR_API_KEY_HERE>
|
||||||
|
#VITE_GOOGLE_DRIVE_APP_ID: <INSERT_YOUR_APP_ID_HERE>
|
||||||
depends_on:
|
depends_on:
|
||||||
- backend
|
- backend
|
||||||
networks:
|
networks:
|
||||||
|
|||||||
@@ -44,6 +44,9 @@ services:
|
|||||||
- "3000:80"
|
- "3000:80"
|
||||||
environment:
|
environment:
|
||||||
BACKEND_URL: http://backend:8080
|
BACKEND_URL: http://backend:8080
|
||||||
|
#VITE_GOOGLE_DRIVE_CLIENT_ID: <INSERT_YOUR_CLIENT_ID_HERE>
|
||||||
|
#VITE_GOOGLE_DRIVE_API_KEY: <INSERT_YOUR_API_KEY_HERE>
|
||||||
|
#VITE_GOOGLE_DRIVE_APP_ID: <INSERT_YOUR_APP_ID_HERE>
|
||||||
depends_on:
|
depends_on:
|
||||||
- backend
|
- backend
|
||||||
networks:
|
networks:
|
||||||
|
|||||||
@@ -46,6 +46,9 @@ services:
|
|||||||
- "3000:80"
|
- "3000:80"
|
||||||
environment:
|
environment:
|
||||||
BACKEND_URL: http://backend:8080
|
BACKEND_URL: http://backend:8080
|
||||||
|
#VITE_GOOGLE_DRIVE_CLIENT_ID: <INSERT_YOUR_CLIENT_ID_HERE>
|
||||||
|
#VITE_GOOGLE_DRIVE_API_KEY: <INSERT_YOUR_API_KEY_HERE>
|
||||||
|
#VITE_GOOGLE_DRIVE_APP_ID: <INSERT_YOUR_APP_ID_HERE>
|
||||||
depends_on:
|
depends_on:
|
||||||
- backend
|
- backend
|
||||||
networks:
|
networks:
|
||||||
|
|||||||
@@ -1,9 +1,18 @@
|
|||||||
// @ts-check
|
// @ts-check
|
||||||
|
|
||||||
import eslint from '@eslint/js';
|
import eslint from '@eslint/js';
|
||||||
|
import globals from "globals";
|
||||||
import { defineConfig } from 'eslint/config';
|
import { defineConfig } from 'eslint/config';
|
||||||
import tseslint from 'typescript-eslint';
|
import tseslint from 'typescript-eslint';
|
||||||
|
|
||||||
|
const srcGlobs = [
|
||||||
|
'src/**/*.{js,mjs,jsx,ts,tsx}',
|
||||||
|
];
|
||||||
|
const nodeGlobs = [
|
||||||
|
'scripts/**/*.{js,ts,mjs}',
|
||||||
|
'*.config.{js,ts,mjs}',
|
||||||
|
];
|
||||||
|
|
||||||
export default defineConfig(
|
export default defineConfig(
|
||||||
eslint.configs.recommended,
|
eslint.configs.recommended,
|
||||||
tseslint.configs.recommended,
|
tseslint.configs.recommended,
|
||||||
@@ -15,7 +24,6 @@ export default defineConfig(
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
rules: {
|
rules: {
|
||||||
"no-undef": "off", // Temporarily disabled until codebase conformant
|
|
||||||
"@typescript-eslint/no-empty-object-type": [
|
"@typescript-eslint/no-empty-object-type": [
|
||||||
"error",
|
"error",
|
||||||
{
|
{
|
||||||
@@ -38,5 +46,23 @@ export default defineConfig(
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
}
|
},
|
||||||
|
// Config for browser scripts
|
||||||
|
{
|
||||||
|
files: srcGlobs,
|
||||||
|
languageOptions: {
|
||||||
|
globals: {
|
||||||
|
...globals.browser,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
// Config for node scripts
|
||||||
|
{
|
||||||
|
files: nodeGlobs,
|
||||||
|
languageOptions: {
|
||||||
|
globals: {
|
||||||
|
...globals.node,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
Generated
+98
-4
@@ -41,6 +41,7 @@
|
|||||||
"@tanstack/react-virtual": "^3.13.12",
|
"@tanstack/react-virtual": "^3.13.12",
|
||||||
"autoprefixer": "^10.4.21",
|
"autoprefixer": "^10.4.21",
|
||||||
"axios": "^1.12.2",
|
"axios": "^1.12.2",
|
||||||
|
"globals": "^16.4.0",
|
||||||
"i18next": "^25.5.2",
|
"i18next": "^25.5.2",
|
||||||
"i18next-browser-languagedetector": "^8.2.0",
|
"i18next-browser-languagedetector": "^8.2.0",
|
||||||
"i18next-http-backend": "^3.0.2",
|
"i18next-http-backend": "^3.0.2",
|
||||||
@@ -53,6 +54,7 @@
|
|||||||
"react-dom": "^19.1.1",
|
"react-dom": "^19.1.1",
|
||||||
"react-i18next": "^15.7.3",
|
"react-i18next": "^15.7.3",
|
||||||
"react-router-dom": "^7.9.1",
|
"react-router-dom": "^7.9.1",
|
||||||
|
"signature_pad": "^5.0.4",
|
||||||
"tailwindcss": "^4.1.13",
|
"tailwindcss": "^4.1.13",
|
||||||
"web-vitals": "^5.1.0"
|
"web-vitals": "^5.1.0"
|
||||||
},
|
},
|
||||||
@@ -65,6 +67,10 @@
|
|||||||
"@testing-library/jest-dom": "^6.8.0",
|
"@testing-library/jest-dom": "^6.8.0",
|
||||||
"@testing-library/react": "^16.3.0",
|
"@testing-library/react": "^16.3.0",
|
||||||
"@testing-library/user-event": "^14.6.1",
|
"@testing-library/user-event": "^14.6.1",
|
||||||
|
"@types/gapi": "^0.0.47",
|
||||||
|
"@types/gapi.client.drive-v3": "^0.0.5",
|
||||||
|
"@types/google.accounts": "^0.0.18",
|
||||||
|
"@types/google.picker": "^0.0.51",
|
||||||
"@types/node": "^24.5.2",
|
"@types/node": "^24.5.2",
|
||||||
"@types/react": "^19.1.13",
|
"@types/react": "^19.1.13",
|
||||||
"@types/react-dom": "^19.1.9",
|
"@types/react-dom": "^19.1.9",
|
||||||
@@ -1760,6 +1766,19 @@
|
|||||||
"mlly": "^1.7.4"
|
"mlly": "^1.7.4"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@iconify/utils/node_modules/globals": {
|
||||||
|
"version": "15.15.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/globals/-/globals-15.15.0.tgz",
|
||||||
|
"integrity": "sha512-7ACyT3wmyp3I61S4fG682L0VA2RGD9otkqGJIwNUMF1SWUombIIk+af1unuDYgMm082aHYwD+mzJvv9Iu8dsgg==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@isaacs/cliui": {
|
"node_modules/@isaacs/cliui": {
|
||||||
"version": "8.0.2",
|
"version": "8.0.2",
|
||||||
"resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz",
|
||||||
@@ -1995,6 +2014,28 @@
|
|||||||
"react": "^18.x || ^19.x"
|
"react": "^18.x || ^19.x"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@maxim_mazurok/gapi.client.discovery-v1": {
|
||||||
|
"version": "0.4.20200806",
|
||||||
|
"resolved": "https://registry.npmjs.org/@maxim_mazurok/gapi.client.discovery-v1/-/gapi.client.discovery-v1-0.4.20200806.tgz",
|
||||||
|
"integrity": "sha512-Jeo/KZqK39DI6ExXHcJ4lqnn1O/wEqboQ6eQ8WnNpu5eJ7wUnX/C5KazOgs1aRhnIB/dVzDe8wm62nmtkMIoaw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@types/gapi.client": "*",
|
||||||
|
"@types/gapi.client.discovery-v1": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@maxim_mazurok/gapi.client.drive-v3": {
|
||||||
|
"version": "0.1.20250930",
|
||||||
|
"resolved": "https://registry.npmjs.org/@maxim_mazurok/gapi.client.drive-v3/-/gapi.client.drive-v3-0.1.20250930.tgz",
|
||||||
|
"integrity": "sha512-zNR7HtaFl2Pvf8Ck2zP8cppUst7ouY2isKn7hrGf6hQ4/0ULsu19qMRSQgRb0HxBYcGjak7kGK4pZI4a2z4CWQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@types/gapi.client": "*",
|
||||||
|
"@types/gapi.client.discovery-v1": "*"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@mui/core-downloads-tracker": {
|
"node_modules/@mui/core-downloads-tracker": {
|
||||||
"version": "7.3.2",
|
"version": "7.3.2",
|
||||||
"resolved": "https://registry.npmjs.org/@mui/core-downloads-tracker/-/core-downloads-tracker-7.3.2.tgz",
|
"resolved": "https://registry.npmjs.org/@mui/core-downloads-tracker/-/core-downloads-tracker-7.3.2.tgz",
|
||||||
@@ -3581,6 +3622,54 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
|
"node_modules/@types/gapi": {
|
||||||
|
"version": "0.0.47",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/gapi/-/gapi-0.0.47.tgz",
|
||||||
|
"integrity": "sha512-/ZsLuq6BffMgbKMtZyDZ8vwQvTyKhKQ1G2K6VyWCgtHHhfSSXbk4+4JwImZiTjWNXfI2q1ZStAwFFHSkNoTkHA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/@types/gapi.client": {
|
||||||
|
"version": "1.0.8",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/gapi.client/-/gapi.client-1.0.8.tgz",
|
||||||
|
"integrity": "sha512-qJQUmmumbYym3Amax0S8CVzuSngcXsC1fJdwRS2zeW5lM63zXkw4wJFP+bG0jzgi0R6EsJKoHnGNVTDbOyG1ng==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/@types/gapi.client.discovery-v1": {
|
||||||
|
"version": "0.0.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/gapi.client.discovery-v1/-/gapi.client.discovery-v1-0.0.4.tgz",
|
||||||
|
"integrity": "sha512-uevhRumNE65F5mf2gABLaReOmbFSXONuzFZjNR3dYv6BmkHg+wciubHrfBAsp3554zNo3Dcg6dUAlwMqQfpwjQ==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@maxim_mazurok/gapi.client.discovery-v1": "latest"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@types/gapi.client.drive-v3": {
|
||||||
|
"version": "0.0.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/gapi.client.drive-v3/-/gapi.client.drive-v3-0.0.5.tgz",
|
||||||
|
"integrity": "sha512-yYBxiqMqJVBg4bns4Q28+f2XdJnd3tVA9dxQX1lXMVmzT2B+pZdyCi1u9HLwGveVlookSsAXuqfLfS9KO6MF6w==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@maxim_mazurok/gapi.client.drive-v3": "latest"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@types/google.accounts": {
|
||||||
|
"version": "0.0.18",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/google.accounts/-/google.accounts-0.0.18.tgz",
|
||||||
|
"integrity": "sha512-yHaPznll97ZnMJlPABHyeiIlLn3u6gQaUjA5k/O9lrrpgFB9VT10CKPLuKM0qTHMl50uXpW5sIcG+utm8jMOHw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/@types/google.picker": {
|
||||||
|
"version": "0.0.51",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/google.picker/-/google.picker-0.0.51.tgz",
|
||||||
|
"integrity": "sha512-z6o2J4PQTcXvlW1rtgQx65d5uEF+rMI1hzrnazKQxBONdEuYAr4AeOSH2KZy12WHPmqMX+aWYyfcZ0uktBBhhA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/@types/http-cache-semantics": {
|
"node_modules/@types/http-cache-semantics": {
|
||||||
"version": "4.0.4",
|
"version": "4.0.4",
|
||||||
"resolved": "https://registry.npmjs.org/@types/http-cache-semantics/-/http-cache-semantics-4.0.4.tgz",
|
"resolved": "https://registry.npmjs.org/@types/http-cache-semantics/-/http-cache-semantics-4.0.4.tgz",
|
||||||
@@ -6415,10 +6504,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/globals": {
|
"node_modules/globals": {
|
||||||
"version": "15.15.0",
|
"version": "16.4.0",
|
||||||
"resolved": "https://registry.npmjs.org/globals/-/globals-15.15.0.tgz",
|
"resolved": "https://registry.npmjs.org/globals/-/globals-16.4.0.tgz",
|
||||||
"integrity": "sha512-7ACyT3wmyp3I61S4fG682L0VA2RGD9otkqGJIwNUMF1SWUombIIk+af1unuDYgMm082aHYwD+mzJvv9Iu8dsgg==",
|
"integrity": "sha512-ob/2LcVVaVGCYN+r14cnwnoDPUufjiYgSqRhiFD0Q1iI4Odora5RE8Iv1D24hAz5oMophRGkGz+yuvQmmUMnMw==",
|
||||||
"dev": true,
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=18"
|
"node": ">=18"
|
||||||
@@ -9905,6 +9993,12 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "ISC"
|
"license": "ISC"
|
||||||
},
|
},
|
||||||
|
"node_modules/signature_pad": {
|
||||||
|
"version": "5.1.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/signature_pad/-/signature_pad-5.1.1.tgz",
|
||||||
|
"integrity": "sha512-BT5JJygS5BS0oV+tffPRorIud6q17bM7v/1LdQwd0o6mTqGoI25yY1NjSL99OqkekWltS4uon6p52Y8j1Zqu7g==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
"node_modules/slash": {
|
"node_modules/slash": {
|
||||||
"version": "5.1.0",
|
"version": "5.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/slash/-/slash-5.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/slash/-/slash-5.1.0.tgz",
|
||||||
|
|||||||
@@ -37,6 +37,7 @@
|
|||||||
"@tanstack/react-virtual": "^3.13.12",
|
"@tanstack/react-virtual": "^3.13.12",
|
||||||
"autoprefixer": "^10.4.21",
|
"autoprefixer": "^10.4.21",
|
||||||
"axios": "^1.12.2",
|
"axios": "^1.12.2",
|
||||||
|
"globals": "^16.4.0",
|
||||||
"i18next": "^25.5.2",
|
"i18next": "^25.5.2",
|
||||||
"i18next-browser-languagedetector": "^8.2.0",
|
"i18next-browser-languagedetector": "^8.2.0",
|
||||||
"i18next-http-backend": "^3.0.2",
|
"i18next-http-backend": "^3.0.2",
|
||||||
@@ -49,6 +50,7 @@
|
|||||||
"react-dom": "^19.1.1",
|
"react-dom": "^19.1.1",
|
||||||
"react-i18next": "^15.7.3",
|
"react-i18next": "^15.7.3",
|
||||||
"react-router-dom": "^7.9.1",
|
"react-router-dom": "^7.9.1",
|
||||||
|
"signature_pad": "^5.0.4",
|
||||||
"tailwindcss": "^4.1.13",
|
"tailwindcss": "^4.1.13",
|
||||||
"web-vitals": "^5.1.0"
|
"web-vitals": "^5.1.0"
|
||||||
},
|
},
|
||||||
@@ -104,6 +106,10 @@
|
|||||||
"@testing-library/jest-dom": "^6.8.0",
|
"@testing-library/jest-dom": "^6.8.0",
|
||||||
"@testing-library/react": "^16.3.0",
|
"@testing-library/react": "^16.3.0",
|
||||||
"@testing-library/user-event": "^14.6.1",
|
"@testing-library/user-event": "^14.6.1",
|
||||||
|
"@types/gapi": "^0.0.47",
|
||||||
|
"@types/gapi.client.drive-v3": "^0.0.5",
|
||||||
|
"@types/google.accounts": "^0.0.18",
|
||||||
|
"@types/google.picker": "^0.0.51",
|
||||||
"@types/node": "^24.5.2",
|
"@types/node": "^24.5.2",
|
||||||
"@types/react": "^19.1.13",
|
"@types/react": "^19.1.13",
|
||||||
"@types/react-dom": "^19.1.9",
|
"@types/react-dom": "^19.1.9",
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -1,9 +1,27 @@
|
|||||||
{
|
{
|
||||||
"unsavedChanges": "You have unsaved changes to your PDF. What would you like to do?",
|
"toolPanel": {
|
||||||
|
"modePrompt": {
|
||||||
|
"title": "Choose how you browse tools",
|
||||||
|
"description": "Preview both layouts and decide how you want to explore Stirling PDF tools.",
|
||||||
|
"sidebarTitle": "Sidebar mode",
|
||||||
|
"sidebarDescription": "Keep tools alongside your workspace for quick switching.",
|
||||||
|
"recommended": "Recommended",
|
||||||
|
"chooseSidebar": "Use sidebar mode",
|
||||||
|
"fullscreenTitle": "Fullscreen mode - (legacy)",
|
||||||
|
"fullscreenDescription": "Browse every tool in a catalogue that covers the workspace until you pick one.",
|
||||||
|
"chooseFullscreen": "Use fullscreen mode",
|
||||||
|
"dismiss": "Maybe later"
|
||||||
|
},
|
||||||
|
"fullscreen": {
|
||||||
|
"showDetails": "Show Details"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"unsavedChanges": "You have unsaved changes to your PDF.",
|
||||||
|
"areYouSure": "Are you sure you want to leave?",
|
||||||
"unsavedChangesTitle": "Unsaved Changes",
|
"unsavedChangesTitle": "Unsaved Changes",
|
||||||
"keepWorking": "Keep Working",
|
"keepWorking": "Keep Working",
|
||||||
"discardChanges": "Discard Changes",
|
"discardChanges": "Discard & Leave",
|
||||||
"applyAndContinue": "Apply & Continue",
|
"applyAndContinue": "Save & Leave",
|
||||||
"exportAndContinue": "Export & Continue",
|
"exportAndContinue": "Export & Continue",
|
||||||
"language": {
|
"language": {
|
||||||
"direction": "ltr"
|
"direction": "ltr"
|
||||||
@@ -65,6 +83,8 @@
|
|||||||
"save": "Save",
|
"save": "Save",
|
||||||
"saveToBrowser": "Save to Browser",
|
"saveToBrowser": "Save to Browser",
|
||||||
"download": "Download",
|
"download": "Download",
|
||||||
|
"pin": "Pin",
|
||||||
|
"unpin": "Unpin",
|
||||||
"undoOperationTooltip": "Click to undo the last operation and restore the original files",
|
"undoOperationTooltip": "Click to undo the last operation and restore the original files",
|
||||||
"undo": "Undo",
|
"undo": "Undo",
|
||||||
"moreOptions": "More Options",
|
"moreOptions": "More Options",
|
||||||
@@ -255,6 +275,33 @@
|
|||||||
"cacheInputs": {
|
"cacheInputs": {
|
||||||
"name": "Save form inputs",
|
"name": "Save form inputs",
|
||||||
"help": "Enable to store previously used inputs for future runs"
|
"help": "Enable to store previously used inputs for future runs"
|
||||||
|
},
|
||||||
|
"general": {
|
||||||
|
"title": "General",
|
||||||
|
"description": "Configure general application preferences.",
|
||||||
|
"autoUnzip": "Auto-unzip API responses",
|
||||||
|
"autoUnzipDescription": "Automatically extract files from ZIP responses",
|
||||||
|
"autoUnzipTooltip": "Automatically extract ZIP files returned from API operations. Disable to keep ZIP files intact. This does not affect automation workflows.",
|
||||||
|
"autoUnzipFileLimit": "Auto-unzip file limit",
|
||||||
|
"autoUnzipFileLimitDescription": "Maximum number of files to extract from ZIP",
|
||||||
|
"autoUnzipFileLimitTooltip": "Only unzip if the ZIP contains this many files or fewer. Set higher to extract larger ZIPs."
|
||||||
|
},
|
||||||
|
"hotkeys": {
|
||||||
|
"title": "Keyboard Shortcuts",
|
||||||
|
"description": "Hover a tool to see its shortcut or customise it below. Click \"Change shortcut\" and press a new key combination. Press Esc to cancel.",
|
||||||
|
"errorModifier": {
|
||||||
|
"mac": "Include ⌘ (Command), ⌥ (Option), or another modifier in your shortcut.",
|
||||||
|
"windows": "Include Ctrl, Alt, or another modifier in your shortcut."
|
||||||
|
},
|
||||||
|
"errorConflict": "Shortcut already used by {{tool}}.",
|
||||||
|
"none": "Not assigned",
|
||||||
|
"customBadge": "Custom",
|
||||||
|
"defaultLabel": "Default: {{shortcut}}",
|
||||||
|
"capturing": "Press keys… (Esc to cancel)",
|
||||||
|
"change": "Change shortcut",
|
||||||
|
"reset": "Reset",
|
||||||
|
"shortcut": "Shortcut",
|
||||||
|
"noShortcut": "No shortcut set"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"changeCreds": {
|
"changeCreds": {
|
||||||
@@ -531,7 +578,7 @@
|
|||||||
"adjustContrast": {
|
"adjustContrast": {
|
||||||
"tags": "contrast,brightness,saturation",
|
"tags": "contrast,brightness,saturation",
|
||||||
"title": "Adjust Colours/Contrast",
|
"title": "Adjust Colours/Contrast",
|
||||||
"desc": "Adjust Contrast, Saturation and Brightness of a PDF"
|
"desc": "Adjust Colors/Contrast, Saturation and Brightness of a PDF"
|
||||||
},
|
},
|
||||||
"crop": {
|
"crop": {
|
||||||
"tags": "trim,cut,resize",
|
"tags": "trim,cut,resize",
|
||||||
@@ -568,11 +615,6 @@
|
|||||||
"title": "Redact",
|
"title": "Redact",
|
||||||
"desc": "Redacts (blacks out) a PDF based on selected text, drawn shapes and/or selected page(s)"
|
"desc": "Redacts (blacks out) a PDF based on selected text, drawn shapes and/or selected page(s)"
|
||||||
},
|
},
|
||||||
"overlayPdfs": {
|
|
||||||
"tags": "overlay,combine,stack",
|
|
||||||
"title": "Overlay PDFs",
|
|
||||||
"desc": "Overlays PDFs on-top of another PDF"
|
|
||||||
},
|
|
||||||
"splitBySections": {
|
"splitBySections": {
|
||||||
"tags": "split,sections,divide",
|
"tags": "split,sections,divide",
|
||||||
"title": "Split PDF by Sections",
|
"title": "Split PDF by Sections",
|
||||||
@@ -868,6 +910,7 @@
|
|||||||
"rotate": {
|
"rotate": {
|
||||||
"title": "Rotate PDF",
|
"title": "Rotate PDF",
|
||||||
"submit": "Apply Rotation",
|
"submit": "Apply Rotation",
|
||||||
|
"selectRotation": "Select Rotation Angle (Clockwise)",
|
||||||
"error": {
|
"error": {
|
||||||
"failed": "An error occurred while rotating the PDF."
|
"failed": "An error occurred while rotating the PDF."
|
||||||
},
|
},
|
||||||
@@ -1788,8 +1831,16 @@
|
|||||||
"placeholder": "Enter your full name"
|
"placeholder": "Enter your full name"
|
||||||
},
|
},
|
||||||
"instructions": {
|
"instructions": {
|
||||||
"title": "How to add signature"
|
"title": "How to add signature",
|
||||||
|
"canvas": "After drawing your signature in the canvas, close the modal then click anywhere on the PDF to place it.",
|
||||||
|
"image": "After uploading your signature image above, click anywhere on the PDF to place it.",
|
||||||
|
"text": "After entering your name above, click anywhere on the PDF to place your signature."
|
||||||
},
|
},
|
||||||
|
"mode": {
|
||||||
|
"move": "Move Signature",
|
||||||
|
"place": "Place Signature"
|
||||||
|
},
|
||||||
|
"updateAndPlace": "Update and Place",
|
||||||
"activate": "Activate Signature Placement",
|
"activate": "Activate Signature Placement",
|
||||||
"deactivate": "Stop Placing Signatures",
|
"deactivate": "Stop Placing Signatures",
|
||||||
"results": {
|
"results": {
|
||||||
@@ -2511,11 +2562,15 @@
|
|||||||
"overlay-pdfs": {
|
"overlay-pdfs": {
|
||||||
"tags": "Overlay",
|
"tags": "Overlay",
|
||||||
"header": "Overlay PDF Files",
|
"header": "Overlay PDF Files",
|
||||||
|
"title": "Overlay PDFs",
|
||||||
|
"desc": "Overlay one PDF on top of another",
|
||||||
"baseFile": {
|
"baseFile": {
|
||||||
"label": "Select Base PDF File"
|
"label": "Select Base PDF File"
|
||||||
},
|
},
|
||||||
"overlayFiles": {
|
"overlayFiles": {
|
||||||
"label": "Select Overlay PDF Files"
|
"label": "Select Overlay PDF Files",
|
||||||
|
"placeholder": "Choose PDF(s)...",
|
||||||
|
"addMore": "Add more PDFs..."
|
||||||
},
|
},
|
||||||
"mode": {
|
"mode": {
|
||||||
"label": "Select Overlay Mode",
|
"label": "Select Overlay Mode",
|
||||||
@@ -2525,14 +2580,49 @@
|
|||||||
},
|
},
|
||||||
"counts": {
|
"counts": {
|
||||||
"label": "Overlay Counts (for Fixed Repeat Mode)",
|
"label": "Overlay Counts (for Fixed Repeat Mode)",
|
||||||
"placeholder": "Enter comma-separated counts (e.g., 2,3,1)"
|
"placeholder": "Enter comma-separated counts (e.g., 2,3,1)",
|
||||||
|
"item": "Count for file"
|
||||||
},
|
},
|
||||||
"position": {
|
"position": {
|
||||||
"label": "Select Overlay Position",
|
"label": "Select Overlay Position",
|
||||||
"foreground": "Foreground",
|
"foreground": "Foreground",
|
||||||
"background": "Background"
|
"background": "Background"
|
||||||
},
|
},
|
||||||
"submit": "Submit"
|
"submit": "Submit",
|
||||||
|
"settings": {
|
||||||
|
"title": "Settings"
|
||||||
|
},
|
||||||
|
"results": {
|
||||||
|
"title": "Overlay Results"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"header": {
|
||||||
|
"title": "Overlay PDFs Overview"
|
||||||
|
},
|
||||||
|
"description": {
|
||||||
|
"title": "Description",
|
||||||
|
"text": "Combine a base PDF with one or more overlay PDFs. Overlays can be applied page-by-page in different modes and placed in the foreground or background."
|
||||||
|
},
|
||||||
|
"mode": {
|
||||||
|
"title": "Overlay Mode",
|
||||||
|
"text": "Choose how to distribute overlay pages across the base PDF pages.",
|
||||||
|
"sequential": "Sequential Overlay: Use pages from the first overlay PDF until it ends, then move to the next.",
|
||||||
|
"interleaved": "Interleaved Overlay: Take one page from each overlay in turn.",
|
||||||
|
"fixedRepeat": "Fixed Repeat Overlay: Take a set number of pages from each overlay before moving to the next. Use Counts to set the numbers."
|
||||||
|
},
|
||||||
|
"position": {
|
||||||
|
"title": "Overlay Position",
|
||||||
|
"text": "Foreground places the overlay on top of the page. Background places it behind."
|
||||||
|
},
|
||||||
|
"overlayFiles": {
|
||||||
|
"title": "Overlay Files",
|
||||||
|
"text": "Select one or more PDFs to overlay on the base. The order of these files affects how pages are applied in Sequential and Fixed Repeat modes."
|
||||||
|
},
|
||||||
|
"counts": {
|
||||||
|
"title": "Counts (Fixed Repeat only)",
|
||||||
|
"text": "Provide a positive number for each overlay file showing how many pages to take before moving to the next. Required when mode is Fixed Repeat."
|
||||||
|
}
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"split-by-sections": {
|
"split-by-sections": {
|
||||||
"tags": "Section Split, Divide, Customize,Customise",
|
"tags": "Section Split, Divide, Customize,Customise",
|
||||||
@@ -2774,8 +2864,9 @@
|
|||||||
"submit": "Sanitize PDF"
|
"submit": "Sanitize PDF"
|
||||||
},
|
},
|
||||||
"adjustContrast": {
|
"adjustContrast": {
|
||||||
"title": "Adjust Contrast",
|
"title": "Adjust Colors/Contrast",
|
||||||
"header": "Adjust Contrast",
|
"header": "Adjust Colors/Contrast",
|
||||||
|
"basic": "Basic Adjustments",
|
||||||
"contrast": "Contrast:",
|
"contrast": "Contrast:",
|
||||||
"brightness": "Brightness:",
|
"brightness": "Brightness:",
|
||||||
"saturation": "Saturation:",
|
"saturation": "Saturation:",
|
||||||
@@ -3062,7 +3153,12 @@
|
|||||||
"panMode": "Pan Mode",
|
"panMode": "Pan Mode",
|
||||||
"rotateLeft": "Rotate Left",
|
"rotateLeft": "Rotate Left",
|
||||||
"rotateRight": "Rotate Right",
|
"rotateRight": "Rotate Right",
|
||||||
"toggleSidebar": "Toggle Sidebar"
|
"toggleSidebar": "Toggle Sidebar",
|
||||||
|
"exportSelected": "Export Selected Pages",
|
||||||
|
"toggleAnnotations": "Toggle Annotations Visibility",
|
||||||
|
"annotationMode": "Toggle Annotation Mode",
|
||||||
|
"draw": "Draw",
|
||||||
|
"save": "Save"
|
||||||
},
|
},
|
||||||
"search": {
|
"search": {
|
||||||
"title": "Search PDF",
|
"title": "Search PDF",
|
||||||
@@ -3104,6 +3200,7 @@
|
|||||||
"automate": "Automate",
|
"automate": "Automate",
|
||||||
"files": "Files",
|
"files": "Files",
|
||||||
"activity": "Activity",
|
"activity": "Activity",
|
||||||
|
"account": "Account",
|
||||||
"config": "Config",
|
"config": "Config",
|
||||||
"allTools": "All Tools"
|
"allTools": "All Tools"
|
||||||
},
|
},
|
||||||
@@ -3131,6 +3228,9 @@
|
|||||||
"addFiles": "Add Files",
|
"addFiles": "Add Files",
|
||||||
"dragFilesInOrClick": "Drag files in or click \"Add Files\" to browse"
|
"dragFilesInOrClick": "Drag files in or click \"Add Files\" to browse"
|
||||||
},
|
},
|
||||||
|
"fileEditor": {
|
||||||
|
"addFiles": "Add Files"
|
||||||
|
},
|
||||||
"fileManager": {
|
"fileManager": {
|
||||||
"title": "Upload PDF Files",
|
"title": "Upload PDF Files",
|
||||||
"subtitle": "Add files to your storage for easy access across tools",
|
"subtitle": "Add files to your storage for easy access across tools",
|
||||||
@@ -3159,6 +3259,7 @@
|
|||||||
"lastModified": "Last Modified",
|
"lastModified": "Last Modified",
|
||||||
"toolChain": "Tools Applied",
|
"toolChain": "Tools Applied",
|
||||||
"restore": "Restore",
|
"restore": "Restore",
|
||||||
|
"unzip": "Unzip",
|
||||||
"searchFiles": "Search files...",
|
"searchFiles": "Search files...",
|
||||||
"recent": "Recent",
|
"recent": "Recent",
|
||||||
"localFiles": "Local Files",
|
"localFiles": "Local Files",
|
||||||
@@ -3166,7 +3267,6 @@
|
|||||||
"googleDriveShort": "Drive",
|
"googleDriveShort": "Drive",
|
||||||
"myFiles": "My Files",
|
"myFiles": "My Files",
|
||||||
"noRecentFiles": "No recent files found",
|
"noRecentFiles": "No recent files found",
|
||||||
"dropFilesHint": "Drop files here to upload",
|
|
||||||
"googleDriveNotAvailable": "Google Drive integration not available",
|
"googleDriveNotAvailable": "Google Drive integration not available",
|
||||||
"openFiles": "Open Files",
|
"openFiles": "Open Files",
|
||||||
"openFile": "Open File",
|
"openFile": "Open File",
|
||||||
|
|||||||
@@ -2,6 +2,23 @@
|
|||||||
"language": {
|
"language": {
|
||||||
"direction": "ltr"
|
"direction": "ltr"
|
||||||
},
|
},
|
||||||
|
"toolPanel": {
|
||||||
|
"modePrompt": {
|
||||||
|
"title": "Choose how you browse tools",
|
||||||
|
"description": "Preview both layouts and decide how you want to explore Stirling PDF tools.",
|
||||||
|
"sidebarTitle": "Sidebar mode",
|
||||||
|
"sidebarDescription": "Keep tools alongside your workspace for quick switching.",
|
||||||
|
"recommended": "Recommended",
|
||||||
|
"chooseSidebar": "Use sidebar mode",
|
||||||
|
"fullscreenTitle": "Fullscreen mode - (legacy)",
|
||||||
|
"fullscreenDescription": "Browse every tool in a catalogue that covers the workspace until you pick one.",
|
||||||
|
"chooseFullscreen": "Use fullscreen mode",
|
||||||
|
"dismiss": "Maybe later"
|
||||||
|
},
|
||||||
|
"fullscreen": {
|
||||||
|
"showDetails": "Show Details"
|
||||||
|
}
|
||||||
|
},
|
||||||
"addPageNumbers": {
|
"addPageNumbers": {
|
||||||
"fontSize": "Font Size",
|
"fontSize": "Font Size",
|
||||||
"fontName": "Font Name",
|
"fontName": "Font Name",
|
||||||
@@ -562,7 +579,7 @@
|
|||||||
"adjustContrast": {
|
"adjustContrast": {
|
||||||
"tags": "contrast,brightness,saturation",
|
"tags": "contrast,brightness,saturation",
|
||||||
"title": "Adjust Colors/Contrast",
|
"title": "Adjust Colors/Contrast",
|
||||||
"desc": "Adjust Contrast, Saturation and Brightness of a PDF"
|
"desc": "Adjust Colors/Contrast, Saturation and Brightness of a PDF"
|
||||||
},
|
},
|
||||||
"crop": {
|
"crop": {
|
||||||
"tags": "trim,cut,resize",
|
"tags": "trim,cut,resize",
|
||||||
@@ -1521,11 +1538,15 @@
|
|||||||
"overlay-pdfs": {
|
"overlay-pdfs": {
|
||||||
"tags": "Overlay",
|
"tags": "Overlay",
|
||||||
"header": "Overlay PDF Files",
|
"header": "Overlay PDF Files",
|
||||||
|
"title": "Overlay PDFs",
|
||||||
|
"desc": "Overlay one PDF on top of another",
|
||||||
"baseFile": {
|
"baseFile": {
|
||||||
"label": "Select Base PDF File"
|
"label": "Select Base PDF File"
|
||||||
},
|
},
|
||||||
"overlayFiles": {
|
"overlayFiles": {
|
||||||
"label": "Select Overlay PDF Files"
|
"label": "Select Overlay PDF Files",
|
||||||
|
"placeholder": "Choose PDF(s)...",
|
||||||
|
"addMore": "Add more PDFs..."
|
||||||
},
|
},
|
||||||
"mode": {
|
"mode": {
|
||||||
"label": "Select Overlay Mode",
|
"label": "Select Overlay Mode",
|
||||||
@@ -1535,14 +1556,49 @@
|
|||||||
},
|
},
|
||||||
"counts": {
|
"counts": {
|
||||||
"label": "Overlay Counts (for Fixed Repeat Mode)",
|
"label": "Overlay Counts (for Fixed Repeat Mode)",
|
||||||
"placeholder": "Enter comma-separated counts (e.g., 2,3,1)"
|
"placeholder": "Enter comma-separated counts (e.g., 2,3,1)",
|
||||||
|
"item": "Count for file"
|
||||||
},
|
},
|
||||||
"position": {
|
"position": {
|
||||||
"label": "Select Overlay Position",
|
"label": "Select Overlay Position",
|
||||||
"foreground": "Foreground",
|
"foreground": "Foreground",
|
||||||
"background": "Background"
|
"background": "Background"
|
||||||
},
|
},
|
||||||
"submit": "Submit"
|
"submit": "Submit",
|
||||||
|
"settings": {
|
||||||
|
"title": "Settings"
|
||||||
|
},
|
||||||
|
"results": {
|
||||||
|
"title": "Overlay Results"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"header": {
|
||||||
|
"title": "Overlay PDFs Overview"
|
||||||
|
},
|
||||||
|
"description": {
|
||||||
|
"title": "Description",
|
||||||
|
"text": "Combine a base PDF with one or more overlay PDFs. Overlays can be applied page-by-page in different modes and placed in the foreground or background."
|
||||||
|
},
|
||||||
|
"mode": {
|
||||||
|
"title": "Overlay Mode",
|
||||||
|
"text": "Choose how to distribute overlay pages across the base PDF pages.",
|
||||||
|
"sequential": "Sequential Overlay: Use pages from the first overlay PDF until it ends, then move to the next.",
|
||||||
|
"interleaved": "Interleaved Overlay: Take one page from each overlay in turn.",
|
||||||
|
"fixedRepeat": "Fixed Repeat Overlay: Take a set number of pages from each overlay before moving to the next. Use Counts to set the numbers."
|
||||||
|
},
|
||||||
|
"position": {
|
||||||
|
"title": "Overlay Position",
|
||||||
|
"text": "Foreground places the overlay on top of the page. Background places it behind."
|
||||||
|
},
|
||||||
|
"overlayFiles": {
|
||||||
|
"title": "Overlay Files",
|
||||||
|
"text": "Select one or more PDFs to overlay on the base. The order of these files affects how pages are applied in Sequential and Fixed Repeat modes."
|
||||||
|
},
|
||||||
|
"counts": {
|
||||||
|
"title": "Counts (Fixed Repeat only)",
|
||||||
|
"text": "Provide a positive number for each overlay file showing how many pages to take before moving to the next. Required when mode is Fixed Repeat."
|
||||||
|
}
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"split-by-sections": {
|
"split-by-sections": {
|
||||||
"tags": "Section Split, Divide, Customize",
|
"tags": "Section Split, Divide, Customize",
|
||||||
@@ -1712,8 +1768,9 @@
|
|||||||
"submit": "Sanitize PDF"
|
"submit": "Sanitize PDF"
|
||||||
},
|
},
|
||||||
"adjustContrast": {
|
"adjustContrast": {
|
||||||
"title": "Adjust Contrast",
|
"title": "Adjust Colors/Contrast",
|
||||||
"header": "Adjust Contrast",
|
"header": "Adjust Colors/Contrast",
|
||||||
|
"basic": "Basic Adjustments",
|
||||||
"contrast": "Contrast:",
|
"contrast": "Contrast:",
|
||||||
"brightness": "Brightness:",
|
"brightness": "Brightness:",
|
||||||
"saturation": "Saturation:",
|
"saturation": "Saturation:",
|
||||||
|
|||||||
@@ -38,7 +38,7 @@
|
|||||||
"save": "Guardar",
|
"save": "Guardar",
|
||||||
"saveToBrowser": "Guardar en el navegador",
|
"saveToBrowser": "Guardar en el navegador",
|
||||||
"close": "Cerrar",
|
"close": "Cerrar",
|
||||||
"filesSelected": "archivos seleccionados",
|
"filesSelected": "{{count}} archivos seleccionados",
|
||||||
"noFavourites": "No se agregaron favoritos",
|
"noFavourites": "No se agregaron favoritos",
|
||||||
"downloadComplete": "Descarga completada",
|
"downloadComplete": "Descarga completada",
|
||||||
"bored": "¿Aburrido de esperar?",
|
"bored": "¿Aburrido de esperar?",
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
+23
-17
@@ -4,7 +4,9 @@ import { FileContextProvider } from "./contexts/FileContext";
|
|||||||
import { NavigationProvider } from "./contexts/NavigationContext";
|
import { NavigationProvider } from "./contexts/NavigationContext";
|
||||||
import { FilesModalProvider } from "./contexts/FilesModalContext";
|
import { FilesModalProvider } from "./contexts/FilesModalContext";
|
||||||
import { ToolWorkflowProvider } from "./contexts/ToolWorkflowContext";
|
import { ToolWorkflowProvider } from "./contexts/ToolWorkflowContext";
|
||||||
|
import { HotkeyProvider } from "./contexts/HotkeyContext";
|
||||||
import { SidebarProvider } from "./contexts/SidebarContext";
|
import { SidebarProvider } from "./contexts/SidebarContext";
|
||||||
|
import { PreferencesProvider } from "./contexts/PreferencesContext";
|
||||||
import ErrorBoundary from "./components/shared/ErrorBoundary";
|
import ErrorBoundary from "./components/shared/ErrorBoundary";
|
||||||
import HomePage from "./pages/HomePage";
|
import HomePage from "./pages/HomePage";
|
||||||
|
|
||||||
@@ -40,23 +42,27 @@ export default function App() {
|
|||||||
<Suspense fallback={<LoadingFallback />}>
|
<Suspense fallback={<LoadingFallback />}>
|
||||||
<RainbowThemeProvider>
|
<RainbowThemeProvider>
|
||||||
<ErrorBoundary>
|
<ErrorBoundary>
|
||||||
<FileContextProvider enableUrlSync={true} enablePersistence={true}>
|
<PreferencesProvider>
|
||||||
<NavigationProvider>
|
<FileContextProvider enableUrlSync={true} enablePersistence={true}>
|
||||||
<FilesModalProvider>
|
<NavigationProvider>
|
||||||
<ToolWorkflowProvider>
|
<FilesModalProvider>
|
||||||
<SidebarProvider>
|
<ToolWorkflowProvider>
|
||||||
<ViewerProvider>
|
<HotkeyProvider>
|
||||||
<SignatureProvider>
|
<SidebarProvider>
|
||||||
<RightRailProvider>
|
<ViewerProvider>
|
||||||
<HomePage />
|
<SignatureProvider>
|
||||||
</RightRailProvider>
|
<RightRailProvider>
|
||||||
</SignatureProvider>
|
<HomePage />
|
||||||
</ViewerProvider>
|
</RightRailProvider>
|
||||||
</SidebarProvider>
|
</SignatureProvider>
|
||||||
</ToolWorkflowProvider>
|
</ViewerProvider>
|
||||||
</FilesModalProvider>
|
</SidebarProvider>
|
||||||
</NavigationProvider>
|
</HotkeyProvider>
|
||||||
</FileContextProvider>
|
</ToolWorkflowProvider>
|
||||||
|
</FilesModalProvider>
|
||||||
|
</NavigationProvider>
|
||||||
|
</FileContextProvider>
|
||||||
|
</PreferencesProvider>
|
||||||
</ErrorBoundary>
|
</ErrorBoundary>
|
||||||
</RainbowThemeProvider>
|
</RainbowThemeProvider>
|
||||||
</Suspense>
|
</Suspense>
|
||||||
|
|||||||
@@ -9,6 +9,9 @@ import MobileLayout from './fileManager/MobileLayout';
|
|||||||
import DesktopLayout from './fileManager/DesktopLayout';
|
import DesktopLayout from './fileManager/DesktopLayout';
|
||||||
import DragOverlay from './fileManager/DragOverlay';
|
import DragOverlay from './fileManager/DragOverlay';
|
||||||
import { FileManagerProvider } from '../contexts/FileManagerContext';
|
import { FileManagerProvider } from '../contexts/FileManagerContext';
|
||||||
|
import { Z_INDEX_FILE_MANAGER_MODAL } from '../styles/zIndex';
|
||||||
|
import { isGoogleDriveConfigured } from '../services/googleDrivePickerService';
|
||||||
|
import { loadScript } from '../utils/scriptLoader';
|
||||||
|
|
||||||
interface FileManagerProps {
|
interface FileManagerProps {
|
||||||
selectedTool?: Tool | null;
|
selectedTool?: Tool | null;
|
||||||
@@ -20,7 +23,7 @@ const FileManager: React.FC<FileManagerProps> = ({ selectedTool }) => {
|
|||||||
const [isDragging, setIsDragging] = useState(false);
|
const [isDragging, setIsDragging] = useState(false);
|
||||||
const [isMobile, setIsMobile] = useState(false);
|
const [isMobile, setIsMobile] = useState(false);
|
||||||
|
|
||||||
const { loadRecentFiles, handleRemoveFile } = useFileManager();
|
const { loadRecentFiles, handleRemoveFile, loading } = useFileManager();
|
||||||
|
|
||||||
// File management handlers
|
// File management handlers
|
||||||
const isFileSupported = useCallback((fileName: string) => {
|
const isFileSupported = useCallback((fileName: string) => {
|
||||||
@@ -84,6 +87,30 @@ const FileManager: React.FC<FileManagerProps> = ({ selectedTool }) => {
|
|||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
// Preload Google Drive scripts if configured
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (isGoogleDriveConfigured()) {
|
||||||
|
// Load scripts in parallel without blocking
|
||||||
|
Promise.all([
|
||||||
|
loadScript({
|
||||||
|
src: 'https://apis.google.com/js/api.js',
|
||||||
|
id: 'gapi-script',
|
||||||
|
async: true,
|
||||||
|
defer: true,
|
||||||
|
}),
|
||||||
|
loadScript({
|
||||||
|
src: 'https://accounts.google.com/gsi/client',
|
||||||
|
id: 'gis-script',
|
||||||
|
async: true,
|
||||||
|
defer: true,
|
||||||
|
}),
|
||||||
|
]).catch((error) => {
|
||||||
|
console.warn('Failed to preload Google Drive scripts:', error);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
// Modal size constants for consistent scaling
|
// Modal size constants for consistent scaling
|
||||||
const modalHeight = '80vh';
|
const modalHeight = '80vh';
|
||||||
const modalWidth = isMobile ? '100%' : '80vw';
|
const modalWidth = isMobile ? '100%' : '80vw';
|
||||||
@@ -100,6 +127,7 @@ const FileManager: React.FC<FileManagerProps> = ({ selectedTool }) => {
|
|||||||
radius="md"
|
radius="md"
|
||||||
className="overflow-hidden p-0"
|
className="overflow-hidden p-0"
|
||||||
withCloseButton={false}
|
withCloseButton={false}
|
||||||
|
zIndex={Z_INDEX_FILE_MANAGER_MODAL}
|
||||||
styles={{
|
styles={{
|
||||||
content: {
|
content: {
|
||||||
position: 'relative',
|
position: 'relative',
|
||||||
@@ -123,7 +151,6 @@ const FileManager: React.FC<FileManagerProps> = ({ selectedTool }) => {
|
|||||||
onDrop={handleNewFileUpload}
|
onDrop={handleNewFileUpload}
|
||||||
onDragEnter={() => setIsDragging(true)}
|
onDragEnter={() => setIsDragging(true)}
|
||||||
onDragLeave={() => setIsDragging(false)}
|
onDragLeave={() => setIsDragging(false)}
|
||||||
accept={{}}
|
|
||||||
multiple={true}
|
multiple={true}
|
||||||
activateOnClick={false}
|
activateOnClick={false}
|
||||||
style={{
|
style={{
|
||||||
@@ -147,6 +174,7 @@ const FileManager: React.FC<FileManagerProps> = ({ selectedTool }) => {
|
|||||||
onFileRemove={handleRemoveFileByIndex}
|
onFileRemove={handleRemoveFileByIndex}
|
||||||
modalHeight={modalHeight}
|
modalHeight={modalHeight}
|
||||||
refreshRecentFiles={refreshRecentFiles}
|
refreshRecentFiles={refreshRecentFiles}
|
||||||
|
isLoading={loading}
|
||||||
>
|
>
|
||||||
{isMobile ? <MobileLayout /> : <DesktopLayout />}
|
{isMobile ? <MobileLayout /> : <DesktopLayout />}
|
||||||
</FileManagerProvider>
|
</FileManagerProvider>
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import React, { useRef, useState, useCallback } from 'react';
|
import React, { useRef, useState } from 'react';
|
||||||
import { Paper, Group, Button, Modal, Stack, Text } from '@mantine/core';
|
import { Paper, Button, Modal, Stack, Text, Popover, ColorPicker as MantineColorPicker } from '@mantine/core';
|
||||||
import { ColorSwatchButton } from './ColorPicker';
|
import { ColorSwatchButton } from './ColorPicker';
|
||||||
import PenSizeSelector from '../../tools/sign/PenSizeSelector';
|
import PenSizeSelector from '../../tools/sign/PenSizeSelector';
|
||||||
|
import SignaturePad from 'signature_pad';
|
||||||
|
|
||||||
interface DrawingCanvasProps {
|
interface DrawingCanvasProps {
|
||||||
selectedColor: string;
|
selectedColor: string;
|
||||||
@@ -11,6 +12,7 @@ interface DrawingCanvasProps {
|
|||||||
onPenSizeChange: (size: number) => void;
|
onPenSizeChange: (size: number) => void;
|
||||||
onPenSizeInputChange: (input: string) => void;
|
onPenSizeInputChange: (input: string) => void;
|
||||||
onSignatureDataChange: (data: string | null) => void;
|
onSignatureDataChange: (data: string | null) => void;
|
||||||
|
onDrawingComplete?: () => void;
|
||||||
disabled?: boolean;
|
disabled?: boolean;
|
||||||
width?: number;
|
width?: number;
|
||||||
height?: number;
|
height?: number;
|
||||||
@@ -27,407 +29,249 @@ export const DrawingCanvas: React.FC<DrawingCanvasProps> = ({
|
|||||||
onPenSizeChange,
|
onPenSizeChange,
|
||||||
onPenSizeInputChange,
|
onPenSizeInputChange,
|
||||||
onSignatureDataChange,
|
onSignatureDataChange,
|
||||||
|
onDrawingComplete,
|
||||||
disabled = false,
|
disabled = false,
|
||||||
width = 400,
|
width = 400,
|
||||||
height = 150,
|
height = 150,
|
||||||
modalWidth = 800,
|
|
||||||
modalHeight = 400,
|
|
||||||
additionalButtons
|
|
||||||
}) => {
|
}) => {
|
||||||
const canvasRef = useRef<HTMLCanvasElement>(null);
|
const previewCanvasRef = useRef<HTMLCanvasElement>(null);
|
||||||
const modalCanvasRef = useRef<HTMLCanvasElement>(null);
|
const modalCanvasRef = useRef<HTMLCanvasElement>(null);
|
||||||
const visibleModalCanvasRef = useRef<HTMLCanvasElement>(null);
|
const padRef = useRef<SignaturePad | null>(null);
|
||||||
|
const [modalOpen, setModalOpen] = useState(false);
|
||||||
|
const [colorPickerOpen, setColorPickerOpen] = useState(false);
|
||||||
|
|
||||||
const [isDrawing, setIsDrawing] = useState(false);
|
const initPad = (canvas: HTMLCanvasElement) => {
|
||||||
const [isModalDrawing, setIsModalDrawing] = useState(false);
|
if (!padRef.current) {
|
||||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
const rect = canvas.getBoundingClientRect();
|
||||||
|
canvas.width = rect.width;
|
||||||
|
canvas.height = rect.height;
|
||||||
|
|
||||||
// Drawing functions for main canvas
|
padRef.current = new SignaturePad(canvas, {
|
||||||
const startDrawing = useCallback((e: React.MouseEvent<HTMLCanvasElement>) => {
|
penColor: selectedColor,
|
||||||
if (!canvasRef.current || disabled) return;
|
minWidth: penSize * 0.5,
|
||||||
|
maxWidth: penSize * 2.5,
|
||||||
setIsDrawing(true);
|
throttle: 10,
|
||||||
const rect = canvasRef.current.getBoundingClientRect();
|
minDistance: 5,
|
||||||
const scaleX = canvasRef.current.width / rect.width;
|
velocityFilterWeight: 0.7,
|
||||||
const scaleY = canvasRef.current.height / rect.height;
|
});
|
||||||
const x = (e.clientX - rect.left) * scaleX;
|
|
||||||
const y = (e.clientY - rect.top) * scaleY;
|
|
||||||
|
|
||||||
const ctx = canvasRef.current.getContext('2d');
|
|
||||||
if (ctx) {
|
|
||||||
ctx.strokeStyle = selectedColor;
|
|
||||||
ctx.lineWidth = penSize;
|
|
||||||
ctx.lineCap = 'round';
|
|
||||||
ctx.lineJoin = 'round';
|
|
||||||
ctx.beginPath();
|
|
||||||
ctx.moveTo(x, y);
|
|
||||||
}
|
}
|
||||||
}, [disabled, selectedColor, penSize]);
|
};
|
||||||
|
|
||||||
const draw = useCallback((e: React.MouseEvent<HTMLCanvasElement>) => {
|
const openModal = () => {
|
||||||
if (!isDrawing || !canvasRef.current || disabled) return;
|
// Clear pad ref so it reinitializes
|
||||||
|
if (padRef.current) {
|
||||||
const rect = canvasRef.current.getBoundingClientRect();
|
padRef.current.off();
|
||||||
const scaleX = canvasRef.current.width / rect.width;
|
padRef.current = null;
|
||||||
const scaleY = canvasRef.current.height / rect.height;
|
|
||||||
const x = (e.clientX - rect.left) * scaleX;
|
|
||||||
const y = (e.clientY - rect.top) * scaleY;
|
|
||||||
|
|
||||||
const ctx = canvasRef.current.getContext('2d');
|
|
||||||
if (ctx) {
|
|
||||||
ctx.lineTo(x, y);
|
|
||||||
ctx.stroke();
|
|
||||||
}
|
}
|
||||||
}, [isDrawing, disabled]);
|
setModalOpen(true);
|
||||||
|
};
|
||||||
|
|
||||||
const stopDrawing = useCallback(() => {
|
const trimCanvas = (canvas: HTMLCanvasElement): string => {
|
||||||
if (!isDrawing || disabled) return;
|
const ctx = canvas.getContext('2d');
|
||||||
|
if (!ctx) return canvas.toDataURL('image/png');
|
||||||
|
|
||||||
setIsDrawing(false);
|
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
|
||||||
|
const pixels = imageData.data;
|
||||||
|
|
||||||
// Save canvas as signature data
|
let minX = canvas.width, minY = canvas.height, maxX = 0, maxY = 0;
|
||||||
if (canvasRef.current) {
|
|
||||||
const dataURL = canvasRef.current.toDataURL('image/png');
|
|
||||||
onSignatureDataChange(dataURL);
|
|
||||||
}
|
|
||||||
}, [isDrawing, disabled, onSignatureDataChange]);
|
|
||||||
|
|
||||||
// Modal canvas drawing functions
|
// Find bounds of non-transparent pixels
|
||||||
const startModalDrawing = useCallback((e: React.MouseEvent<HTMLCanvasElement>) => {
|
for (let y = 0; y < canvas.height; y++) {
|
||||||
if (!visibleModalCanvasRef.current || !modalCanvasRef.current) return;
|
for (let x = 0; x < canvas.width; x++) {
|
||||||
|
const alpha = pixels[(y * canvas.width + x) * 4 + 3];
|
||||||
setIsModalDrawing(true);
|
if (alpha > 0) {
|
||||||
const rect = visibleModalCanvasRef.current.getBoundingClientRect();
|
if (x < minX) minX = x;
|
||||||
const scaleX = visibleModalCanvasRef.current.width / rect.width;
|
if (x > maxX) maxX = x;
|
||||||
const scaleY = visibleModalCanvasRef.current.height / rect.height;
|
if (y < minY) minY = y;
|
||||||
const x = (e.clientX - rect.left) * scaleX;
|
if (y > maxY) maxY = y;
|
||||||
const y = (e.clientY - rect.top) * scaleY;
|
|
||||||
|
|
||||||
// Draw on both the visible modal canvas and hidden canvas
|
|
||||||
const visibleCtx = visibleModalCanvasRef.current.getContext('2d');
|
|
||||||
const hiddenCtx = modalCanvasRef.current.getContext('2d');
|
|
||||||
|
|
||||||
[visibleCtx, hiddenCtx].forEach(ctx => {
|
|
||||||
if (ctx) {
|
|
||||||
ctx.strokeStyle = selectedColor;
|
|
||||||
ctx.lineWidth = penSize;
|
|
||||||
ctx.lineCap = 'round';
|
|
||||||
ctx.lineJoin = 'round';
|
|
||||||
ctx.beginPath();
|
|
||||||
ctx.moveTo(x, y);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}, [selectedColor, penSize]);
|
|
||||||
|
|
||||||
const drawModal = useCallback((e: React.MouseEvent<HTMLCanvasElement>) => {
|
|
||||||
if (!isModalDrawing || !visibleModalCanvasRef.current || !modalCanvasRef.current) return;
|
|
||||||
|
|
||||||
const rect = visibleModalCanvasRef.current.getBoundingClientRect();
|
|
||||||
const scaleX = visibleModalCanvasRef.current.width / rect.width;
|
|
||||||
const scaleY = visibleModalCanvasRef.current.height / rect.height;
|
|
||||||
const x = (e.clientX - rect.left) * scaleX;
|
|
||||||
const y = (e.clientY - rect.top) * scaleY;
|
|
||||||
|
|
||||||
// Draw on both canvases
|
|
||||||
const visibleCtx = visibleModalCanvasRef.current.getContext('2d');
|
|
||||||
const hiddenCtx = modalCanvasRef.current.getContext('2d');
|
|
||||||
|
|
||||||
[visibleCtx, hiddenCtx].forEach(ctx => {
|
|
||||||
if (ctx) {
|
|
||||||
ctx.lineTo(x, y);
|
|
||||||
ctx.stroke();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}, [isModalDrawing]);
|
|
||||||
|
|
||||||
const stopModalDrawing = useCallback(() => {
|
|
||||||
if (!isModalDrawing) return;
|
|
||||||
setIsModalDrawing(false);
|
|
||||||
|
|
||||||
// Sync the canvases and update signature data (only when drawing stops)
|
|
||||||
if (modalCanvasRef.current) {
|
|
||||||
const dataURL = modalCanvasRef.current.toDataURL('image/png');
|
|
||||||
onSignatureDataChange(dataURL);
|
|
||||||
|
|
||||||
// Also update the small canvas display
|
|
||||||
if (canvasRef.current) {
|
|
||||||
const smallCtx = canvasRef.current.getContext('2d');
|
|
||||||
if (smallCtx) {
|
|
||||||
const img = new Image();
|
|
||||||
img.onload = () => {
|
|
||||||
smallCtx.clearRect(0, 0, canvasRef.current!.width, canvasRef.current!.height);
|
|
||||||
smallCtx.drawImage(img, 0, 0, canvasRef.current!.width, canvasRef.current!.height);
|
|
||||||
};
|
|
||||||
img.src = dataURL;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, [isModalDrawing]);
|
|
||||||
|
|
||||||
// Clear canvas functions
|
const trimWidth = maxX - minX + 1;
|
||||||
const clearCanvas = useCallback(() => {
|
const trimHeight = maxY - minY + 1;
|
||||||
if (!canvasRef.current || disabled) return;
|
|
||||||
|
|
||||||
const ctx = canvasRef.current.getContext('2d');
|
// Create trimmed canvas
|
||||||
if (ctx) {
|
const trimmedCanvas = document.createElement('canvas');
|
||||||
ctx.clearRect(0, 0, canvasRef.current.width, canvasRef.current.height);
|
trimmedCanvas.width = trimWidth;
|
||||||
|
trimmedCanvas.height = trimHeight;
|
||||||
// Also clear the modal canvas if it exists
|
const trimmedCtx = trimmedCanvas.getContext('2d');
|
||||||
if (modalCanvasRef.current) {
|
if (trimmedCtx) {
|
||||||
const modalCtx = modalCanvasRef.current.getContext('2d');
|
trimmedCtx.drawImage(canvas, minX, minY, trimWidth, trimHeight, 0, 0, trimWidth, trimHeight);
|
||||||
if (modalCtx) {
|
|
||||||
modalCtx.clearRect(0, 0, modalCanvasRef.current.width, modalCanvasRef.current.height);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
onSignatureDataChange(null);
|
|
||||||
}
|
|
||||||
}, [disabled]);
|
|
||||||
|
|
||||||
const clearModalCanvas = useCallback(() => {
|
|
||||||
// Clear both modal canvases (visible and hidden)
|
|
||||||
if (modalCanvasRef.current) {
|
|
||||||
const hiddenCtx = modalCanvasRef.current.getContext('2d');
|
|
||||||
if (hiddenCtx) {
|
|
||||||
hiddenCtx.clearRect(0, 0, modalCanvasRef.current.width, modalCanvasRef.current.height);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (visibleModalCanvasRef.current) {
|
return trimmedCanvas.toDataURL('image/png');
|
||||||
const visibleCtx = visibleModalCanvasRef.current.getContext('2d');
|
};
|
||||||
if (visibleCtx) {
|
|
||||||
visibleCtx.clearRect(0, 0, visibleModalCanvasRef.current.width, visibleModalCanvasRef.current.height);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Also clear the main canvas and signature data
|
const closeModal = () => {
|
||||||
if (canvasRef.current) {
|
if (padRef.current && !padRef.current.isEmpty()) {
|
||||||
const mainCtx = canvasRef.current.getContext('2d');
|
const canvas = modalCanvasRef.current;
|
||||||
if (mainCtx) {
|
if (canvas) {
|
||||||
mainCtx.clearRect(0, 0, canvasRef.current.width, canvasRef.current.height);
|
const trimmedPng = trimCanvas(canvas);
|
||||||
}
|
onSignatureDataChange(trimmedPng);
|
||||||
}
|
|
||||||
|
|
||||||
onSignatureDataChange(null);
|
// Update preview canvas with proper aspect ratio
|
||||||
}, []);
|
|
||||||
|
|
||||||
const saveModalSignature = useCallback(() => {
|
|
||||||
if (!modalCanvasRef.current) return;
|
|
||||||
|
|
||||||
const dataURL = modalCanvasRef.current.toDataURL('image/png');
|
|
||||||
onSignatureDataChange(dataURL);
|
|
||||||
|
|
||||||
// Copy to small canvas for display
|
|
||||||
if (canvasRef.current) {
|
|
||||||
const ctx = canvasRef.current.getContext('2d');
|
|
||||||
if (ctx) {
|
|
||||||
const img = new Image();
|
const img = new Image();
|
||||||
img.onload = () => {
|
img.onload = () => {
|
||||||
ctx.clearRect(0, 0, canvasRef.current!.width, canvasRef.current!.height);
|
if (previewCanvasRef.current) {
|
||||||
ctx.drawImage(img, 0, 0, canvasRef.current!.width, canvasRef.current!.height);
|
const ctx = previewCanvasRef.current.getContext('2d');
|
||||||
|
if (ctx) {
|
||||||
|
ctx.clearRect(0, 0, previewCanvasRef.current.width, previewCanvasRef.current.height);
|
||||||
|
|
||||||
|
// Calculate scaling to fit within preview canvas while maintaining aspect ratio
|
||||||
|
const scale = Math.min(
|
||||||
|
previewCanvasRef.current.width / img.width,
|
||||||
|
previewCanvasRef.current.height / img.height
|
||||||
|
);
|
||||||
|
const scaledWidth = img.width * scale;
|
||||||
|
const scaledHeight = img.height * scale;
|
||||||
|
const x = (previewCanvasRef.current.width - scaledWidth) / 2;
|
||||||
|
const y = (previewCanvasRef.current.height - scaledHeight) / 2;
|
||||||
|
|
||||||
|
ctx.drawImage(img, x, y, scaledWidth, scaledHeight);
|
||||||
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
img.src = dataURL;
|
img.src = trimmedPng;
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
setIsModalOpen(false);
|
if (onDrawingComplete) {
|
||||||
}, []);
|
onDrawingComplete();
|
||||||
|
|
||||||
const openModal = useCallback(() => {
|
|
||||||
setIsModalOpen(true);
|
|
||||||
// Copy content to modal canvas after a brief delay
|
|
||||||
setTimeout(() => {
|
|
||||||
if (visibleModalCanvasRef.current && modalCanvasRef.current) {
|
|
||||||
const visibleCtx = visibleModalCanvasRef.current.getContext('2d');
|
|
||||||
if (visibleCtx) {
|
|
||||||
visibleCtx.strokeStyle = selectedColor;
|
|
||||||
visibleCtx.lineWidth = penSize;
|
|
||||||
visibleCtx.lineCap = 'round';
|
|
||||||
visibleCtx.lineJoin = 'round';
|
|
||||||
visibleCtx.clearRect(0, 0, visibleModalCanvasRef.current.width, visibleModalCanvasRef.current.height);
|
|
||||||
visibleCtx.drawImage(modalCanvasRef.current, 0, 0, visibleModalCanvasRef.current.width, visibleModalCanvasRef.current.height);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, 300);
|
}
|
||||||
}, [selectedColor, penSize]);
|
if (padRef.current) {
|
||||||
|
padRef.current.off();
|
||||||
|
padRef.current = null;
|
||||||
|
}
|
||||||
|
setModalOpen(false);
|
||||||
|
};
|
||||||
|
|
||||||
// Initialize canvas settings whenever color or pen size changes
|
const clear = () => {
|
||||||
React.useEffect(() => {
|
if (padRef.current) {
|
||||||
const updateCanvas = (canvas: HTMLCanvasElement | null) => {
|
padRef.current.clear();
|
||||||
if (!canvas) return;
|
}
|
||||||
const ctx = canvas.getContext('2d');
|
if (previewCanvasRef.current) {
|
||||||
|
const ctx = previewCanvasRef.current.getContext('2d');
|
||||||
if (ctx) {
|
if (ctx) {
|
||||||
ctx.strokeStyle = selectedColor;
|
ctx.clearRect(0, 0, previewCanvasRef.current.width, previewCanvasRef.current.height);
|
||||||
ctx.lineWidth = penSize;
|
|
||||||
ctx.lineCap = 'round';
|
|
||||||
ctx.lineJoin = 'round';
|
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
onSignatureDataChange(null);
|
||||||
|
};
|
||||||
|
|
||||||
updateCanvas(canvasRef.current);
|
const updatePenColor = (color: string) => {
|
||||||
updateCanvas(modalCanvasRef.current);
|
if (padRef.current) {
|
||||||
updateCanvas(visibleModalCanvasRef.current);
|
padRef.current.penColor = color;
|
||||||
}, [selectedColor, penSize]);
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const updatePenSize = (size: number) => {
|
||||||
|
if (padRef.current) {
|
||||||
|
padRef.current.minWidth = size * 0.8;
|
||||||
|
padRef.current.maxWidth = size * 1.2;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Paper withBorder p="md">
|
<Paper withBorder p="md">
|
||||||
<Stack gap="sm">
|
<Stack gap="sm">
|
||||||
<Group justify="space-between">
|
<Text fw={500}>Draw your signature</Text>
|
||||||
<Text fw={500}>Draw your signature</Text>
|
|
||||||
<Group gap="lg">
|
|
||||||
<div>
|
|
||||||
<Text size="sm" fw={500} mb="xs" ta="center">Color</Text>
|
|
||||||
<Group justify="center">
|
|
||||||
<ColorSwatchButton
|
|
||||||
color={selectedColor}
|
|
||||||
onClick={onColorSwatchClick}
|
|
||||||
/>
|
|
||||||
</Group>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Text size="sm" fw={500} mb="xs">Pen Size</Text>
|
|
||||||
<PenSizeSelector
|
|
||||||
value={penSize}
|
|
||||||
inputValue={penSizeInput}
|
|
||||||
onValueChange={onPenSizeChange}
|
|
||||||
onInputChange={onPenSizeInputChange}
|
|
||||||
disabled={disabled}
|
|
||||||
placeholder="Size"
|
|
||||||
size="compact-sm"
|
|
||||||
style={{ width: '60px' }}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div style={{ paddingTop: '24px' }}>
|
|
||||||
<Button
|
|
||||||
variant="light"
|
|
||||||
size="compact-sm"
|
|
||||||
onClick={openModal}
|
|
||||||
disabled={disabled}
|
|
||||||
>
|
|
||||||
Expand
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</Group>
|
|
||||||
</Group>
|
|
||||||
<canvas
|
<canvas
|
||||||
ref={canvasRef}
|
ref={previewCanvasRef}
|
||||||
width={width}
|
width={width}
|
||||||
height={height}
|
height={height}
|
||||||
style={{
|
style={{
|
||||||
border: '1px solid #ccc',
|
border: '1px solid #ccc',
|
||||||
borderRadius: '4px',
|
borderRadius: '4px',
|
||||||
cursor: disabled ? 'default' : 'crosshair',
|
cursor: disabled ? 'default' : 'pointer',
|
||||||
backgroundColor: '#ffffff',
|
backgroundColor: '#ffffff',
|
||||||
width: '100%',
|
width: '100%',
|
||||||
}}
|
}}
|
||||||
onMouseDown={startDrawing}
|
onClick={disabled ? undefined : openModal}
|
||||||
onMouseMove={draw}
|
|
||||||
onMouseUp={stopDrawing}
|
|
||||||
onMouseLeave={stopDrawing}
|
|
||||||
/>
|
/>
|
||||||
<Group justify="space-between">
|
<Text size="sm" c="dimmed" ta="center">
|
||||||
<div>
|
Click to open drawing canvas
|
||||||
{additionalButtons}
|
</Text>
|
||||||
</div>
|
|
||||||
<Button
|
|
||||||
variant="subtle"
|
|
||||||
color="red"
|
|
||||||
size="compact-sm"
|
|
||||||
onClick={clearCanvas}
|
|
||||||
disabled={disabled}
|
|
||||||
>
|
|
||||||
Clear
|
|
||||||
</Button>
|
|
||||||
</Group>
|
|
||||||
</Stack>
|
</Stack>
|
||||||
</Paper>
|
</Paper>
|
||||||
|
|
||||||
{/* Hidden canvas for modal synchronization */}
|
<Modal opened={modalOpen} onClose={closeModal} title="Draw Your Signature" size="auto" centered>
|
||||||
<canvas
|
|
||||||
ref={modalCanvasRef}
|
|
||||||
width={modalWidth}
|
|
||||||
height={modalHeight}
|
|
||||||
style={{ display: 'none' }}
|
|
||||||
/>
|
|
||||||
|
|
||||||
{/* Modal for larger signature canvas */}
|
|
||||||
<Modal
|
|
||||||
opened={isModalOpen}
|
|
||||||
onClose={() => setIsModalOpen(false)}
|
|
||||||
title="Draw Your Signature"
|
|
||||||
size="xl"
|
|
||||||
centered
|
|
||||||
>
|
|
||||||
<Stack gap="md">
|
<Stack gap="md">
|
||||||
{/* Color and Pen Size picker */}
|
<div style={{ display: 'flex', gap: '20px', alignItems: 'flex-end' }}>
|
||||||
<Paper withBorder p="sm">
|
<div>
|
||||||
<Group gap="lg" align="flex-end">
|
<Text size="sm" fw={500} mb="xs">Color</Text>
|
||||||
<div>
|
<Popover
|
||||||
<Text size="sm" fw={500} mb="xs">Color</Text>
|
opened={colorPickerOpen}
|
||||||
<ColorSwatchButton
|
onChange={setColorPickerOpen}
|
||||||
color={selectedColor}
|
position="bottom-start"
|
||||||
onClick={onColorSwatchClick}
|
withArrow
|
||||||
/>
|
withinPortal={false}
|
||||||
</div>
|
>
|
||||||
<div>
|
<Popover.Target>
|
||||||
<Text size="sm" fw={500} mb="xs">Pen Size</Text>
|
<div>
|
||||||
<PenSizeSelector
|
<ColorSwatchButton
|
||||||
value={penSize}
|
color={selectedColor}
|
||||||
inputValue={penSizeInput}
|
onClick={() => setColorPickerOpen(!colorPickerOpen)}
|
||||||
onValueChange={onPenSizeChange}
|
/>
|
||||||
onInputChange={onPenSizeInputChange}
|
</div>
|
||||||
placeholder="Size"
|
</Popover.Target>
|
||||||
size="compact-sm"
|
<Popover.Dropdown>
|
||||||
style={{ width: '60px' }}
|
<MantineColorPicker
|
||||||
/>
|
format="hex"
|
||||||
</div>
|
value={selectedColor}
|
||||||
</Group>
|
onChange={(color) => {
|
||||||
</Paper>
|
onColorSwatchClick();
|
||||||
|
updatePenColor(color);
|
||||||
|
}}
|
||||||
|
swatches={['#000000', '#0066cc', '#cc0000', '#cc6600', '#009900', '#6600cc']}
|
||||||
|
/>
|
||||||
|
</Popover.Dropdown>
|
||||||
|
</Popover>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<Text size="sm" fw={500} mb="xs">Pen Size</Text>
|
||||||
|
<PenSizeSelector
|
||||||
|
value={penSize}
|
||||||
|
inputValue={penSizeInput}
|
||||||
|
onValueChange={(size) => {
|
||||||
|
onPenSizeChange(size);
|
||||||
|
updatePenSize(size);
|
||||||
|
}}
|
||||||
|
onInputChange={onPenSizeInputChange}
|
||||||
|
placeholder="Size"
|
||||||
|
size="compact-sm"
|
||||||
|
style={{ width: '60px' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<Paper withBorder p="md">
|
<canvas
|
||||||
<canvas
|
ref={(el) => {
|
||||||
ref={visibleModalCanvasRef}
|
modalCanvasRef.current = el;
|
||||||
width={modalWidth}
|
if (el) initPad(el);
|
||||||
height={modalHeight}
|
}}
|
||||||
style={{
|
style={{
|
||||||
border: '1px solid #ccc',
|
border: '1px solid #ccc',
|
||||||
borderRadius: '4px',
|
borderRadius: '4px',
|
||||||
cursor: 'crosshair',
|
display: 'block',
|
||||||
backgroundColor: '#ffffff',
|
touchAction: 'none',
|
||||||
width: '100%',
|
backgroundColor: 'white',
|
||||||
maxWidth: `${modalWidth}px`,
|
width: '100%',
|
||||||
height: 'auto',
|
maxWidth: '800px',
|
||||||
}}
|
height: '400px',
|
||||||
onMouseDown={startModalDrawing}
|
cursor: 'crosshair',
|
||||||
onMouseMove={drawModal}
|
}}
|
||||||
onMouseUp={stopModalDrawing}
|
/>
|
||||||
onMouseLeave={stopModalDrawing}
|
|
||||||
/>
|
|
||||||
</Paper>
|
|
||||||
|
|
||||||
<Group justify="space-between">
|
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
|
||||||
<Button
|
<Button variant="subtle" color="red" onClick={clear}>
|
||||||
variant="subtle"
|
|
||||||
color="red"
|
|
||||||
onClick={clearModalCanvas}
|
|
||||||
>
|
|
||||||
Clear Canvas
|
Clear Canvas
|
||||||
</Button>
|
</Button>
|
||||||
<Group gap="sm">
|
<Button onClick={closeModal}>
|
||||||
<Button
|
Done
|
||||||
variant="subtle"
|
</Button>
|
||||||
onClick={() => setIsModalOpen(false)}
|
</div>
|
||||||
>
|
|
||||||
Cancel
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
onClick={saveModalSignature}
|
|
||||||
>
|
|
||||||
Save Signature
|
|
||||||
</Button>
|
|
||||||
</Group>
|
|
||||||
</Group>
|
|
||||||
</Stack>
|
</Stack>
|
||||||
</Modal>
|
</Modal>
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ export const ImageUploader: React.FC<ImageUploaderProps> = ({
|
|||||||
disabled={disabled}
|
disabled={disabled}
|
||||||
/>
|
/>
|
||||||
<Text size="sm" c="dimmed">
|
<Text size="sm" c="dimmed">
|
||||||
{hint || t('sign.image.hint', 'Upload a PNG or JPG image of your signature')}
|
{hint || t('sign.image.hint', 'Upload an image of your signature')}
|
||||||
</Text>
|
</Text>
|
||||||
</Stack>
|
</Stack>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect } from 'react';
|
||||||
import { Stack, TextInput, Select, Combobox, useCombobox } from '@mantine/core';
|
import { Stack, TextInput, Select, Combobox, useCombobox, Group, Box } from '@mantine/core';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { ColorPicker } from './ColorPicker';
|
||||||
|
|
||||||
interface TextInputWithFontProps {
|
interface TextInputWithFontProps {
|
||||||
text: string;
|
text: string;
|
||||||
@@ -9,6 +10,8 @@ interface TextInputWithFontProps {
|
|||||||
onFontSizeChange: (size: number) => void;
|
onFontSizeChange: (size: number) => void;
|
||||||
fontFamily: string;
|
fontFamily: string;
|
||||||
onFontFamilyChange: (family: string) => void;
|
onFontFamilyChange: (family: string) => void;
|
||||||
|
textColor?: string;
|
||||||
|
onTextColorChange?: (color: string) => void;
|
||||||
disabled?: boolean;
|
disabled?: boolean;
|
||||||
label?: string;
|
label?: string;
|
||||||
placeholder?: string;
|
placeholder?: string;
|
||||||
@@ -21,6 +24,8 @@ export const TextInputWithFont: React.FC<TextInputWithFontProps> = ({
|
|||||||
onFontSizeChange,
|
onFontSizeChange,
|
||||||
fontFamily,
|
fontFamily,
|
||||||
onFontFamilyChange,
|
onFontFamilyChange,
|
||||||
|
textColor = '#000000',
|
||||||
|
onTextColorChange,
|
||||||
disabled = false,
|
disabled = false,
|
||||||
label,
|
label,
|
||||||
placeholder
|
placeholder
|
||||||
@@ -28,6 +33,7 @@ export const TextInputWithFont: React.FC<TextInputWithFontProps> = ({
|
|||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const [fontSizeInput, setFontSizeInput] = useState(fontSize.toString());
|
const [fontSizeInput, setFontSizeInput] = useState(fontSize.toString());
|
||||||
const fontSizeCombobox = useCombobox();
|
const fontSizeCombobox = useCombobox();
|
||||||
|
const [isColorPickerOpen, setIsColorPickerOpen] = useState(false);
|
||||||
|
|
||||||
// Sync font size input with prop changes
|
// Sync font size input with prop changes
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -42,7 +48,7 @@ export const TextInputWithFont: React.FC<TextInputWithFontProps> = ({
|
|||||||
{ value: 'Georgia', label: 'Georgia' },
|
{ value: 'Georgia', label: 'Georgia' },
|
||||||
];
|
];
|
||||||
|
|
||||||
const fontSizeOptions = ['8', '12', '16', '20', '24', '28', '32', '36', '40', '48'];
|
const fontSizeOptions = ['8', '12', '16', '20', '24', '28', '32', '36', '40', '48', '56', '64', '72', '80', '96', '112', '128', '144', '160', '176', '192', '200'];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack gap="sm">
|
<Stack gap="sm">
|
||||||
@@ -66,61 +72,101 @@ export const TextInputWithFont: React.FC<TextInputWithFontProps> = ({
|
|||||||
allowDeselect={false}
|
allowDeselect={false}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* Font Size */}
|
{/* Font Size and Color */}
|
||||||
<Combobox
|
<Group grow>
|
||||||
onOptionSubmit={(optionValue) => {
|
<Combobox
|
||||||
setFontSizeInput(optionValue);
|
onOptionSubmit={(optionValue) => {
|
||||||
const size = parseInt(optionValue);
|
setFontSizeInput(optionValue);
|
||||||
if (!isNaN(size)) {
|
const size = parseInt(optionValue);
|
||||||
onFontSizeChange(size);
|
if (!isNaN(size)) {
|
||||||
}
|
onFontSizeChange(size);
|
||||||
fontSizeCombobox.closeDropdown();
|
}
|
||||||
}}
|
fontSizeCombobox.closeDropdown();
|
||||||
store={fontSizeCombobox}
|
}}
|
||||||
withinPortal={false}
|
store={fontSizeCombobox}
|
||||||
>
|
withinPortal={false}
|
||||||
<Combobox.Target>
|
>
|
||||||
<TextInput
|
<Combobox.Target>
|
||||||
label="Font Size"
|
<TextInput
|
||||||
placeholder="Type or select font size (8-72)"
|
label="Font Size"
|
||||||
value={fontSizeInput}
|
placeholder="Type or select font size (8-200)"
|
||||||
onChange={(event) => {
|
value={fontSizeInput}
|
||||||
const value = event.currentTarget.value;
|
onChange={(event) => {
|
||||||
setFontSizeInput(value);
|
const value = event.currentTarget.value;
|
||||||
|
setFontSizeInput(value);
|
||||||
|
|
||||||
// Parse and validate the typed value in real-time
|
// Parse and validate the typed value in real-time
|
||||||
const size = parseInt(value);
|
const size = parseInt(value);
|
||||||
if (!isNaN(size) && size >= 8 && size <= 72) {
|
if (!isNaN(size) && size >= 8 && size <= 200) {
|
||||||
onFontSizeChange(size);
|
onFontSizeChange(size);
|
||||||
|
}
|
||||||
|
|
||||||
|
fontSizeCombobox.openDropdown();
|
||||||
|
fontSizeCombobox.updateSelectedOptionIndex();
|
||||||
|
}}
|
||||||
|
onClick={() => fontSizeCombobox.openDropdown()}
|
||||||
|
onFocus={() => fontSizeCombobox.openDropdown()}
|
||||||
|
onBlur={() => {
|
||||||
|
fontSizeCombobox.closeDropdown();
|
||||||
|
// Clean up invalid values on blur
|
||||||
|
const size = parseInt(fontSizeInput);
|
||||||
|
if (isNaN(size) || size < 8 || size > 200) {
|
||||||
|
setFontSizeInput(fontSize.toString());
|
||||||
|
} else {
|
||||||
|
onFontSizeChange(size);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
disabled={disabled}
|
||||||
|
/>
|
||||||
|
</Combobox.Target>
|
||||||
|
|
||||||
|
<Combobox.Dropdown>
|
||||||
|
<Combobox.Options>
|
||||||
|
{fontSizeOptions.map((size) => (
|
||||||
|
<Combobox.Option value={size} key={size}>
|
||||||
|
{size}px
|
||||||
|
</Combobox.Option>
|
||||||
|
))}
|
||||||
|
</Combobox.Options>
|
||||||
|
</Combobox.Dropdown>
|
||||||
|
</Combobox>
|
||||||
|
|
||||||
|
{/* Text Color Picker */}
|
||||||
|
{onTextColorChange && (
|
||||||
|
<Box>
|
||||||
|
<TextInput
|
||||||
|
label="Text Color"
|
||||||
|
value={textColor}
|
||||||
|
readOnly
|
||||||
|
disabled={disabled}
|
||||||
|
onClick={() => !disabled && setIsColorPickerOpen(true)}
|
||||||
|
style={{ cursor: disabled ? 'default' : 'pointer' }}
|
||||||
|
rightSection={
|
||||||
|
<Box
|
||||||
|
style={{
|
||||||
|
width: 24,
|
||||||
|
height: 24,
|
||||||
|
backgroundColor: textColor,
|
||||||
|
border: '1px solid #ccc',
|
||||||
|
borderRadius: 4,
|
||||||
|
cursor: disabled ? 'default' : 'pointer'
|
||||||
|
}}
|
||||||
|
/>
|
||||||
}
|
}
|
||||||
|
/>
|
||||||
|
</Box>
|
||||||
|
)}
|
||||||
|
</Group>
|
||||||
|
|
||||||
fontSizeCombobox.openDropdown();
|
{/* Color Picker Modal */}
|
||||||
fontSizeCombobox.updateSelectedOptionIndex();
|
{onTextColorChange && (
|
||||||
}}
|
<ColorPicker
|
||||||
onClick={() => fontSizeCombobox.openDropdown()}
|
isOpen={isColorPickerOpen}
|
||||||
onFocus={() => fontSizeCombobox.openDropdown()}
|
onClose={() => setIsColorPickerOpen(false)}
|
||||||
onBlur={() => {
|
selectedColor={textColor}
|
||||||
fontSizeCombobox.closeDropdown();
|
onColorChange={onTextColorChange}
|
||||||
// Clean up invalid values on blur
|
/>
|
||||||
const size = parseInt(fontSizeInput);
|
)}
|
||||||
if (isNaN(size) || size < 8 || size > 72) {
|
|
||||||
setFontSizeInput(fontSize.toString());
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
disabled={disabled}
|
|
||||||
/>
|
|
||||||
</Combobox.Target>
|
|
||||||
|
|
||||||
<Combobox.Dropdown>
|
|
||||||
<Combobox.Options>
|
|
||||||
{fontSizeOptions.map((size) => (
|
|
||||||
<Combobox.Option value={size} key={size}>
|
|
||||||
{size}px
|
|
||||||
</Combobox.Option>
|
|
||||||
))}
|
|
||||||
</Combobox.Options>
|
|
||||||
</Combobox.Dropdown>
|
|
||||||
</Combobox>
|
|
||||||
</Stack>
|
</Stack>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
@@ -0,0 +1,177 @@
|
|||||||
|
import React, { useRef, useState } from 'react';
|
||||||
|
import { Button, Group, useMantineColorScheme } from '@mantine/core';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import AddIcon from '@mui/icons-material/Add';
|
||||||
|
import { useFilesModalContext } from '../../contexts/FilesModalContext';
|
||||||
|
import LocalIcon from '../shared/LocalIcon';
|
||||||
|
import { BASE_PATH } from '../../constants/app';
|
||||||
|
import styles from './FileEditor.module.css';
|
||||||
|
|
||||||
|
interface AddFileCardProps {
|
||||||
|
onFileSelect: (files: File[]) => void;
|
||||||
|
accept?: string;
|
||||||
|
multiple?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const AddFileCard = ({
|
||||||
|
onFileSelect,
|
||||||
|
accept,
|
||||||
|
multiple = true
|
||||||
|
}: AddFileCardProps) => {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
const { openFilesModal } = useFilesModalContext();
|
||||||
|
const { colorScheme } = useMantineColorScheme();
|
||||||
|
const [isUploadHover, setIsUploadHover] = useState(false);
|
||||||
|
|
||||||
|
const handleCardClick = () => {
|
||||||
|
openFilesModal();
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleNativeUploadClick = (e: React.MouseEvent) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
fileInputRef.current?.click();
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleOpenFilesModal = (e: React.MouseEvent) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
openFilesModal();
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const files = Array.from(event.target.files || []);
|
||||||
|
if (files.length > 0) {
|
||||||
|
onFileSelect(files);
|
||||||
|
}
|
||||||
|
// Reset input so same files can be selected again
|
||||||
|
event.target.value = '';
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<input
|
||||||
|
ref={fileInputRef}
|
||||||
|
type="file"
|
||||||
|
accept={accept}
|
||||||
|
multiple={multiple}
|
||||||
|
onChange={handleFileChange}
|
||||||
|
style={{ display: 'none' }}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div
|
||||||
|
className={`${styles.addFileCard} w-[18rem] h-[22rem] select-none flex flex-col shadow-sm transition-all relative cursor-pointer`}
|
||||||
|
tabIndex={0}
|
||||||
|
role="button"
|
||||||
|
aria-label={t('fileEditor.addFiles', 'Add files')}
|
||||||
|
onClick={handleCardClick}
|
||||||
|
onKeyDown={(e) => {
|
||||||
|
if (e.key === 'Enter' || e.key === ' ') {
|
||||||
|
e.preventDefault();
|
||||||
|
handleCardClick();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{/* Header bar - matches FileEditorThumbnail structure */}
|
||||||
|
<div className={`${styles.header} ${styles.addFileHeader}`}>
|
||||||
|
<div className={styles.logoMark}>
|
||||||
|
<AddIcon sx={{ color: 'inherit', fontSize: '1.5rem' }} />
|
||||||
|
</div>
|
||||||
|
<div className={styles.headerIndex}>
|
||||||
|
{t('fileEditor.addFiles', 'Add Files')}
|
||||||
|
</div>
|
||||||
|
<div className={styles.kebab} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Main content area */}
|
||||||
|
<div className={styles.addFileContent}>
|
||||||
|
{/* Stirling PDF Branding */}
|
||||||
|
<Group gap="xs" align="center">
|
||||||
|
<img
|
||||||
|
src={colorScheme === 'dark' ? `${BASE_PATH}/branding/StirlingPDFLogoWhiteText.svg` : `${BASE_PATH}/branding/StirlingPDFLogoGreyText.svg`}
|
||||||
|
alt="Stirling PDF"
|
||||||
|
style={{ height: '2.2rem', width: 'auto' }}
|
||||||
|
/>
|
||||||
|
</Group>
|
||||||
|
|
||||||
|
{/* Add Files + Native Upload Buttons - styled like LandingPage */}
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
gap: '0.6rem',
|
||||||
|
width: '100%',
|
||||||
|
marginTop: '0.8rem',
|
||||||
|
marginBottom: '0.8rem'
|
||||||
|
}}
|
||||||
|
onMouseLeave={() => setIsUploadHover(false)}
|
||||||
|
>
|
||||||
|
<Button
|
||||||
|
style={{
|
||||||
|
backgroundColor: 'var(--landing-button-bg)',
|
||||||
|
color: 'var(--landing-button-color)',
|
||||||
|
border: '1px solid var(--landing-button-border)',
|
||||||
|
borderRadius: '2rem',
|
||||||
|
height: '38px',
|
||||||
|
paddingLeft: isUploadHover ? 0 : '1rem',
|
||||||
|
paddingRight: isUploadHover ? 0 : '1rem',
|
||||||
|
width: isUploadHover ? '58px' : 'calc(100% - 58px - 0.6rem)',
|
||||||
|
minWidth: isUploadHover ? '58px' : undefined,
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
transition: 'width .5s ease, padding .5s ease'
|
||||||
|
}}
|
||||||
|
onClick={handleOpenFilesModal}
|
||||||
|
onMouseEnter={() => setIsUploadHover(false)}
|
||||||
|
>
|
||||||
|
<LocalIcon icon="add" width="1.5rem" height="1.5rem" className="text-[var(--accent-interactive)]" />
|
||||||
|
{!isUploadHover && (
|
||||||
|
<span>
|
||||||
|
{t('landing.addFiles', 'Add Files')}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
aria-label="Upload"
|
||||||
|
style={{
|
||||||
|
backgroundColor: 'var(--landing-button-bg)',
|
||||||
|
color: 'var(--landing-button-color)',
|
||||||
|
border: '1px solid var(--landing-button-border)',
|
||||||
|
borderRadius: '1rem',
|
||||||
|
height: '38px',
|
||||||
|
width: isUploadHover ? 'calc(100% - 58px - 0.6rem)' : '58px',
|
||||||
|
minWidth: '58px',
|
||||||
|
paddingLeft: isUploadHover ? '1rem' : 0,
|
||||||
|
paddingRight: isUploadHover ? '1rem' : 0,
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
transition: 'width .5s ease, padding .5s ease'
|
||||||
|
}}
|
||||||
|
onClick={handleNativeUploadClick}
|
||||||
|
onMouseEnter={() => setIsUploadHover(true)}
|
||||||
|
>
|
||||||
|
<LocalIcon icon="upload" width="1.25rem" height="1.25rem" style={{ color: 'var(--accent-interactive)' }} />
|
||||||
|
{isUploadHover && (
|
||||||
|
<span style={{ marginLeft: '.5rem' }}>
|
||||||
|
{t('landing.uploadFromComputer', 'Upload from computer')}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Instruction Text */}
|
||||||
|
<span
|
||||||
|
className="text-[var(--accent-interactive)]"
|
||||||
|
style={{ fontSize: '.8rem', textAlign: 'center', marginTop: '0.5rem' }}
|
||||||
|
>
|
||||||
|
{t('fileUpload.dropFilesHere', 'Drop files here or click the upload button')}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default AddFileCard;
|
||||||
@@ -34,9 +34,9 @@
|
|||||||
.header {
|
.header {
|
||||||
height: 2.25rem;
|
height: 2.25rem;
|
||||||
border-radius: 0.0625rem 0.0625rem 0 0;
|
border-radius: 0.0625rem 0.0625rem 0 0;
|
||||||
display: grid;
|
display: flex;
|
||||||
grid-template-columns: 44px 1fr 44px;
|
|
||||||
align-items: center;
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
padding: 0 6px;
|
padding: 0 6px;
|
||||||
user-select: none;
|
user-select: none;
|
||||||
background: var(--bg-toolbar);
|
background: var(--bg-toolbar);
|
||||||
@@ -86,14 +86,23 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.headerIndex {
|
.headerIndex {
|
||||||
|
position: absolute;
|
||||||
|
left: 50%;
|
||||||
|
transform: translateX(-50%);
|
||||||
text-align: center;
|
text-align: center;
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
font-size: 18px;
|
font-size: 18px;
|
||||||
letter-spacing: 0.04em;
|
letter-spacing: 0.04em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.kebab {
|
.headerActions {
|
||||||
justify-self: end;
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
margin-left: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.headerIconButton {
|
||||||
color: #FFFFFF !important;
|
color: #FFFFFF !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -216,6 +225,11 @@
|
|||||||
color: rgba(0, 0, 0, 0.35);
|
color: rgba(0, 0, 0, 0.35);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.pinned {
|
||||||
|
color: #FFC107 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/* Unsupported file indicator */
|
/* Unsupported file indicator */
|
||||||
.unsupportedPill {
|
.unsupportedPill {
|
||||||
margin-left: 1.75rem;
|
margin-left: 1.75rem;
|
||||||
@@ -305,3 +319,181 @@
|
|||||||
:global([data-mantine-color-scheme="light"]) .card[data-selected="true"] {
|
:global([data-mantine-color-scheme="light"]) .card[data-selected="true"] {
|
||||||
outline-color: #3B4B6E;
|
outline-color: #3B4B6E;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* =========================
|
||||||
|
Add File Card Styles
|
||||||
|
========================= */
|
||||||
|
|
||||||
|
.addFileCard {
|
||||||
|
background: var(--file-card-bg);
|
||||||
|
border: 2px dashed var(--border-default);
|
||||||
|
border-radius: 0.0625rem;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.18s ease;
|
||||||
|
max-width: 100%;
|
||||||
|
max-height: 100%;
|
||||||
|
overflow: hidden;
|
||||||
|
margin-left: 0.5rem;
|
||||||
|
margin-right: 0.5rem;
|
||||||
|
opacity: 0.7;
|
||||||
|
}
|
||||||
|
|
||||||
|
.addFileCard:hover {
|
||||||
|
opacity: 1;
|
||||||
|
border-color: var(--color-blue-500);
|
||||||
|
box-shadow: var(--shadow-md);
|
||||||
|
transform: translateY(-2px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.addFileCard:focus {
|
||||||
|
outline: 2px solid var(--color-blue-500);
|
||||||
|
outline-offset: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.addFileHeader {
|
||||||
|
background: var(--bg-subtle);
|
||||||
|
color: var(--text-secondary);
|
||||||
|
border-bottom: 1px solid var(--border-default);
|
||||||
|
}
|
||||||
|
|
||||||
|
.addFileCard:hover .addFileHeader {
|
||||||
|
background: var(--color-blue-500);
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.addFileContent {
|
||||||
|
flex: 1;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 1.5rem 1rem;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.addFileIcon {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 5rem;
|
||||||
|
height: 5rem;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--bg-subtle);
|
||||||
|
transition: background-color 0.18s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.addFileCard:hover .addFileIcon {
|
||||||
|
background: var(--color-blue-50);
|
||||||
|
}
|
||||||
|
|
||||||
|
.addFileText {
|
||||||
|
font-weight: 500;
|
||||||
|
transition: color 0.18s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.addFileCard:hover .addFileText {
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.addFileSubtext {
|
||||||
|
font-size: 0.875rem;
|
||||||
|
opacity: 0.8;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -----------------------
|
||||||
|
Async Job Progress HUD
|
||||||
|
----------------------- */
|
||||||
|
.jobProgressContainer {
|
||||||
|
position: absolute;
|
||||||
|
left: 8px;
|
||||||
|
right: 8px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 10px;
|
||||||
|
z-index: 6;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.jobProgressRow {
|
||||||
|
pointer-events: auto;
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 10px 14px 12px;
|
||||||
|
background: rgba(18, 26, 44, 0.88);
|
||||||
|
box-shadow: 0 18px 36px rgba(11, 16, 28, 0.25);
|
||||||
|
backdrop-filter: blur(12px);
|
||||||
|
color: #f1f6ff;
|
||||||
|
transition: transform 120ms ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.jobProgressRow[data-status='failed'] {
|
||||||
|
background: rgba(128, 28, 38, 0.9);
|
||||||
|
}
|
||||||
|
|
||||||
|
:global([data-mantine-color-scheme='dark']) .jobProgressRow {
|
||||||
|
background: rgba(28, 39, 58, 0.9);
|
||||||
|
color: var(--mantine-color-gray-2);
|
||||||
|
}
|
||||||
|
|
||||||
|
:global([data-mantine-color-scheme='dark']) .jobProgressRow[data-status='failed'] {
|
||||||
|
background: rgba(138, 34, 43, 0.92);
|
||||||
|
}
|
||||||
|
|
||||||
|
.jobProgressHeader {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
font-size: 0.78rem;
|
||||||
|
font-weight: 600;
|
||||||
|
letter-spacing: 0.01em;
|
||||||
|
}
|
||||||
|
|
||||||
|
.jobProgressLabel {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
}
|
||||||
|
|
||||||
|
.jobProgressValue {
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
opacity: 0.92;
|
||||||
|
}
|
||||||
|
|
||||||
|
.jobProgressTrack {
|
||||||
|
position: relative;
|
||||||
|
margin-top: 8px;
|
||||||
|
height: 6px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: rgba(241, 246, 255, 0.25);
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.jobProgressRow[data-status='failed'] .jobProgressTrack {
|
||||||
|
background: rgba(255, 255, 255, 0.23);
|
||||||
|
}
|
||||||
|
|
||||||
|
.jobProgressFill {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
width: 0;
|
||||||
|
height: 100%;
|
||||||
|
background: linear-gradient(90deg, #5aa5ff 0%, #206de5 100%);
|
||||||
|
transition: width 160ms ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.jobProgressRow[data-status='queued'] .jobProgressFill {
|
||||||
|
background: linear-gradient(90deg, #cfd8dc 0%, #a7b6bf 100%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.jobProgressRow[data-status='failed'] .jobProgressFill {
|
||||||
|
background: linear-gradient(90deg, #ff8a80 0%, #e53935 100%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.jobProgressError {
|
||||||
|
margin-top: 8px;
|
||||||
|
font-size: 0.72rem;
|
||||||
|
line-height: 1.3;
|
||||||
|
opacity: 0.92;
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,13 +1,14 @@
|
|||||||
import React, { useState, useCallback, useRef, useMemo } from 'react';
|
import React, { useState, useCallback, useRef, useMemo, useEffect } from 'react';
|
||||||
import {
|
import {
|
||||||
Text, Center, Box, LoadingOverlay, Stack, Group
|
Text, Center, Box, LoadingOverlay, Stack, Group
|
||||||
} from '@mantine/core';
|
} from '@mantine/core';
|
||||||
import { Dropzone } from '@mantine/dropzone';
|
import { Dropzone } from '@mantine/dropzone';
|
||||||
import { useFileSelection, useFileState, useFileManagement } from '../../contexts/FileContext';
|
import { useFileSelection, useFileState, useFileManagement, useFileActions } from '../../contexts/FileContext';
|
||||||
import { useNavigationActions } from '../../contexts/NavigationContext';
|
import { useNavigationActions } from '../../contexts/NavigationContext';
|
||||||
import { zipFileService } from '../../services/zipFileService';
|
import { zipFileService } from '../../services/zipFileService';
|
||||||
import { detectFileExtension } from '../../utils/fileUtils';
|
import { detectFileExtension } from '../../utils/fileUtils';
|
||||||
import FileEditorThumbnail from './FileEditorThumbnail';
|
import FileEditorThumbnail from './FileEditorThumbnail';
|
||||||
|
import AddFileCard from './AddFileCard';
|
||||||
import FilePickerModal from '../shared/FilePickerModal';
|
import FilePickerModal from '../shared/FilePickerModal';
|
||||||
import SkeletonLoader from '../shared/SkeletonLoader';
|
import SkeletonLoader from '../shared/SkeletonLoader';
|
||||||
import { FileId, StirlingFile } from '../../types/fileContext';
|
import { FileId, StirlingFile } from '../../types/fileContext';
|
||||||
@@ -36,6 +37,7 @@ const FileEditor = ({
|
|||||||
// Use optimized FileContext hooks
|
// Use optimized FileContext hooks
|
||||||
const { state, selectors } = useFileState();
|
const { state, selectors } = useFileState();
|
||||||
const { addFiles, removeFiles, reorderFiles } = useFileManagement();
|
const { addFiles, removeFiles, reorderFiles } = useFileManagement();
|
||||||
|
const { actions } = useFileActions();
|
||||||
|
|
||||||
// Extract needed values from state (memoized to prevent infinite loops)
|
// Extract needed values from state (memoized to prevent infinite loops)
|
||||||
const activeStirlingFileStubs = useMemo(() => selectors.getStirlingFileStubs(), [selectors.getFilesSignature()]);
|
const activeStirlingFileStubs = useMemo(() => selectors.getStirlingFileStubs(), [selectors.getFilesSignature()]);
|
||||||
@@ -60,7 +62,7 @@ const FileEditor = ({
|
|||||||
const [selectionMode, setSelectionMode] = useState(toolMode);
|
const [selectionMode, setSelectionMode] = useState(toolMode);
|
||||||
|
|
||||||
// Enable selection mode automatically in tool mode
|
// Enable selection mode automatically in tool mode
|
||||||
React.useEffect(() => {
|
useEffect(() => {
|
||||||
if (toolMode) {
|
if (toolMode) {
|
||||||
setSelectionMode(true);
|
setSelectionMode(true);
|
||||||
}
|
}
|
||||||
@@ -171,8 +173,8 @@ const FileEditor = ({
|
|||||||
|
|
||||||
// Process all extracted files
|
// Process all extracted files
|
||||||
if (allExtractedFiles.length > 0) {
|
if (allExtractedFiles.length > 0) {
|
||||||
// Add files to context (they will be processed automatically)
|
// Add files to context and select them automatically
|
||||||
await addFiles(allExtractedFiles);
|
await addFiles(allExtractedFiles, { selectFiles: true });
|
||||||
showStatus(`Added ${allExtractedFiles.length} files`, 'success');
|
showStatus(`Added ${allExtractedFiles.length} files`, 'success');
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -286,7 +288,7 @@ const FileEditor = ({
|
|||||||
|
|
||||||
|
|
||||||
// File operations using context
|
// File operations using context
|
||||||
const handleDeleteFile = useCallback((fileId: FileId) => {
|
const handleCloseFile = useCallback((fileId: FileId) => {
|
||||||
const record = activeStirlingFileStubs.find(r => r.id === fileId);
|
const record = activeStirlingFileStubs.find(r => r.id === fileId);
|
||||||
const file = record ? selectors.getFile(record.id) : null;
|
const file = record ? selectors.getFile(record.id) : null;
|
||||||
if (record && file) {
|
if (record && file) {
|
||||||
@@ -308,6 +310,48 @@ const FileEditor = ({
|
|||||||
}
|
}
|
||||||
}, [activeStirlingFileStubs, selectors, _setStatus]);
|
}, [activeStirlingFileStubs, selectors, _setStatus]);
|
||||||
|
|
||||||
|
const handleUnzipFile = useCallback(async (fileId: FileId) => {
|
||||||
|
const record = activeStirlingFileStubs.find(r => r.id === fileId);
|
||||||
|
const file = record ? selectors.getFile(record.id) : null;
|
||||||
|
if (record && file) {
|
||||||
|
try {
|
||||||
|
// Extract and store files using shared service method
|
||||||
|
const result = await zipFileService.extractAndStoreFilesWithHistory(file, record);
|
||||||
|
|
||||||
|
if (result.success && result.extractedStubs.length > 0) {
|
||||||
|
// Add extracted file stubs to FileContext
|
||||||
|
await actions.addStirlingFileStubs(result.extractedStubs);
|
||||||
|
|
||||||
|
// Remove the original ZIP file
|
||||||
|
removeFiles([fileId], false);
|
||||||
|
|
||||||
|
alert({
|
||||||
|
alertType: 'success',
|
||||||
|
title: `Extracted ${result.extractedStubs.length} file(s) from ${file.name}`,
|
||||||
|
expandable: false,
|
||||||
|
durationMs: 3500
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
alert({
|
||||||
|
alertType: 'error',
|
||||||
|
title: `Failed to extract files from ${file.name}`,
|
||||||
|
body: result.errors.join('\n'),
|
||||||
|
expandable: true,
|
||||||
|
durationMs: 3500
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to unzip file:', error);
|
||||||
|
alert({
|
||||||
|
alertType: 'error',
|
||||||
|
title: `Error unzipping ${file.name}`,
|
||||||
|
expandable: false,
|
||||||
|
durationMs: 3500
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [activeStirlingFileStubs, selectors, actions, removeFiles]);
|
||||||
|
|
||||||
const handleViewFile = useCallback((fileId: FileId) => {
|
const handleViewFile = useCallback((fileId: FileId) => {
|
||||||
const record = activeStirlingFileStubs.find(r => r.id === fileId);
|
const record = activeStirlingFileStubs.find(r => r.id === fileId);
|
||||||
if (record) {
|
if (record) {
|
||||||
@@ -347,7 +391,7 @@ const FileEditor = ({
|
|||||||
<Box pos="relative" style={{ overflow: 'auto' }}>
|
<Box pos="relative" style={{ overflow: 'auto' }}>
|
||||||
<LoadingOverlay visible={false} />
|
<LoadingOverlay visible={false} />
|
||||||
|
|
||||||
<Box p="md" pt="xl">
|
<Box p="md">
|
||||||
|
|
||||||
|
|
||||||
{activeStirlingFileStubs.length === 0 && !zipExtractionProgress.isExtracting ? (
|
{activeStirlingFileStubs.length === 0 && !zipExtractionProgress.isExtracting ? (
|
||||||
@@ -405,6 +449,14 @@ const FileEditor = ({
|
|||||||
pointerEvents: 'auto'
|
pointerEvents: 'auto'
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
|
{/* Add File Card - only show when files exist */}
|
||||||
|
{activeStirlingFileStubs.length > 0 && (
|
||||||
|
<AddFileCard
|
||||||
|
key="add-file-card"
|
||||||
|
onFileSelect={handleFileUpload}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
{activeStirlingFileStubs.map((record, index) => {
|
{activeStirlingFileStubs.map((record, index) => {
|
||||||
return (
|
return (
|
||||||
<FileEditorThumbnail
|
<FileEditorThumbnail
|
||||||
@@ -415,11 +467,12 @@ const FileEditor = ({
|
|||||||
selectedFiles={localSelectedIds}
|
selectedFiles={localSelectedIds}
|
||||||
selectionMode={selectionMode}
|
selectionMode={selectionMode}
|
||||||
onToggleFile={toggleFile}
|
onToggleFile={toggleFile}
|
||||||
onDeleteFile={handleDeleteFile}
|
onCloseFile={handleCloseFile}
|
||||||
onViewFile={handleViewFile}
|
onViewFile={handleViewFile}
|
||||||
_onSetStatus={showStatus}
|
_onSetStatus={showStatus}
|
||||||
onReorderFiles={handleReorderFiles}
|
onReorderFiles={handleReorderFiles}
|
||||||
onDownloadFile={handleDownloadFile}
|
onDownloadFile={handleDownloadFile}
|
||||||
|
onUnzipFile={handleUnzipFile}
|
||||||
toolMode={toolMode}
|
toolMode={toolMode}
|
||||||
isSupported={isFileSupported(record.name)}
|
isSupported={isFileSupported(record.name)}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,15 +1,17 @@
|
|||||||
import React, { useState, useCallback, useRef, useMemo, useEffect } from 'react';
|
import React, { useState, useCallback, useRef, useMemo, useEffect } from 'react';
|
||||||
import { Text, ActionIcon, CheckboxIndicator } from '@mantine/core';
|
import { Text, ActionIcon, CheckboxIndicator, Tooltip } from '@mantine/core';
|
||||||
import { alert } from '../toast';
|
import { alert } from '../toast';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import MoreVertIcon from '@mui/icons-material/MoreVert';
|
import MoreVertIcon from '@mui/icons-material/MoreVert';
|
||||||
import DownloadOutlinedIcon from '@mui/icons-material/DownloadOutlined';
|
import DownloadOutlinedIcon from '@mui/icons-material/DownloadOutlined';
|
||||||
import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline';
|
import CloseIcon from '@mui/icons-material/Close';
|
||||||
|
import UnarchiveIcon from '@mui/icons-material/Unarchive';
|
||||||
import PushPinIcon from '@mui/icons-material/PushPin';
|
import PushPinIcon from '@mui/icons-material/PushPin';
|
||||||
import PushPinOutlinedIcon from '@mui/icons-material/PushPinOutlined';
|
import PushPinOutlinedIcon from '@mui/icons-material/PushPinOutlined';
|
||||||
import DragIndicatorIcon from '@mui/icons-material/DragIndicator';
|
import DragIndicatorIcon from '@mui/icons-material/DragIndicator';
|
||||||
import { draggable, dropTargetForElements } from '@atlaskit/pragmatic-drag-and-drop/element/adapter';
|
import { draggable, dropTargetForElements } from '@atlaskit/pragmatic-drag-and-drop/element/adapter';
|
||||||
import { StirlingFileStub } from '../../types/fileContext';
|
import { StirlingFileStub } from '../../types/fileContext';
|
||||||
|
import { zipFileService } from '../../services/zipFileService';
|
||||||
|
|
||||||
import styles from './FileEditor.module.css';
|
import styles from './FileEditor.module.css';
|
||||||
import { useFileContext } from '../../contexts/FileContext';
|
import { useFileContext } from '../../contexts/FileContext';
|
||||||
@@ -27,11 +29,12 @@ interface FileEditorThumbnailProps {
|
|||||||
selectedFiles: FileId[];
|
selectedFiles: FileId[];
|
||||||
selectionMode: boolean;
|
selectionMode: boolean;
|
||||||
onToggleFile: (fileId: FileId) => void;
|
onToggleFile: (fileId: FileId) => void;
|
||||||
onDeleteFile: (fileId: FileId) => void;
|
onCloseFile: (fileId: FileId) => void;
|
||||||
onViewFile: (fileId: FileId) => void;
|
onViewFile: (fileId: FileId) => void;
|
||||||
_onSetStatus: (status: string) => void;
|
_onSetStatus: (status: string) => void;
|
||||||
onReorderFiles?: (sourceFileId: FileId, targetFileId: FileId, selectedFileIds: FileId[]) => void;
|
onReorderFiles?: (sourceFileId: FileId, targetFileId: FileId, selectedFileIds: FileId[]) => void;
|
||||||
onDownloadFile: (fileId: FileId) => void;
|
onDownloadFile: (fileId: FileId) => void;
|
||||||
|
onUnzipFile?: (fileId: FileId) => void;
|
||||||
toolMode?: boolean;
|
toolMode?: boolean;
|
||||||
isSupported?: boolean;
|
isSupported?: boolean;
|
||||||
}
|
}
|
||||||
@@ -41,16 +44,20 @@ const FileEditorThumbnail = ({
|
|||||||
index,
|
index,
|
||||||
selectedFiles,
|
selectedFiles,
|
||||||
onToggleFile,
|
onToggleFile,
|
||||||
onDeleteFile,
|
onCloseFile,
|
||||||
_onSetStatus,
|
_onSetStatus,
|
||||||
onReorderFiles,
|
onReorderFiles,
|
||||||
onDownloadFile,
|
onDownloadFile,
|
||||||
|
onUnzipFile,
|
||||||
isSupported = true,
|
isSupported = true,
|
||||||
}: FileEditorThumbnailProps) => {
|
}: FileEditorThumbnailProps) => {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const { pinFile, unpinFile, isFilePinned, activeFiles, actions: fileActions } = useFileContext();
|
const { pinFile, unpinFile, isFilePinned, activeFiles, actions: fileActions } = useFileContext();
|
||||||
const { state } = useFileState();
|
const { state } = useFileState();
|
||||||
const hasError = state.ui.errorFileIds.includes(file.id);
|
const hasError = state.ui.errorFileIds.includes(file.id);
|
||||||
|
const activeJobs = useMemo(() => file.activeJobs ?? [], [file.activeJobs]);
|
||||||
|
const visibleJobs = useMemo(() => activeJobs.filter(job => job.status !== 'completed'), [activeJobs]);
|
||||||
|
const hasActiveJobs = visibleJobs.length > 0;
|
||||||
|
|
||||||
// ---- Drag state ----
|
// ---- Drag state ----
|
||||||
const [isDragging, setIsDragging] = useState(false);
|
const [isDragging, setIsDragging] = useState(false);
|
||||||
@@ -64,6 +71,9 @@ const FileEditorThumbnail = ({
|
|||||||
}, [activeFiles, file.id]);
|
}, [activeFiles, file.id]);
|
||||||
const isPinned = actualFile ? isFilePinned(actualFile) : false;
|
const isPinned = actualFile ? isFilePinned(actualFile) : false;
|
||||||
|
|
||||||
|
// Check if this is a ZIP file
|
||||||
|
const isZipFile = zipFileService.isZipFileStub(file);
|
||||||
|
|
||||||
const pageCount = file.processedFile?.totalPages || 0;
|
const pageCount = file.processedFile?.totalPages || 0;
|
||||||
|
|
||||||
const handleRef = useRef<HTMLSpanElement | null>(null);
|
const handleRef = useRef<HTMLSpanElement | null>(null);
|
||||||
@@ -206,6 +216,9 @@ const FileEditorThumbnail = ({
|
|||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
const progressContainerBottom = file.toolHistory ? '56px' : '12px';
|
||||||
|
const toolChainBottom = hasActiveJobs ? '8px' : '4px';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
ref={fileElementRef}
|
ref={fileElementRef}
|
||||||
@@ -251,18 +264,60 @@ const FileEditorThumbnail = ({
|
|||||||
{index + 1}
|
{index + 1}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Kebab menu */}
|
{/* Action buttons group */}
|
||||||
<ActionIcon
|
<div className={styles.headerActions}>
|
||||||
aria-label={t('moreOptions', 'More options')}
|
{/* Pin/Unpin icon */}
|
||||||
variant="subtle"
|
<Tooltip label={isPinned ? t('unpin', 'Unpin') : t('pin', 'Pin')}>
|
||||||
className={styles.kebab}
|
<ActionIcon
|
||||||
onClick={(e) => {
|
aria-label={isPinned ? t('unpin', 'Unpin') : t('pin', 'Pin')}
|
||||||
e.stopPropagation();
|
variant="subtle"
|
||||||
setShowActions((v) => !v);
|
className={isPinned ? styles.pinned : styles.headerIconButton}
|
||||||
}}
|
onClick={(e) => {
|
||||||
>
|
e.stopPropagation();
|
||||||
<MoreVertIcon fontSize="small" />
|
if (actualFile) {
|
||||||
</ActionIcon>
|
if (isPinned) {
|
||||||
|
unpinFile(actualFile);
|
||||||
|
alert({ alertType: 'neutral', title: `Unpinned ${file.name}`, expandable: false, durationMs: 3000 });
|
||||||
|
} else {
|
||||||
|
pinFile(actualFile);
|
||||||
|
alert({ alertType: 'success', title: `Pinned ${file.name}`, expandable: false, durationMs: 3000 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{isPinned ? <PushPinIcon fontSize="small" /> : <PushPinOutlinedIcon fontSize="small" />}
|
||||||
|
</ActionIcon>
|
||||||
|
</Tooltip>
|
||||||
|
|
||||||
|
{/* Download icon */}
|
||||||
|
<Tooltip label={t('download', 'Download')}>
|
||||||
|
<ActionIcon
|
||||||
|
aria-label={t('download', 'Download')}
|
||||||
|
variant="subtle"
|
||||||
|
className={styles.headerIconButton}
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
onDownloadFile(file.id);
|
||||||
|
alert({ alertType: 'success', title: `Downloading ${file.name}`, expandable: false, durationMs: 2500 });
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<DownloadOutlinedIcon fontSize="small" />
|
||||||
|
</ActionIcon>
|
||||||
|
</Tooltip>
|
||||||
|
|
||||||
|
{/* Kebab menu */}
|
||||||
|
<ActionIcon
|
||||||
|
aria-label={t('moreOptions', 'More options')}
|
||||||
|
variant="subtle"
|
||||||
|
className={styles.headerIconButton}
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
setShowActions((v) => !v);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<MoreVertIcon fontSize="small" />
|
||||||
|
</ActionIcon>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Actions overlay */}
|
{/* Actions overlay */}
|
||||||
@@ -287,7 +342,7 @@ const FileEditorThumbnail = ({
|
|||||||
setShowActions(false);
|
setShowActions(false);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{isPinned ? <PushPinIcon fontSize="small" /> : <PushPinOutlinedIcon fontSize="small" />}
|
{isPinned ? <PushPinIcon className={styles.pinned} fontSize="small" /> : <PushPinOutlinedIcon fontSize="small" />}
|
||||||
<span>{isPinned ? t('unpin', 'Unpin') : t('pin', 'Pin')}</span>
|
<span>{isPinned ? t('unpin', 'Unpin') : t('pin', 'Pin')}</span>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
@@ -299,18 +354,28 @@ const FileEditorThumbnail = ({
|
|||||||
<span>{t('download', 'Download')}</span>
|
<span>{t('download', 'Download')}</span>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
|
{isZipFile && onUnzipFile && (
|
||||||
|
<button
|
||||||
|
className={styles.actionRow}
|
||||||
|
onClick={() => { onUnzipFile(file.id); alert({ alertType: 'success', title: `Unzipping ${file.name}`, expandable: false, durationMs: 2500 }); setShowActions(false); }}
|
||||||
|
>
|
||||||
|
<UnarchiveIcon fontSize="small" />
|
||||||
|
<span>{t('fileManager.unzip', 'Unzip')}</span>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
|
||||||
<div className={styles.actionsDivider} />
|
<div className={styles.actionsDivider} />
|
||||||
|
|
||||||
<button
|
<button
|
||||||
className={`${styles.actionRow} ${styles.actionDanger}`}
|
className={`${styles.actionRow} ${styles.actionDanger}`}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
onDeleteFile(file.id);
|
onCloseFile(file.id);
|
||||||
alert({ alertType: 'neutral', title: `Deleted ${file.name}`, expandable: false, durationMs: 3500 });
|
alert({ alertType: 'neutral', title: `Closed ${file.name}`, expandable: false, durationMs: 3500 });
|
||||||
setShowActions(false);
|
setShowActions(false);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<DeleteOutlineIcon fontSize="small" />
|
<CloseIcon fontSize="small" />
|
||||||
<span>{t('delete', 'Delete')}</span>
|
<span>{t('close', 'Close')}</span>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -324,7 +389,7 @@ const FileEditorThumbnail = ({
|
|||||||
marginTop: '0.5rem',
|
marginTop: '0.5rem',
|
||||||
marginBottom: '0.5rem',
|
marginBottom: '0.5rem',
|
||||||
}}>
|
}}>
|
||||||
<Text size="lg" fw={700} className={styles.title} lineClamp={2}>
|
<Text size="lg" fw={700} className={`${styles.title} ph-no-capture `} lineClamp={2}>
|
||||||
{file.name}
|
{file.name}
|
||||||
</Text>
|
</Text>
|
||||||
<Text
|
<Text
|
||||||
@@ -350,6 +415,7 @@ const FileEditorThumbnail = ({
|
|||||||
<div className={styles.previewPaper}>
|
<div className={styles.previewPaper}>
|
||||||
{file.thumbnailUrl && (
|
{file.thumbnailUrl && (
|
||||||
<img
|
<img
|
||||||
|
className="ph-no-capture"
|
||||||
src={file.thumbnailUrl}
|
src={file.thumbnailUrl}
|
||||||
alt={file.name}
|
alt={file.name}
|
||||||
draggable={false}
|
draggable={false}
|
||||||
@@ -376,11 +442,52 @@ const FileEditorThumbnail = ({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Pin indicator (bottom-left) */}
|
{hasActiveJobs && (
|
||||||
{isPinned && (
|
<div
|
||||||
<span className={styles.pinIndicator} aria-hidden>
|
className={styles.jobProgressContainer}
|
||||||
<PushPinIcon fontSize="small" />
|
style={{ bottom: progressContainerBottom }}
|
||||||
</span>
|
>
|
||||||
|
{visibleJobs.map(job => {
|
||||||
|
const queueSuffix = typeof job.queuePosition === 'number' ? ` (#${job.queuePosition + 1})` : '';
|
||||||
|
const label = job.message
|
||||||
|
|| (job.status === 'failed'
|
||||||
|
? t('async.jobFailed', 'Job failed')
|
||||||
|
: job.status === 'queued'
|
||||||
|
? `${t('async.jobQueued', 'Waiting in queue')}${queueSuffix}`
|
||||||
|
: t('async.jobProcessing', 'Processing…'));
|
||||||
|
const rawPercent = Number.isFinite(job.progressPercent) ? Math.round(job.progressPercent) : 0;
|
||||||
|
const percent = Math.max(0, Math.min(rawPercent, 100));
|
||||||
|
const displayValue = job.status === 'failed'
|
||||||
|
? t('async.jobFailedShort', 'Failed')
|
||||||
|
: job.status === 'queued'
|
||||||
|
? t('async.jobQueuedShort', 'Queued')
|
||||||
|
: `${percent}%`;
|
||||||
|
const fillBase = job.status === 'failed'
|
||||||
|
? 100
|
||||||
|
: Math.max(job.status === 'queued' ? 12 : 6, percent);
|
||||||
|
const fillWidth = Math.max(0, Math.min(fillBase, 100));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={job.jobId}
|
||||||
|
className={styles.jobProgressRow}
|
||||||
|
data-status={job.status}
|
||||||
|
title={job.error || label}
|
||||||
|
>
|
||||||
|
<div className={styles.jobProgressHeader}>
|
||||||
|
<span className={styles.jobProgressLabel}>{label}</span>
|
||||||
|
<span className={styles.jobProgressValue}>{displayValue}</span>
|
||||||
|
</div>
|
||||||
|
<div className={styles.jobProgressTrack}>
|
||||||
|
<div className={styles.jobProgressFill} style={{ width: `${fillWidth}%` }} />
|
||||||
|
</div>
|
||||||
|
{job.status === 'failed' && job.error && (
|
||||||
|
<div className={styles.jobProgressError}>{job.error}</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Drag handle (span wrapper so we can attach a ref reliably) */}
|
{/* Drag handle (span wrapper so we can attach a ref reliably) */}
|
||||||
@@ -392,7 +499,7 @@ const FileEditorThumbnail = ({
|
|||||||
{file.toolHistory && (
|
{file.toolHistory && (
|
||||||
<div style={{
|
<div style={{
|
||||||
position: 'absolute',
|
position: 'absolute',
|
||||||
bottom: '4px',
|
bottom: toolChainBottom,
|
||||||
left: '4px',
|
left: '4px',
|
||||||
right: '4px',
|
right: '4px',
|
||||||
padding: '4px 6px',
|
padding: '4px 6px',
|
||||||
|
|||||||
@@ -0,0 +1,115 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import { Button, Group, Text, Stack, useMantineColorScheme } from '@mantine/core';
|
||||||
|
import HistoryIcon from '@mui/icons-material/History';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { useFileManagerContext } from '../../contexts/FileManagerContext';
|
||||||
|
import LocalIcon from '../shared/LocalIcon';
|
||||||
|
import { BASE_PATH } from '../../constants/app';
|
||||||
|
|
||||||
|
const EmptyFilesState: React.FC = () => {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const { colorScheme } = useMantineColorScheme();
|
||||||
|
const { onLocalFileClick } = useFileManagerContext();
|
||||||
|
const [isUploadHover, setIsUploadHover] = useState(false);
|
||||||
|
|
||||||
|
const handleUploadClick = () => {
|
||||||
|
onLocalFileClick();
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
height: '100%',
|
||||||
|
width: '100%',
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
padding: '2rem'
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{/* Container */}
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
backgroundColor: 'transparent',
|
||||||
|
padding: '3rem 2rem',
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
gap: '1.5rem',
|
||||||
|
minWidth: '20rem',
|
||||||
|
maxWidth: '28rem',
|
||||||
|
width: '100%'
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{/* No Recent Files Message */}
|
||||||
|
<Stack align="center" gap="sm">
|
||||||
|
<HistoryIcon style={{ fontSize: '3rem', color: 'var(--mantine-color-gray-5)' }} />
|
||||||
|
<Text c="dimmed" ta="center" size="lg">
|
||||||
|
{t('fileManager.noRecentFiles', 'No recent files')}
|
||||||
|
</Text>
|
||||||
|
</Stack>
|
||||||
|
|
||||||
|
{/* Stirling PDF Logo */}
|
||||||
|
<Group gap="xs" align="center">
|
||||||
|
<img
|
||||||
|
src={colorScheme === 'dark' ? `${BASE_PATH}/branding/StirlingPDFLogoWhiteText.svg` : `${BASE_PATH}/branding/StirlingPDFLogoGreyText.svg`}
|
||||||
|
alt="Stirling PDF"
|
||||||
|
style={{ height: '2.2rem', width: 'auto' }}
|
||||||
|
/>
|
||||||
|
</Group>
|
||||||
|
|
||||||
|
{/* Upload Button */}
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
width: '100%',
|
||||||
|
marginTop: '0.5rem',
|
||||||
|
marginBottom: '0.5rem'
|
||||||
|
}}
|
||||||
|
onMouseLeave={() => setIsUploadHover(false)}
|
||||||
|
>
|
||||||
|
<Button
|
||||||
|
aria-label="Upload"
|
||||||
|
style={{
|
||||||
|
backgroundColor: 'var(--bg-file-manager)',
|
||||||
|
color: 'var(--landing-button-color)',
|
||||||
|
border: '1px solid var(--landing-button-border)',
|
||||||
|
borderRadius: isUploadHover ? '2rem' : '1rem',
|
||||||
|
height: '38px',
|
||||||
|
width: isUploadHover ? '100%' : '58px',
|
||||||
|
minWidth: '58px',
|
||||||
|
paddingLeft: isUploadHover ? '1rem' : 0,
|
||||||
|
paddingRight: isUploadHover ? '1rem' : 0,
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
transition: 'width .5s ease, padding .5s ease, border-radius .5s ease'
|
||||||
|
}}
|
||||||
|
onClick={handleUploadClick}
|
||||||
|
onMouseEnter={() => setIsUploadHover(true)}
|
||||||
|
>
|
||||||
|
<LocalIcon icon="upload" width="1.25rem" height="1.25rem" style={{ color: 'var(--accent-interactive)' }} />
|
||||||
|
{isUploadHover && (
|
||||||
|
<span style={{ marginLeft: '.5rem' }}>
|
||||||
|
{t('landing.uploadFromComputer', 'Upload from computer')}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Instruction Text */}
|
||||||
|
<span
|
||||||
|
className="text-[var(--accent-interactive)]"
|
||||||
|
style={{ fontSize: '.8rem', textAlign: 'center' }}
|
||||||
|
>
|
||||||
|
{t('fileUpload.dropFilesHere', 'Drop files here or click the upload button')}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default EmptyFilesState;
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import React, { useState } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
import { Stack, Button, Box } from '@mantine/core';
|
import { Stack, Button, Box } from '@mantine/core';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { useIndexedDBThumbnail } from '../../hooks/useIndexedDBThumbnail';
|
import { useIndexedDBThumbnail } from '../../hooks/useIndexedDBThumbnail';
|
||||||
@@ -50,7 +50,7 @@ const FileDetails: React.FC<FileDetailsProps> = ({
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Reset index when selection changes
|
// Reset index when selection changes
|
||||||
React.useEffect(() => {
|
useEffect(() => {
|
||||||
if (currentFileIndex >= selectedFiles.length) {
|
if (currentFileIndex >= selectedFiles.length) {
|
||||||
setCurrentFileIndex(0);
|
setCurrentFileIndex(0);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ const FileHistoryGroup: React.FC<FileHistoryGroupProps> = ({
|
|||||||
</Group>
|
</Group>
|
||||||
|
|
||||||
<Box ml="md">
|
<Box ml="md">
|
||||||
{sortedHistory.map((historyFile, _index) => (
|
{sortedHistory.map((historyFile) => (
|
||||||
<FileListItem
|
<FileListItem
|
||||||
key={`history-${historyFile.id}-${historyFile.versionNumber || 1}`}
|
key={`history-${historyFile.id}-${historyFile.versionNumber || 1}`}
|
||||||
file={historyFile}
|
file={historyFile}
|
||||||
@@ -56,7 +56,6 @@ const FileHistoryGroup: React.FC<FileHistoryGroupProps> = ({
|
|||||||
onDoubleClick={() => onFileDoubleClick(historyFile)}
|
onDoubleClick={() => onFileDoubleClick(historyFile)}
|
||||||
isHistoryFile={true} // This enables "Add to Recents" in menu
|
isHistoryFile={true} // This enables "Add to Recents" in menu
|
||||||
isLatestVersion={false} // History files are never latest
|
isLatestVersion={false} // History files are never latest
|
||||||
// onAddToRecents is accessed from context by FileListItem
|
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</Box>
|
</Box>
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ const FileInfoCard: React.FC<FileInfoCardProps> = ({
|
|||||||
<ScrollArea style={{ flex: 1 }} p="md">
|
<ScrollArea style={{ flex: 1 }} p="md">
|
||||||
<Stack gap="sm">
|
<Stack gap="sm">
|
||||||
<Group justify="space-between" py="xs">
|
<Group justify="space-between" py="xs">
|
||||||
<Text size="sm" c="dimmed">{t('fileManager.fileName', 'Name')}</Text>
|
<Text className='ph-no-capture' size="sm" c="dimmed">{t('fileManager.fileName', 'Name')}</Text>
|
||||||
<Text size="sm" fw={500} style={{ maxWidth: '60%', textAlign: 'right' }} truncate>
|
<Text size="sm" fw={500} style={{ maxWidth: '60%', textAlign: 'right' }} truncate>
|
||||||
{currentFile ? currentFile.name : ''}
|
{currentFile ? currentFile.name : ''}
|
||||||
</Text>
|
</Text>
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { Center, ScrollArea, Text, Stack } from '@mantine/core';
|
import { Center, ScrollArea, Text, Stack } from '@mantine/core';
|
||||||
import CloudIcon from '@mui/icons-material/Cloud';
|
import CloudIcon from '@mui/icons-material/Cloud';
|
||||||
import HistoryIcon from '@mui/icons-material/History';
|
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import FileListItem from './FileListItem';
|
import FileListItem from './FileListItem';
|
||||||
import FileHistoryGroup from './FileHistoryGroup';
|
import FileHistoryGroup from './FileHistoryGroup';
|
||||||
|
import EmptyFilesState from './EmptyFilesState';
|
||||||
import { useFileManagerContext } from '../../contexts/FileManagerContext';
|
import { useFileManagerContext } from '../../contexts/FileManagerContext';
|
||||||
|
|
||||||
interface FileListAreaProps {
|
interface FileListAreaProps {
|
||||||
@@ -29,6 +29,7 @@ const FileListArea: React.FC<FileListAreaProps> = ({
|
|||||||
onFileDoubleClick,
|
onFileDoubleClick,
|
||||||
onDownloadSingle,
|
onDownloadSingle,
|
||||||
isFileSupported,
|
isFileSupported,
|
||||||
|
isLoading,
|
||||||
} = useFileManagerContext();
|
} = useFileManagerContext();
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
|
||||||
@@ -43,15 +44,11 @@ const FileListArea: React.FC<FileListAreaProps> = ({
|
|||||||
scrollbarSize={8}
|
scrollbarSize={8}
|
||||||
>
|
>
|
||||||
<Stack gap={0}>
|
<Stack gap={0}>
|
||||||
{recentFiles.length === 0 ? (
|
{recentFiles.length === 0 && !isLoading ? (
|
||||||
|
<EmptyFilesState />
|
||||||
|
) : recentFiles.length === 0 && isLoading ? (
|
||||||
<Center style={{ height: '12.5rem' }}>
|
<Center style={{ height: '12.5rem' }}>
|
||||||
<Stack align="center" gap="sm">
|
<Text c="dimmed" ta="center">{t('fileManager.loadingFiles', 'Loading files...')}</Text>
|
||||||
<HistoryIcon style={{ fontSize: '3rem', color: 'var(--mantine-color-gray-5)' }} />
|
|
||||||
<Text c="dimmed" ta="center">{t('fileManager.noRecentFiles', 'No recent files')}</Text>
|
|
||||||
<Text size="xs" c="dimmed" ta="center" style={{ opacity: 0.7 }}>
|
|
||||||
{t('fileManager.dropFilesHint', 'Drop files anywhere to upload')}
|
|
||||||
</Text>
|
|
||||||
</Stack>
|
|
||||||
</Center>
|
</Center>
|
||||||
) : (
|
) : (
|
||||||
filteredFiles.map((file, index) => {
|
filteredFiles.map((file, index) => {
|
||||||
|
|||||||
@@ -5,10 +5,12 @@ import DeleteIcon from '@mui/icons-material/Delete';
|
|||||||
import DownloadIcon from '@mui/icons-material/Download';
|
import DownloadIcon from '@mui/icons-material/Download';
|
||||||
import HistoryIcon from '@mui/icons-material/History';
|
import HistoryIcon from '@mui/icons-material/History';
|
||||||
import RestoreIcon from '@mui/icons-material/Restore';
|
import RestoreIcon from '@mui/icons-material/Restore';
|
||||||
|
import UnarchiveIcon from '@mui/icons-material/Unarchive';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { getFileSize, getFileDate } from '../../utils/fileUtils';
|
import { getFileSize, getFileDate } from '../../utils/fileUtils';
|
||||||
import { FileId, StirlingFileStub } from '../../types/fileContext';
|
import { FileId, StirlingFileStub } from '../../types/fileContext';
|
||||||
import { useFileManagerContext } from '../../contexts/FileManagerContext';
|
import { useFileManagerContext } from '../../contexts/FileManagerContext';
|
||||||
|
import { zipFileService } from '../../services/zipFileService';
|
||||||
import ToolChain from '../shared/ToolChain';
|
import ToolChain from '../shared/ToolChain';
|
||||||
|
|
||||||
interface FileListItemProps {
|
interface FileListItemProps {
|
||||||
@@ -38,7 +40,10 @@ const FileListItem: React.FC<FileListItemProps> = ({
|
|||||||
const [isHovered, setIsHovered] = useState(false);
|
const [isHovered, setIsHovered] = useState(false);
|
||||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const {expandedFileIds, onToggleExpansion, onAddToRecents } = useFileManagerContext();
|
const {expandedFileIds, onToggleExpansion, onUnzipFile } = useFileManagerContext();
|
||||||
|
|
||||||
|
// Check if this is a ZIP file
|
||||||
|
const isZipFile = zipFileService.isZipFileStub(file);
|
||||||
|
|
||||||
// Keep item in hovered state if menu is open
|
// Keep item in hovered state if menu is open
|
||||||
const shouldShowHovered = isHovered || isMenuOpen;
|
const shouldShowHovered = isHovered || isMenuOpen;
|
||||||
@@ -93,7 +98,7 @@ const FileListItem: React.FC<FileListItemProps> = ({
|
|||||||
|
|
||||||
<Box style={{ flex: 1, minWidth: 0 }}>
|
<Box style={{ flex: 1, minWidth: 0 }}>
|
||||||
<Group gap="xs" align="center">
|
<Group gap="xs" align="center">
|
||||||
<Text size="sm" fw={500} truncate style={{ flex: 1 }}>{file.name}</Text>
|
<Text size="sm" fw={500} className='ph-no-capture' truncate style={{ flex: 1 }}>{file.name}</Text>
|
||||||
<Badge size="xs" variant="light" color={"blue"}>
|
<Badge size="xs" variant="light" color={"blue"}>
|
||||||
v{currentVersion}
|
v{currentVersion}
|
||||||
</Badge>
|
</Badge>
|
||||||
@@ -183,7 +188,6 @@ const FileListItem: React.FC<FileListItemProps> = ({
|
|||||||
leftSection={<RestoreIcon style={{ fontSize: 16 }} />}
|
leftSection={<RestoreIcon style={{ fontSize: 16 }} />}
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
onAddToRecents(file);
|
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{t('fileManager.restore', 'Restore')}
|
{t('fileManager.restore', 'Restore')}
|
||||||
@@ -192,6 +196,22 @@ const FileListItem: React.FC<FileListItemProps> = ({
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* Unzip option for ZIP files */}
|
||||||
|
{isZipFile && !isHistoryFile && (
|
||||||
|
<>
|
||||||
|
<Menu.Item
|
||||||
|
leftSection={<UnarchiveIcon style={{ fontSize: 16 }} />}
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
onUnzipFile(file);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t('fileManager.unzip', 'Unzip')}
|
||||||
|
</Menu.Item>
|
||||||
|
<Menu.Divider />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
<Menu.Item
|
<Menu.Item
|
||||||
leftSection={<DeleteIcon style={{ fontSize: 16 }} />}
|
leftSection={<DeleteIcon style={{ fontSize: 16 }} />}
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import UploadIcon from '@mui/icons-material/Upload';
|
|||||||
import CloudIcon from '@mui/icons-material/Cloud';
|
import CloudIcon from '@mui/icons-material/Cloud';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { useFileManagerContext } from '../../contexts/FileManagerContext';
|
import { useFileManagerContext } from '../../contexts/FileManagerContext';
|
||||||
|
import { useGoogleDrivePicker } from '../../hooks/useGoogleDrivePicker';
|
||||||
|
|
||||||
interface FileSourceButtonsProps {
|
interface FileSourceButtonsProps {
|
||||||
horizontal?: boolean;
|
horizontal?: boolean;
|
||||||
@@ -13,8 +14,20 @@ interface FileSourceButtonsProps {
|
|||||||
const FileSourceButtons: React.FC<FileSourceButtonsProps> = ({
|
const FileSourceButtons: React.FC<FileSourceButtonsProps> = ({
|
||||||
horizontal = false
|
horizontal = false
|
||||||
}) => {
|
}) => {
|
||||||
const { activeSource, onSourceChange, onLocalFileClick } = useFileManagerContext();
|
const { activeSource, onSourceChange, onLocalFileClick, onGoogleDriveSelect } = useFileManagerContext();
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
const { isEnabled: isGoogleDriveEnabled, openPicker: openGoogleDrivePicker } = useGoogleDrivePicker();
|
||||||
|
|
||||||
|
const handleGoogleDriveClick = async () => {
|
||||||
|
try {
|
||||||
|
const files = await openGoogleDrivePicker({ multiple: true });
|
||||||
|
if (files.length > 0) {
|
||||||
|
onGoogleDriveSelect(files);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to pick files from Google Drive:', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const buttonProps = {
|
const buttonProps = {
|
||||||
variant: (source: string) => activeSource === source ? 'filled' : 'subtle',
|
variant: (source: string) => activeSource === source ? 'filled' : 'subtle',
|
||||||
@@ -67,15 +80,24 @@ const FileSourceButtons: React.FC<FileSourceButtonsProps> = ({
|
|||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
variant={buttonProps.variant('drive')}
|
variant="subtle"
|
||||||
|
color='var(--mantine-color-gray-6)'
|
||||||
leftSection={<CloudIcon />}
|
leftSection={<CloudIcon />}
|
||||||
justify={horizontal ? "center" : "flex-start"}
|
justify={horizontal ? "center" : "flex-start"}
|
||||||
onClick={() => onSourceChange('drive')}
|
onClick={handleGoogleDriveClick}
|
||||||
fullWidth={!horizontal}
|
fullWidth={!horizontal}
|
||||||
size={horizontal ? "xs" : "sm"}
|
size={horizontal ? "xs" : "sm"}
|
||||||
disabled
|
disabled={!isGoogleDriveEnabled}
|
||||||
color={activeSource === 'drive' ? 'gray' : undefined}
|
styles={{
|
||||||
styles={buttonProps.getStyles('drive')}
|
root: {
|
||||||
|
backgroundColor: 'transparent',
|
||||||
|
border: 'none',
|
||||||
|
'&:hover': {
|
||||||
|
backgroundColor: isGoogleDriveEnabled ? 'var(--mantine-color-gray-0)' : 'transparent'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
title={!isGoogleDriveEnabled ? t('fileManager.googleDriveNotAvailable', 'Google Drive integration not available') : undefined}
|
||||||
>
|
>
|
||||||
{horizontal ? t('fileManager.googleDriveShort', 'Drive') : t('fileManager.googleDrive', 'Google Drive')}
|
{horizontal ? t('fileManager.googleDriveShort', 'Drive') : t('fileManager.googleDrive', 'Google Drive')}
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ const HiddenFileInput: React.FC = () => {
|
|||||||
ref={fileInputRef}
|
ref={fileInputRef}
|
||||||
type="file"
|
type="file"
|
||||||
multiple={true}
|
multiple={true}
|
||||||
accept={["*/*"] as any}
|
|
||||||
onChange={onFileInputChange}
|
onChange={onFileInputChange}
|
||||||
style={{ display: 'none' }}
|
style={{ display: 'none' }}
|
||||||
data-testid="file-input"
|
data-testid="file-input"
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { HotkeyBinding } from '../../utils/hotkeys';
|
||||||
|
import { useHotkeys } from '../../contexts/HotkeyContext';
|
||||||
|
|
||||||
|
interface HotkeyDisplayProps {
|
||||||
|
binding: HotkeyBinding | null | undefined;
|
||||||
|
size?: 'sm' | 'md';
|
||||||
|
muted?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const baseKeyStyle: React.CSSProperties = {
|
||||||
|
display: 'inline-flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
borderRadius: '0.375rem',
|
||||||
|
background: 'var(--mantine-color-gray-1)',
|
||||||
|
border: '1px solid var(--mantine-color-gray-3)',
|
||||||
|
padding: '0.125rem 0.35rem',
|
||||||
|
fontSize: '0.75rem',
|
||||||
|
lineHeight: 1,
|
||||||
|
fontFamily: 'var(--mantine-font-family-monospace, monospace)',
|
||||||
|
minWidth: '1.35rem',
|
||||||
|
color: 'var(--mantine-color-text)',
|
||||||
|
};
|
||||||
|
|
||||||
|
export const HotkeyDisplay: React.FC<HotkeyDisplayProps> = ({ binding, size = 'sm', muted = false }) => {
|
||||||
|
const { getDisplayParts } = useHotkeys();
|
||||||
|
const parts = getDisplayParts(binding);
|
||||||
|
|
||||||
|
if (!binding || parts.length === 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const keyStyle = size === 'md'
|
||||||
|
? { ...baseKeyStyle, fontSize: '0.85rem', padding: '0.2rem 0.5rem' }
|
||||||
|
: baseKeyStyle;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
style={{
|
||||||
|
display: 'inline-flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
gap: '0.25rem',
|
||||||
|
color: muted ? 'var(--mantine-color-dimmed)' : 'inherit',
|
||||||
|
fontWeight: muted ? 500 : 600,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{parts.map((part, index) => (
|
||||||
|
<React.Fragment key={`${part}-${index}`}>
|
||||||
|
<kbd style={keyStyle}>{part}</kbd>
|
||||||
|
{index < parts.length - 1 && <span aria-hidden style={{ fontWeight: 400 }}>+</span>}
|
||||||
|
</React.Fragment>
|
||||||
|
))}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default HotkeyDisplay;
|
||||||
@@ -146,10 +146,12 @@ export default function Workbench() {
|
|||||||
}
|
}
|
||||||
>
|
>
|
||||||
{/* Top Controls */}
|
{/* Top Controls */}
|
||||||
<TopControls
|
{activeFiles.length > 0 && (
|
||||||
currentView={currentView}
|
<TopControls
|
||||||
setCurrentView={setCurrentView}
|
currentView={currentView}
|
||||||
/>
|
setCurrentView={setCurrentView}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
{/* Dismiss All Errors Button */}
|
{/* Dismiss All Errors Button */}
|
||||||
<DismissAllErrorsButton />
|
<DismissAllErrorsButton />
|
||||||
@@ -159,6 +161,7 @@ export default function Workbench() {
|
|||||||
className="flex-1 min-h-0 relative z-10 workbench-scrollable "
|
className="flex-1 min-h-0 relative z-10 workbench-scrollable "
|
||||||
style={{
|
style={{
|
||||||
transition: 'opacity 0.15s ease-in-out',
|
transition: 'opacity 0.15s ease-in-out',
|
||||||
|
paddingTop: activeFiles.length > 0 ? '3.5rem' : '0',
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{renderMainContent()}
|
{renderMainContent()}
|
||||||
|
|||||||
@@ -317,6 +317,7 @@ const FileThumbnail = ({
|
|||||||
>
|
>
|
||||||
{file.thumbnail && (
|
{file.thumbnail && (
|
||||||
<img
|
<img
|
||||||
|
className="ph-no-capture"
|
||||||
src={file.thumbnail}
|
src={file.thumbnail}
|
||||||
alt={file.name}
|
alt={file.name}
|
||||||
draggable={false}
|
draggable={false}
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ import { useNavigationGuard } from "../../contexts/NavigationContext";
|
|||||||
import { PDFDocument, PageEditorFunctions } from "../../types/pageEditor";
|
import { PDFDocument, PageEditorFunctions } from "../../types/pageEditor";
|
||||||
import { pdfExportService } from "../../services/pdfExportService";
|
import { pdfExportService } from "../../services/pdfExportService";
|
||||||
import { documentManipulationService } from "../../services/documentManipulationService";
|
import { documentManipulationService } from "../../services/documentManipulationService";
|
||||||
|
import { exportProcessedDocumentsToFiles } from "../../services/pdfExportHelpers";
|
||||||
|
import { createStirlingFilesAndStubs } from "../../services/fileStubHelpers";
|
||||||
// Thumbnail generation is now handled by individual PageThumbnail components
|
// Thumbnail generation is now handled by individual PageThumbnail components
|
||||||
import './PageEditor.module.css';
|
import './PageEditor.module.css';
|
||||||
import PageThumbnail from './PageThumbnail';
|
import PageThumbnail from './PageThumbnail';
|
||||||
@@ -524,66 +526,38 @@ const PageEditor = ({
|
|||||||
try {
|
try {
|
||||||
// Step 1: Apply DOM changes to document state first
|
// Step 1: Apply DOM changes to document state first
|
||||||
const processedDocuments = documentManipulationService.applyDOMChangesToDocument(
|
const processedDocuments = documentManipulationService.applyDOMChangesToDocument(
|
||||||
mergedPdfDocument || displayDocument, // Original order
|
mergedPdfDocument || displayDocument,
|
||||||
displayDocument, // Current display order (includes reordering)
|
displayDocument,
|
||||||
splitPositions // Position-based splits
|
splitPositions
|
||||||
);
|
);
|
||||||
|
|
||||||
// Step 2: Check if we have multiple documents (splits) or single document
|
// Step 2: Export to files
|
||||||
if (Array.isArray(processedDocuments)) {
|
const sourceFiles = getSourceFiles();
|
||||||
// Multiple documents (splits) - export as ZIP
|
const exportFilename = getExportFilename();
|
||||||
const blobs: Blob[] = [];
|
const files = await exportProcessedDocumentsToFiles(processedDocuments, sourceFiles, exportFilename);
|
||||||
const filenames: string[] = [];
|
|
||||||
|
|
||||||
const sourceFiles = getSourceFiles();
|
// Step 3: Download
|
||||||
const baseExportFilename = getExportFilename();
|
if (files.length > 1) {
|
||||||
const baseName = baseExportFilename.replace(/\.pdf$/i, '');
|
// Multiple files - create ZIP
|
||||||
|
|
||||||
for (let i = 0; i < processedDocuments.length; i++) {
|
|
||||||
const doc = processedDocuments[i];
|
|
||||||
const partFilename = `${baseName}_part_${i + 1}.pdf`;
|
|
||||||
|
|
||||||
const result = sourceFiles
|
|
||||||
? await pdfExportService.exportPDFMultiFile(doc, sourceFiles, [], { filename: partFilename })
|
|
||||||
: await pdfExportService.exportPDF(doc, [], { filename: partFilename });
|
|
||||||
blobs.push(result.blob);
|
|
||||||
filenames.push(result.filename);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create ZIP file
|
|
||||||
const JSZip = await import('jszip');
|
const JSZip = await import('jszip');
|
||||||
const zip = new JSZip.default();
|
const zip = new JSZip.default();
|
||||||
|
|
||||||
blobs.forEach((blob, index) => {
|
files.forEach((file) => {
|
||||||
zip.file(filenames[index], blob);
|
zip.file(file.name, file);
|
||||||
});
|
});
|
||||||
|
|
||||||
const zipBlob = await zip.generateAsync({ type: 'blob' });
|
const zipBlob = await zip.generateAsync({ type: 'blob' });
|
||||||
const zipFilename = baseExportFilename.replace(/\.pdf$/i, '.zip');
|
const exportFilename = getExportFilename();
|
||||||
|
const zipFilename = exportFilename.replace(/\.pdf$/i, '.zip');
|
||||||
|
|
||||||
pdfExportService.downloadFile(zipBlob, zipFilename);
|
pdfExportService.downloadFile(zipBlob, zipFilename);
|
||||||
setHasUnsavedChanges(false); // Clear unsaved changes after successful export
|
|
||||||
} else {
|
} else {
|
||||||
// Single document - regular export
|
// Single file - download directly
|
||||||
const sourceFiles = getSourceFiles();
|
const file = files[0];
|
||||||
const exportFilename = getExportFilename();
|
pdfExportService.downloadFile(file, file.name);
|
||||||
const result = sourceFiles
|
|
||||||
? await pdfExportService.exportPDFMultiFile(
|
|
||||||
processedDocuments,
|
|
||||||
sourceFiles,
|
|
||||||
[],
|
|
||||||
{ selectedOnly: false, filename: exportFilename }
|
|
||||||
)
|
|
||||||
: await pdfExportService.exportPDF(
|
|
||||||
processedDocuments,
|
|
||||||
[],
|
|
||||||
{ selectedOnly: false, filename: exportFilename }
|
|
||||||
);
|
|
||||||
|
|
||||||
pdfExportService.downloadFile(result.blob, result.filename);
|
|
||||||
setHasUnsavedChanges(false); // Clear unsaved changes after successful export
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
setHasUnsavedChanges(false);
|
||||||
setExportLoading(false);
|
setExportLoading(false);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Export failed:', error);
|
console.error('Export failed:', error);
|
||||||
@@ -592,21 +566,39 @@ const PageEditor = ({
|
|||||||
}, [displayDocument, mergedPdfDocument, splitPositions, getSourceFiles, getExportFilename, setHasUnsavedChanges]);
|
}, [displayDocument, mergedPdfDocument, splitPositions, getSourceFiles, getExportFilename, setHasUnsavedChanges]);
|
||||||
|
|
||||||
// Apply DOM changes to document state using dedicated service
|
// Apply DOM changes to document state using dedicated service
|
||||||
const applyChanges = useCallback(() => {
|
const applyChanges = useCallback(async () => {
|
||||||
if (!displayDocument) return;
|
if (!displayDocument) return;
|
||||||
|
|
||||||
// Pass current display document (which includes reordering) to get both reordering AND DOM changes
|
setExportLoading(true);
|
||||||
const processedDocuments = documentManipulationService.applyDOMChangesToDocument(
|
try {
|
||||||
mergedPdfDocument || displayDocument, // Original order
|
// Step 1: Apply DOM changes to document state first
|
||||||
displayDocument, // Current display order (includes reordering)
|
const processedDocuments = documentManipulationService.applyDOMChangesToDocument(
|
||||||
splitPositions // Position-based splits
|
mergedPdfDocument || displayDocument,
|
||||||
);
|
displayDocument,
|
||||||
|
splitPositions
|
||||||
|
);
|
||||||
|
|
||||||
// For apply changes, we only set the first document if it's an array (splits shouldn't affect document state)
|
// Step 2: Export to files
|
||||||
const documentToSet = Array.isArray(processedDocuments) ? processedDocuments[0] : processedDocuments;
|
const sourceFiles = getSourceFiles();
|
||||||
setEditedDocument(documentToSet);
|
const exportFilename = getExportFilename();
|
||||||
|
const files = await exportProcessedDocumentsToFiles(processedDocuments, sourceFiles, exportFilename);
|
||||||
|
|
||||||
}, [displayDocument, mergedPdfDocument, splitPositions]);
|
// Step 3: Create StirlingFiles and stubs for version history
|
||||||
|
const parentStub = selectors.getStirlingFileStub(activeFileIds[0]);
|
||||||
|
if (!parentStub) throw new Error('Parent stub not found');
|
||||||
|
|
||||||
|
const { stirlingFiles, stubs } = await createStirlingFilesAndStubs(files, parentStub, 'multiTool');
|
||||||
|
|
||||||
|
// Step 4: Consume files (replace in context)
|
||||||
|
await actions.consumeFiles(activeFileIds, stirlingFiles, stubs);
|
||||||
|
|
||||||
|
setHasUnsavedChanges(false);
|
||||||
|
setExportLoading(false);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Apply changes failed:', error);
|
||||||
|
setExportLoading(false);
|
||||||
|
}
|
||||||
|
}, [displayDocument, mergedPdfDocument, splitPositions, activeFileIds, getSourceFiles, getExportFilename, actions, selectors, setHasUnsavedChanges]);
|
||||||
|
|
||||||
|
|
||||||
const closePdf = useCallback(() => {
|
const closePdf = useCallback(() => {
|
||||||
@@ -670,7 +662,7 @@ const PageEditor = ({
|
|||||||
const displayedPages = displayDocument?.pages || [];
|
const displayedPages = displayDocument?.pages || [];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box pos="relative" h='100%' pt={40} style={{ overflow: 'auto' }} data-scrolling-container="true">
|
<Box pos="relative" h='100%' style={{ overflow: 'auto' }} data-scrolling-container="true">
|
||||||
<LoadingOverlay visible={globalProcessing && !mergedPdfDocument} />
|
<LoadingOverlay visible={globalProcessing && !mergedPdfDocument} />
|
||||||
|
|
||||||
{!mergedPdfDocument && !globalProcessing && activeFileIds.length === 0 && (
|
{!mergedPdfDocument && !globalProcessing && activeFileIds.length === 0 && (
|
||||||
@@ -793,7 +785,7 @@ const PageEditor = ({
|
|||||||
|
|
||||||
<NavigationWarningModal
|
<NavigationWarningModal
|
||||||
onApplyAndContinue={async () => {
|
onApplyAndContinue={async () => {
|
||||||
applyChanges();
|
await applyChanges();
|
||||||
}}
|
}}
|
||||||
onExportAndContinue={async () => {
|
onExportAndContinue={async () => {
|
||||||
await onExportAll();
|
await onExportAll();
|
||||||
|
|||||||
@@ -371,9 +371,11 @@ const PageThumbnail: React.FC<PageThumbnailProps> = ({
|
|||||||
</div>
|
</div>
|
||||||
) : thumbnailUrl ? (
|
) : thumbnailUrl ? (
|
||||||
<img
|
<img
|
||||||
|
className="ph-no-capture"
|
||||||
src={thumbnailUrl}
|
src={thumbnailUrl}
|
||||||
alt={`Page ${page.pageNumber}`}
|
alt={`Page ${page.pageNumber}`}
|
||||||
draggable={false}
|
draggable={false}
|
||||||
|
data-original-rotation={page.rotation}
|
||||||
style={{
|
style={{
|
||||||
width: '100%',
|
width: '100%',
|
||||||
height: '100%',
|
height: '100%',
|
||||||
|
|||||||
@@ -17,32 +17,34 @@ export class RotatePageCommand extends DOMCommand {
|
|||||||
}
|
}
|
||||||
|
|
||||||
execute(): void {
|
execute(): void {
|
||||||
// Only update DOM for immediate visual feedback
|
|
||||||
const pageElement = document.querySelector(`[data-page-id="${this.pageId}"]`);
|
const pageElement = document.querySelector(`[data-page-id="${this.pageId}"]`);
|
||||||
if (pageElement) {
|
if (pageElement) {
|
||||||
const img = pageElement.querySelector('img');
|
const img = pageElement.querySelector('img');
|
||||||
if (img) {
|
if (img) {
|
||||||
// Extract current rotation from transform property to match the animated CSS
|
|
||||||
const currentTransform = img.style.transform || '';
|
const currentTransform = img.style.transform || '';
|
||||||
const rotateMatch = currentTransform.match(/rotate\(([^)]+)\)/);
|
const rotateMatch = currentTransform.match(/rotate\(([^)]+)\)/);
|
||||||
const currentRotation = rotateMatch ? parseInt(rotateMatch[1]) : 0;
|
const currentRotation = rotateMatch ? parseInt(rotateMatch[1]) : 0;
|
||||||
const newRotation = currentRotation + this.degrees;
|
let newRotation = currentRotation + this.degrees;
|
||||||
|
|
||||||
|
newRotation = ((newRotation % 360) + 360) % 360;
|
||||||
|
|
||||||
img.style.transform = `rotate(${newRotation}deg)`;
|
img.style.transform = `rotate(${newRotation}deg)`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
undo(): void {
|
undo(): void {
|
||||||
// Only update DOM
|
|
||||||
const pageElement = document.querySelector(`[data-page-id="${this.pageId}"]`);
|
const pageElement = document.querySelector(`[data-page-id="${this.pageId}"]`);
|
||||||
if (pageElement) {
|
if (pageElement) {
|
||||||
const img = pageElement.querySelector('img');
|
const img = pageElement.querySelector('img');
|
||||||
if (img) {
|
if (img) {
|
||||||
// Extract current rotation from transform property
|
|
||||||
const currentTransform = img.style.transform || '';
|
const currentTransform = img.style.transform || '';
|
||||||
const rotateMatch = currentTransform.match(/rotate\(([^)]+)\)/);
|
const rotateMatch = currentTransform.match(/rotate\(([^)]+)\)/);
|
||||||
const currentRotation = rotateMatch ? parseInt(rotateMatch[1]) : 0;
|
const currentRotation = rotateMatch ? parseInt(rotateMatch[1]) : 0;
|
||||||
const previousRotation = currentRotation - this.degrees;
|
let previousRotation = currentRotation - this.degrees;
|
||||||
|
|
||||||
|
previousRotation = ((previousRotation % 360) + 360) % 360;
|
||||||
|
|
||||||
img.style.transform = `rotate(${previousRotation}deg)`;
|
img.style.transform = `rotate(${previousRotation}deg)`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,130 @@
|
|||||||
|
/* AppConfigModal styles */
|
||||||
|
.modal-container {
|
||||||
|
display: flex;
|
||||||
|
gap: 0;
|
||||||
|
height: 37.5rem; /* 600px */
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-nav {
|
||||||
|
width: 15rem; /* 240px */
|
||||||
|
height: 37.5rem; /* 600px */
|
||||||
|
border-top-left-radius: 0.75rem; /* 12px */
|
||||||
|
border-bottom-left-radius: 0.75rem; /* 12px */
|
||||||
|
overflow: hidden;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Mobile: compact icon-only navigation */
|
||||||
|
@media (max-width: 1024px) {
|
||||||
|
.modal-container {
|
||||||
|
height: 100vh !important;
|
||||||
|
max-height: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-nav {
|
||||||
|
width: 5rem; /* 80px - wider for larger icons */
|
||||||
|
height: 100vh !important;
|
||||||
|
max-height: none !important;
|
||||||
|
border-top-left-radius: 0;
|
||||||
|
border-bottom-left-radius: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-nav-scroll {
|
||||||
|
padding: 1rem 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-nav-section {
|
||||||
|
margin-bottom: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-nav-item.mobile {
|
||||||
|
padding: 1rem;
|
||||||
|
justify-content: center;
|
||||||
|
border-radius: 0.75rem;
|
||||||
|
margin-bottom: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-content {
|
||||||
|
height: 100vh !important;
|
||||||
|
max-height: none !important;
|
||||||
|
border-radius: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-nav-scroll {
|
||||||
|
flex: 1;
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: 1rem;
|
||||||
|
padding-bottom: 2rem;
|
||||||
|
scrollbar-width: none;
|
||||||
|
-ms-overflow-style: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-nav-scroll::-webkit-scrollbar {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-nav-section {
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-nav-section-items {
|
||||||
|
margin-top: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-nav-item {
|
||||||
|
cursor: pointer;
|
||||||
|
padding: 0.5rem 0.625rem; /* 8px 10px */
|
||||||
|
border-radius: 0.5rem; /* 8px */
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
margin-bottom: 0.25rem; /* 4px */
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-content {
|
||||||
|
flex: 1;
|
||||||
|
height: 37.5rem; /* 600px */
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-content-scroll {
|
||||||
|
flex: 1;
|
||||||
|
overflow-y: auto;
|
||||||
|
scrollbar-width: none;
|
||||||
|
-ms-overflow-style: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-content-scroll::-webkit-scrollbar {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-header {
|
||||||
|
position: sticky;
|
||||||
|
top: 0;
|
||||||
|
z-index: 5;
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
padding: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-body {
|
||||||
|
padding: 2rem;
|
||||||
|
padding-top: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.confirm-modal-content {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.confirm-modal-buttons {
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
@@ -1,6 +1,12 @@
|
|||||||
import React from 'react';
|
import React, { useMemo, useState, useEffect } from 'react';
|
||||||
import { Modal, Button, Stack, Text, Code, ScrollArea, Group, Badge, Alert, Loader } from '@mantine/core';
|
import { Modal, Text, ActionIcon } from '@mantine/core';
|
||||||
import { useAppConfig } from '../../hooks/useAppConfig';
|
import { useMediaQuery } from '@mantine/hooks';
|
||||||
|
import LocalIcon from './LocalIcon';
|
||||||
|
import Overview from './config/configSections/Overview';
|
||||||
|
import { createConfigNavSections } from './config/configNavSections';
|
||||||
|
import { NavKey } from './config/types';
|
||||||
|
import './AppConfigModal.css';
|
||||||
|
import { Z_INDEX_OVER_FULLSCREEN_SURFACE } from '../../styles/zIndex';
|
||||||
|
|
||||||
interface AppConfigModalProps {
|
interface AppConfigModalProps {
|
||||||
opened: boolean;
|
opened: boolean;
|
||||||
@@ -8,131 +14,143 @@ interface AppConfigModalProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const AppConfigModal: React.FC<AppConfigModalProps> = ({ opened, onClose }) => {
|
const AppConfigModal: React.FC<AppConfigModalProps> = ({ opened, onClose }) => {
|
||||||
const { config, loading, error, refetch } = useAppConfig();
|
const [active, setActive] = useState<NavKey>('overview');
|
||||||
|
const isMobile = useMediaQuery("(max-width: 1024px)");
|
||||||
|
|
||||||
const renderConfigSection = (title: string, data: any) => {
|
useEffect(() => {
|
||||||
if (!data || typeof data !== 'object') return null;
|
const handler = (ev: Event) => {
|
||||||
|
const detail = (ev as CustomEvent).detail as { key?: NavKey } | undefined;
|
||||||
|
if (detail?.key) {
|
||||||
|
setActive(detail.key);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
window.addEventListener('appConfig:navigate', handler as EventListener);
|
||||||
|
return () => window.removeEventListener('appConfig:navigate', handler as EventListener);
|
||||||
|
}, []);
|
||||||
|
|
||||||
return (
|
const colors = useMemo(() => ({
|
||||||
<Stack gap="xs" mb="md">
|
navBg: 'var(--modal-nav-bg)',
|
||||||
<Text fw={600} size="md" c="blue">{title}</Text>
|
sectionTitle: 'var(--modal-nav-section-title)',
|
||||||
<Stack gap="xs" pl="md">
|
navItem: 'var(--modal-nav-item)',
|
||||||
{Object.entries(data).map(([key, value]) => (
|
navItemActive: 'var(--modal-nav-item-active)',
|
||||||
<Group key={key} wrap="nowrap" align="flex-start">
|
navItemActiveBg: 'var(--modal-nav-item-active-bg)',
|
||||||
<Text size="sm" w={150} style={{ flexShrink: 0 }} c="dimmed">
|
contentBg: 'var(--modal-content-bg)',
|
||||||
{key}:
|
headerBorder: 'var(--modal-header-border)',
|
||||||
</Text>
|
}), []);
|
||||||
{typeof value === 'boolean' ? (
|
|
||||||
<Badge color={value ? 'green' : 'red'} size="sm">
|
// Placeholder logout handler (not needed in open-source but keeps SaaS compatibility)
|
||||||
{value ? 'true' : 'false'}
|
const handleLogout = () => {
|
||||||
</Badge>
|
// In SaaS this would sign out, in open-source it does nothing
|
||||||
) : typeof value === 'object' ? (
|
console.log('Logout placeholder for SaaS compatibility');
|
||||||
<Code block>{JSON.stringify(value, null, 2)}</Code>
|
|
||||||
) : (
|
|
||||||
String(value) || 'null'
|
|
||||||
)}
|
|
||||||
</Group>
|
|
||||||
))}
|
|
||||||
</Stack>
|
|
||||||
</Stack>
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const basicConfig = config ? {
|
// Left navigation structure and icons
|
||||||
appName: config.appName,
|
const configNavSections = useMemo(() =>
|
||||||
appNameNavbar: config.appNameNavbar,
|
createConfigNavSections(
|
||||||
baseUrl: config.baseUrl,
|
Overview,
|
||||||
contextPath: config.contextPath,
|
handleLogout
|
||||||
serverPort: config.serverPort,
|
),
|
||||||
} : null;
|
[]
|
||||||
|
);
|
||||||
|
|
||||||
const securityConfig = config ? {
|
const activeLabel = useMemo(() => {
|
||||||
enableLogin: config.enableLogin,
|
for (const section of configNavSections) {
|
||||||
} : null;
|
const found = section.items.find(i => i.key === active);
|
||||||
|
if (found) return found.label;
|
||||||
|
}
|
||||||
|
return '';
|
||||||
|
}, [configNavSections, active]);
|
||||||
|
|
||||||
const systemConfig = config ? {
|
const activeComponent = useMemo(() => {
|
||||||
enableAlphaFunctionality: config.enableAlphaFunctionality,
|
for (const section of configNavSections) {
|
||||||
enableAnalytics: config.enableAnalytics,
|
const found = section.items.find(i => i.key === active);
|
||||||
} : null;
|
if (found) return found.component;
|
||||||
|
}
|
||||||
const premiumConfig = config ? {
|
return null;
|
||||||
premiumEnabled: config.premiumEnabled,
|
}, [configNavSections, active]);
|
||||||
premiumKey: config.premiumKey ? '***hidden***' : null,
|
|
||||||
runningProOrHigher: config.runningProOrHigher,
|
|
||||||
runningEE: config.runningEE,
|
|
||||||
license: config.license,
|
|
||||||
} : null;
|
|
||||||
|
|
||||||
const integrationConfig = config ? {
|
|
||||||
GoogleDriveEnabled: config.GoogleDriveEnabled,
|
|
||||||
SSOAutoLogin: config.SSOAutoLogin,
|
|
||||||
} : null;
|
|
||||||
|
|
||||||
const legalConfig = config ? {
|
|
||||||
termsAndConditions: config.termsAndConditions,
|
|
||||||
privacyPolicy: config.privacyPolicy,
|
|
||||||
cookiePolicy: config.cookiePolicy,
|
|
||||||
impressum: config.impressum,
|
|
||||||
accessibilityStatement: config.accessibilityStatement,
|
|
||||||
} : null;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal
|
<Modal
|
||||||
opened={opened}
|
opened={opened}
|
||||||
onClose={onClose}
|
onClose={onClose}
|
||||||
title="App Configuration (Testing)"
|
title={null}
|
||||||
size="lg"
|
size={isMobile ? "100%" : 980}
|
||||||
style={{ zIndex: 1000 }}
|
centered
|
||||||
|
radius="lg"
|
||||||
|
withCloseButton={false}
|
||||||
|
zIndex={Z_INDEX_OVER_FULLSCREEN_SURFACE}
|
||||||
|
overlayProps={{ opacity: 0.35, blur: 2 }}
|
||||||
|
padding={0}
|
||||||
|
fullScreen={isMobile}
|
||||||
>
|
>
|
||||||
<Stack>
|
<div className="modal-container">
|
||||||
<Group justify="space-between">
|
{/* Left navigation */}
|
||||||
<Text size="sm" c="dimmed">
|
<div
|
||||||
This modal shows the current application configuration for testing purposes only.
|
className={`modal-nav ${isMobile ? 'mobile' : ''}`}
|
||||||
</Text>
|
style={{
|
||||||
<Button size="xs" variant="light" onClick={refetch}>
|
background: colors.navBg,
|
||||||
Refresh
|
borderRight: `1px solid ${colors.headerBorder}`,
|
||||||
</Button>
|
}}
|
||||||
</Group>
|
>
|
||||||
|
<div className="modal-nav-scroll">
|
||||||
|
{configNavSections.map(section => (
|
||||||
|
<div key={section.title} className="modal-nav-section">
|
||||||
|
{!isMobile && (
|
||||||
|
<Text size="xs" fw={600} c={colors.sectionTitle} style={{ textTransform: 'uppercase', letterSpacing: 0.4 }}>
|
||||||
|
{section.title}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
<div className="modal-nav-section-items">
|
||||||
|
{section.items.map(item => {
|
||||||
|
const isActive = active === item.key;
|
||||||
|
const color = isActive ? colors.navItemActive : colors.navItem;
|
||||||
|
const iconSize = isMobile ? 28 : 18;
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={item.key}
|
||||||
|
onClick={() => setActive(item.key)}
|
||||||
|
className={`modal-nav-item ${isMobile ? 'mobile' : ''}`}
|
||||||
|
style={{
|
||||||
|
background: isActive ? colors.navItemActiveBg : 'transparent',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<LocalIcon icon={item.icon} width={iconSize} height={iconSize} style={{ color }} />
|
||||||
|
{!isMobile && (
|
||||||
|
<Text size="sm" fw={500} style={{ color }}>
|
||||||
|
{item.label}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
{loading && (
|
{/* Right content */}
|
||||||
<Stack align="center" py="md">
|
<div className="modal-content">
|
||||||
<Loader size="sm" />
|
<div className="modal-content-scroll">
|
||||||
<Text size="sm" c="dimmed">Loading configuration...</Text>
|
{/* Sticky header with section title and small close button */}
|
||||||
</Stack>
|
<div
|
||||||
)}
|
className="modal-header"
|
||||||
|
style={{
|
||||||
{error && (
|
background: colors.contentBg,
|
||||||
<Alert color="red" title="Error">
|
borderBottom: `1px solid ${colors.headerBorder}`,
|
||||||
{error}
|
}}
|
||||||
</Alert>
|
>
|
||||||
)}
|
<Text fw={700} size="lg">{activeLabel}</Text>
|
||||||
|
<ActionIcon variant="subtle" onClick={onClose} aria-label="Close">
|
||||||
{config && (
|
<LocalIcon icon="close-rounded" width={18} height={18} />
|
||||||
<ScrollArea h={400}>
|
</ActionIcon>
|
||||||
<Stack gap="lg">
|
</div>
|
||||||
{renderConfigSection('Basic Configuration', basicConfig)}
|
<div className="modal-body">
|
||||||
{renderConfigSection('Security Configuration', securityConfig)}
|
{activeComponent}
|
||||||
{renderConfigSection('System Configuration', systemConfig)}
|
</div>
|
||||||
{renderConfigSection('Premium/Enterprise Configuration', premiumConfig)}
|
</div>
|
||||||
{renderConfigSection('Integration Configuration', integrationConfig)}
|
</div>
|
||||||
{renderConfigSection('Legal Configuration', legalConfig)}
|
</div>
|
||||||
|
|
||||||
{config.error && (
|
|
||||||
<Alert color="yellow" title="Configuration Warning">
|
|
||||||
{config.error}
|
|
||||||
</Alert>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Stack gap="xs">
|
|
||||||
<Text fw={600} size="md" c="blue">Raw Configuration</Text>
|
|
||||||
<Code block style={{ fontSize: '11px' }}>
|
|
||||||
{JSON.stringify(config, null, 2)}
|
|
||||||
</Code>
|
|
||||||
</Stack>
|
|
||||||
</Stack>
|
|
||||||
</ScrollArea>
|
|
||||||
)}
|
|
||||||
</Stack>
|
|
||||||
</Modal>
|
</Modal>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,101 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { Box } from '@mantine/core';
|
||||||
|
|
||||||
|
interface BadgeProps {
|
||||||
|
children: React.ReactNode;
|
||||||
|
size?: 'sm' | 'md' | 'lg';
|
||||||
|
variant?: 'default' | 'colored';
|
||||||
|
color?: string;
|
||||||
|
textColor?: string;
|
||||||
|
backgroundColor?: string;
|
||||||
|
className?: string;
|
||||||
|
style?: React.CSSProperties;
|
||||||
|
}
|
||||||
|
|
||||||
|
const Badge: React.FC<BadgeProps> = ({
|
||||||
|
children,
|
||||||
|
size = 'sm',
|
||||||
|
variant = 'default',
|
||||||
|
color,
|
||||||
|
textColor,
|
||||||
|
backgroundColor,
|
||||||
|
className,
|
||||||
|
style
|
||||||
|
}) => {
|
||||||
|
const getSizeStyles = () => {
|
||||||
|
switch (size) {
|
||||||
|
case 'sm':
|
||||||
|
return {
|
||||||
|
padding: '0.125rem 0.5rem',
|
||||||
|
fontSize: '0.75rem',
|
||||||
|
fontWeight: 700,
|
||||||
|
borderRadius: '0.5rem',
|
||||||
|
};
|
||||||
|
case 'md':
|
||||||
|
return {
|
||||||
|
padding: '0.25rem 0.75rem',
|
||||||
|
fontSize: '0.875rem',
|
||||||
|
fontWeight: 700,
|
||||||
|
borderRadius: '0.625rem',
|
||||||
|
};
|
||||||
|
case 'lg':
|
||||||
|
return {
|
||||||
|
padding: '0.375rem 1rem',
|
||||||
|
fontSize: '1rem',
|
||||||
|
fontWeight: 700,
|
||||||
|
borderRadius: '0.75rem',
|
||||||
|
};
|
||||||
|
default:
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const getVariantStyles = () => {
|
||||||
|
// If explicit colors are provided, use them
|
||||||
|
if (textColor && backgroundColor) {
|
||||||
|
return {
|
||||||
|
backgroundColor,
|
||||||
|
color: textColor,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// If a single color is provided, use it for text and 20% opacity for background
|
||||||
|
if (color) {
|
||||||
|
return {
|
||||||
|
backgroundColor: `color-mix(in srgb, ${color} 20%, transparent)`,
|
||||||
|
color: color,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// If variant is colored but no color provided, use default colored styling
|
||||||
|
if (variant === 'colored') {
|
||||||
|
return {
|
||||||
|
backgroundColor: `color-mix(in srgb, var(--category-color-default) 15%, transparent)`,
|
||||||
|
color: 'var(--category-color-default)',
|
||||||
|
borderColor: `color-mix(in srgb, var(--category-color-default) 30%, transparent)`,
|
||||||
|
border: '1px solid',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Default styling
|
||||||
|
return {
|
||||||
|
background: 'var(--tool-header-badge-bg)',
|
||||||
|
color: 'var(--tool-header-badge-text)',
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Box
|
||||||
|
className={className}
|
||||||
|
style={{
|
||||||
|
...getSizeStyles(),
|
||||||
|
...getVariantStyles(),
|
||||||
|
...style,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</Box>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default Badge;
|
||||||
@@ -125,6 +125,7 @@ const FilePickerModal = ({
|
|||||||
title={t("fileUpload.selectFromStorage", "Select Files from Storage")}
|
title={t("fileUpload.selectFromStorage", "Select Files from Storage")}
|
||||||
size="lg"
|
size="lg"
|
||||||
scrollAreaComponent={ScrollArea.Autosize}
|
scrollAreaComponent={ScrollArea.Autosize}
|
||||||
|
zIndex={1100}
|
||||||
>
|
>
|
||||||
<Stack gap="md">
|
<Stack gap="md">
|
||||||
{storedFiles.length === 0 ? (
|
{storedFiles.length === 0 ? (
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ interface FileUploadButtonProps {
|
|||||||
const FileUploadButton = ({
|
const FileUploadButton = ({
|
||||||
file,
|
file,
|
||||||
onChange,
|
onChange,
|
||||||
accept = "*/*",
|
accept,
|
||||||
disabled = false,
|
disabled = false,
|
||||||
placeholder,
|
placeholder,
|
||||||
variant = "outline",
|
variant = "outline",
|
||||||
|
|||||||
@@ -41,7 +41,6 @@ const LandingPage = () => {
|
|||||||
{/* White PDF Page Background */}
|
{/* White PDF Page Background */}
|
||||||
<Dropzone
|
<Dropzone
|
||||||
onDrop={handleFileDrop}
|
onDrop={handleFileDrop}
|
||||||
accept={["application/pdf", "application/zip", "application/x-zip-compressed"]}
|
|
||||||
multiple={true}
|
multiple={true}
|
||||||
className="w-4/5 flex items-center justify-center h-[95%]"
|
className="w-4/5 flex items-center justify-center h-[95%]"
|
||||||
style={{
|
style={{
|
||||||
@@ -178,7 +177,6 @@ const LandingPage = () => {
|
|||||||
ref={fileInputRef}
|
ref={fileInputRef}
|
||||||
type="file"
|
type="file"
|
||||||
multiple
|
multiple
|
||||||
accept=".pdf,.zip"
|
|
||||||
onChange={handleFileSelect}
|
onChange={handleFileSelect}
|
||||||
style={{ display: 'none' }}
|
style={{ display: 'none' }}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { useTranslation } from 'react-i18next';
|
|||||||
import { supportedLanguages } from '../../i18n';
|
import { supportedLanguages } from '../../i18n';
|
||||||
import LocalIcon from './LocalIcon';
|
import LocalIcon from './LocalIcon';
|
||||||
import styles from './LanguageSelector.module.css';
|
import styles from './LanguageSelector.module.css';
|
||||||
|
import { Z_INDEX_OVER_FULLSCREEN_SURFACE } from '../../styles/zIndex';
|
||||||
|
|
||||||
// Types
|
// Types
|
||||||
interface LanguageSelectorProps {
|
interface LanguageSelectorProps {
|
||||||
@@ -209,6 +210,7 @@ const LanguageSelector: React.FC<LanguageSelectorProps> = ({ position = 'bottom-
|
|||||||
width={600}
|
width={600}
|
||||||
position={position}
|
position={position}
|
||||||
offset={offset}
|
offset={offset}
|
||||||
|
zIndex={Z_INDEX_OVER_FULLSCREEN_SURFACE}
|
||||||
transitionProps={{
|
transitionProps={{
|
||||||
transition: 'scale-y',
|
transition: 'scale-y',
|
||||||
duration: 200,
|
duration: 200,
|
||||||
@@ -264,13 +266,15 @@ const LanguageSelector: React.FC<LanguageSelectorProps> = ({ position = 'bottom-
|
|||||||
boxShadow: '0 4px 12px rgba(0, 0, 0, 0.1)',
|
boxShadow: '0 4px 12px rgba(0, 0, 0, 0.1)',
|
||||||
backgroundColor: 'light-dark(var(--mantine-color-white), var(--mantine-color-dark-6))',
|
backgroundColor: 'light-dark(var(--mantine-color-white), var(--mantine-color-dark-6))',
|
||||||
border: 'light-dark(1px solid var(--mantine-color-gray-3), 1px solid var(--mantine-color-dark-4))',
|
border: 'light-dark(1px solid var(--mantine-color-gray-3), 1px solid var(--mantine-color-dark-4))',
|
||||||
|
zIndex: Z_INDEX_OVER_FULLSCREEN_SURFACE,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<ScrollArea h={190} type="scroll">
|
<ScrollArea h={190} type="scroll">
|
||||||
<div className={styles.languageGrid}>
|
<div className={styles.languageGrid}>
|
||||||
{languageOptions.map((option, index) => {
|
{languageOptions.map((option, index) => {
|
||||||
const isEnglishGB = option.value === 'en-GB'; // Currently only English GB has enough translations to use
|
// Enable languages with >90% translation completion
|
||||||
const isDisabled = !isEnglishGB;
|
const enabledLanguages = ['en-GB', 'ar-AR', 'de-DE', 'es-ES', 'fr-FR', 'it-IT', 'pt-BR', 'ru-RU', 'zh-CN'];
|
||||||
|
const isDisabled = !enabledLanguages.includes(option.value);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<LanguageItem
|
<LanguageItem
|
||||||
|
|||||||
@@ -1,25 +1,19 @@
|
|||||||
import { Modal, Text, Button, Group, Stack } from '@mantine/core';
|
import { Modal, Text, Button, Group, Stack } from "@mantine/core";
|
||||||
import { useNavigationGuard } from '../../contexts/NavigationContext';
|
import { useNavigationGuard } from "../../contexts/NavigationContext";
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from "react-i18next";
|
||||||
|
import ArrowBackIcon from "@mui/icons-material/ArrowBack";
|
||||||
|
import DeleteOutlineIcon from "@mui/icons-material/DeleteOutline";
|
||||||
|
import CheckCircleOutlineIcon from "@mui/icons-material/CheckCircleOutline";
|
||||||
|
|
||||||
interface NavigationWarningModalProps {
|
interface NavigationWarningModalProps {
|
||||||
onApplyAndContinue?: () => Promise<void>;
|
onApplyAndContinue?: () => Promise<void>;
|
||||||
onExportAndContinue?: () => Promise<void>;
|
onExportAndContinue?: () => Promise<void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
const NavigationWarningModal = ({
|
const NavigationWarningModal = ({ onApplyAndContinue, onExportAndContinue }: NavigationWarningModalProps) => {
|
||||||
onApplyAndContinue,
|
|
||||||
onExportAndContinue
|
|
||||||
}: NavigationWarningModalProps) => {
|
|
||||||
|
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const {
|
const { showNavigationWarning, hasUnsavedChanges, cancelNavigation, confirmNavigation, setHasUnsavedChanges } =
|
||||||
showNavigationWarning,
|
useNavigationGuard();
|
||||||
hasUnsavedChanges,
|
|
||||||
cancelNavigation,
|
|
||||||
confirmNavigation,
|
|
||||||
setHasUnsavedChanges
|
|
||||||
} = useNavigationGuard();
|
|
||||||
|
|
||||||
const handleKeepWorking = () => {
|
const handleKeepWorking = () => {
|
||||||
cancelNavigation();
|
cancelNavigation();
|
||||||
@@ -30,7 +24,7 @@ const NavigationWarningModal = ({
|
|||||||
confirmNavigation();
|
confirmNavigation();
|
||||||
};
|
};
|
||||||
|
|
||||||
const _handleApplyAndContinue = async () => {
|
const handleApplyAndContinue = async () => {
|
||||||
if (onApplyAndContinue) {
|
if (onApplyAndContinue) {
|
||||||
await onApplyAndContinue();
|
await onApplyAndContinue();
|
||||||
}
|
}
|
||||||
@@ -38,13 +32,14 @@ const NavigationWarningModal = ({
|
|||||||
confirmNavigation();
|
confirmNavigation();
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleExportAndContinue = async () => {
|
const _handleExportAndContinue = async () => {
|
||||||
if (onExportAndContinue) {
|
if (onExportAndContinue) {
|
||||||
await onExportAndContinue();
|
await onExportAndContinue();
|
||||||
}
|
}
|
||||||
setHasUnsavedChanges(false);
|
setHasUnsavedChanges(false);
|
||||||
confirmNavigation();
|
confirmNavigation();
|
||||||
};
|
};
|
||||||
|
const BUTTON_WIDTH = "10rem";
|
||||||
|
|
||||||
if (!hasUnsavedChanges) {
|
if (!hasUnsavedChanges) {
|
||||||
return null;
|
return null;
|
||||||
@@ -56,54 +51,53 @@ const NavigationWarningModal = ({
|
|||||||
onClose={handleKeepWorking}
|
onClose={handleKeepWorking}
|
||||||
title={t("unsavedChangesTitle", "Unsaved Changes")}
|
title={t("unsavedChangesTitle", "Unsaved Changes")}
|
||||||
centered
|
centered
|
||||||
size="lg"
|
size="auto"
|
||||||
closeOnClickOutside={false}
|
closeOnClickOutside={true}
|
||||||
closeOnEscape={false}
|
closeOnEscape={true}
|
||||||
>
|
>
|
||||||
<Stack gap="md">
|
<Stack>
|
||||||
<Text>
|
<Stack ta="center" p="md">
|
||||||
{t("unsavedChanges", "You have unsaved changes to your PDF. What would you like to do?")}
|
<Text size="md" fw="300">
|
||||||
|
{t("unsavedChanges", "You have unsaved changes to your PDF.")}
|
||||||
</Text>
|
</Text>
|
||||||
|
<Text size="lg" fw="500" >
|
||||||
|
{t("areYouSure", "Are you sure you want to leave?")}
|
||||||
|
</Text>
|
||||||
|
</Stack>
|
||||||
|
|
||||||
|
{/* Desktop layout: 2 groups side by side */}
|
||||||
<Group justify="space-between" gap="sm">
|
<Group justify="space-between" gap="xl" visibleFrom="md">
|
||||||
<Button
|
|
||||||
variant="light"
|
|
||||||
color="red"
|
|
||||||
onClick={handleDiscardChanges}
|
|
||||||
>
|
|
||||||
{t("discardChanges", "Discard Changes")}
|
|
||||||
</Button>
|
|
||||||
|
|
||||||
<Group gap="sm">
|
<Group gap="sm">
|
||||||
<Button
|
<Button variant="light" color="var(--mantine-color-gray-8)" onClick={handleKeepWorking} w={BUTTON_WIDTH} leftSection={<ArrowBackIcon fontSize="small" />}>
|
||||||
variant="light"
|
|
||||||
color="var(--mantine-color-gray-8)"
|
|
||||||
onClick={handleKeepWorking}
|
|
||||||
>
|
|
||||||
{t("keepWorking", "Keep Working")}
|
{t("keepWorking", "Keep Working")}
|
||||||
</Button>
|
</Button>
|
||||||
|
</Group>
|
||||||
{/* TODO:: Add this back in when it works */}
|
<Group gap="sm">
|
||||||
{/* {onApplyAndContinue && (
|
<Button variant="filled" color="var(--mantine-color-red-9)" onClick={handleDiscardChanges} w={BUTTON_WIDTH} leftSection={<DeleteOutlineIcon fontSize="small" />}>
|
||||||
<Button
|
{t("discardChanges", "Discard Changes")}
|
||||||
variant="light"
|
</Button>
|
||||||
color="blue"
|
{onApplyAndContinue && (
|
||||||
onClick={handleApplyAndContinue}
|
<Button variant="filled" onClick={handleApplyAndContinue} w={BUTTON_WIDTH} leftSection={<CheckCircleOutlineIcon fontSize="small" />}>
|
||||||
>
|
{t("applyAndContinue", "Apply & Leave")}
|
||||||
{t("applyAndContinue", "Apply & Continue")}
|
|
||||||
</Button>
|
|
||||||
)} */}
|
|
||||||
|
|
||||||
{onExportAndContinue && (
|
|
||||||
<Button
|
|
||||||
onClick={handleExportAndContinue}
|
|
||||||
>
|
|
||||||
{t("exportAndContinue", "Export & Continue")}
|
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</Group>
|
</Group>
|
||||||
</Group>
|
</Group>
|
||||||
|
|
||||||
|
{/* Mobile layout: centered stack of 4 buttons */}
|
||||||
|
<Stack align="center" gap="sm" hiddenFrom="md">
|
||||||
|
<Button variant="light" color="var(--mantine-color-gray-8)" onClick={handleKeepWorking} w={BUTTON_WIDTH} leftSection={<ArrowBackIcon fontSize="small" />}>
|
||||||
|
{t("keepWorking", "Keep Working")}
|
||||||
|
</Button>
|
||||||
|
<Button variant="filled" color="var(--mantine-color-red-9)" onClick={handleDiscardChanges} w={BUTTON_WIDTH} leftSection={<DeleteOutlineIcon fontSize="small" />}>
|
||||||
|
{t("discardChanges", "Discard Changes")}
|
||||||
|
</Button>
|
||||||
|
{onApplyAndContinue && (
|
||||||
|
<Button variant="filled" onClick={handleApplyAndContinue} w={BUTTON_WIDTH} leftSection={<CheckCircleOutlineIcon fontSize="small" />}>
|
||||||
|
{t("applyAndContinue", "Apply & Leave")}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</Stack>
|
||||||
</Stack>
|
</Stack>
|
||||||
</Modal>
|
</Modal>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ import { ButtonConfig } from '../../types/sidebar';
|
|||||||
import './quickAccessBar/QuickAccessBar.css';
|
import './quickAccessBar/QuickAccessBar.css';
|
||||||
import AllToolsNavButton from './AllToolsNavButton';
|
import AllToolsNavButton from './AllToolsNavButton';
|
||||||
import ActiveToolButton from "./quickAccessBar/ActiveToolButton";
|
import ActiveToolButton from "./quickAccessBar/ActiveToolButton";
|
||||||
|
import AppConfigModal from './AppConfigModal';
|
||||||
|
import { useAppConfig } from '../../hooks/useAppConfig';
|
||||||
import {
|
import {
|
||||||
isNavButtonActive,
|
isNavButtonActive,
|
||||||
getNavButtonStyle,
|
getNavButtonStyle,
|
||||||
@@ -22,8 +24,9 @@ const QuickAccessBar = forwardRef<HTMLDivElement>((_, ref) => {
|
|||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const { isRainbowMode } = useRainbowThemeContext();
|
const { isRainbowMode } = useRainbowThemeContext();
|
||||||
const { openFilesModal, isFilesModalOpen } = useFilesModalContext();
|
const { openFilesModal, isFilesModalOpen } = useFilesModalContext();
|
||||||
const { handleReaderToggle, handleBackToTools, handleToolSelect, selectedToolKey, leftPanelView, toolRegistry, readerMode, resetTool } = useToolWorkflow();
|
const { handleReaderToggle, handleToolSelect, selectedToolKey, leftPanelView, toolRegistry, readerMode, resetTool } = useToolWorkflow();
|
||||||
const { getToolNavigation } = useSidebarNavigation();
|
const { getToolNavigation } = useSidebarNavigation();
|
||||||
|
const { config } = useAppConfig();
|
||||||
const [configModalOpen, setConfigModalOpen] = useState(false);
|
const [configModalOpen, setConfigModalOpen] = useState(false);
|
||||||
const [activeButton, setActiveButton] = useState<string>('tools');
|
const [activeButton, setActiveButton] = useState<string>('tools');
|
||||||
const scrollableRef = useRef<HTMLDivElement>(null);
|
const scrollableRef = useRef<HTMLDivElement>(null);
|
||||||
@@ -65,7 +68,8 @@ const QuickAccessBar = forwardRef<HTMLDivElement>((_, ref) => {
|
|||||||
onClick: (e: React.MouseEvent) => handleClick(e),
|
onClick: (e: React.MouseEvent) => handleClick(e),
|
||||||
'aria-label': config.name
|
'aria-label': config.name
|
||||||
} : {
|
} : {
|
||||||
onClick: () => handleClick()
|
onClick: () => handleClick(),
|
||||||
|
'aria-label': config.name
|
||||||
})}
|
})}
|
||||||
size={isActive ? (config.size || 'lg') : 'lg'}
|
size={isActive ? (config.size || 'lg') : 'lg'}
|
||||||
variant="subtle"
|
variant="subtle"
|
||||||
@@ -95,12 +99,10 @@ const QuickAccessBar = forwardRef<HTMLDivElement>((_, ref) => {
|
|||||||
type: 'navigation',
|
type: 'navigation',
|
||||||
onClick: () => {
|
onClick: () => {
|
||||||
setActiveButton('read');
|
setActiveButton('read');
|
||||||
handleBackToTools();
|
|
||||||
handleReaderToggle();
|
handleReaderToggle();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
// TODO: Add sign
|
// {
|
||||||
//{
|
|
||||||
// id: 'sign',
|
// id: 'sign',
|
||||||
// name: t("quickAccess.sign", "Sign"),
|
// name: t("quickAccess.sign", "Sign"),
|
||||||
// icon: <LocalIcon icon="signature-rounded" width="1.25rem" height="1.25rem" />,
|
// icon: <LocalIcon icon="signature-rounded" width="1.25rem" height="1.25rem" />,
|
||||||
@@ -111,7 +113,7 @@ const QuickAccessBar = forwardRef<HTMLDivElement>((_, ref) => {
|
|||||||
// setActiveButton('sign');
|
// setActiveButton('sign');
|
||||||
// handleToolSelect('sign');
|
// handleToolSelect('sign');
|
||||||
// }
|
// }
|
||||||
//},
|
// },
|
||||||
{
|
{
|
||||||
id: 'automate',
|
id: 'automate',
|
||||||
name: t("quickAccess.automate", "Automate"),
|
name: t("quickAccess.automate", "Automate"),
|
||||||
@@ -150,8 +152,8 @@ const QuickAccessBar = forwardRef<HTMLDivElement>((_, ref) => {
|
|||||||
//},
|
//},
|
||||||
{
|
{
|
||||||
id: 'config',
|
id: 'config',
|
||||||
name: t("quickAccess.config", "Config"),
|
name: config?.enableLogin ? t("quickAccess.account", "Account") : t("quickAccess.config", "Config"),
|
||||||
icon: <LocalIcon icon="settings-rounded" width="1.25rem" height="1.25rem" />,
|
icon: config?.enableLogin ? <LocalIcon icon="person-rounded" width="1.25rem" height="1.25rem" /> : <LocalIcon icon="settings-rounded" width="1.25rem" height="1.25rem" />,
|
||||||
size: 'lg',
|
size: 'lg',
|
||||||
type: 'modal',
|
type: 'modal',
|
||||||
onClick: () => {
|
onClick: () => {
|
||||||
@@ -217,7 +219,7 @@ const QuickAccessBar = forwardRef<HTMLDivElement>((_, ref) => {
|
|||||||
<div className="spacer" />
|
<div className="spacer" />
|
||||||
|
|
||||||
{/* Config button at the bottom */}
|
{/* Config button at the bottom */}
|
||||||
{/* {buttonConfigs
|
{buttonConfigs
|
||||||
.filter(config => config.id === 'config')
|
.filter(config => config.id === 'config')
|
||||||
.map(config => (
|
.map(config => (
|
||||||
<div key={config.id} className="flex flex-col items-center gap-1">
|
<div key={config.id} className="flex flex-col items-center gap-1">
|
||||||
@@ -227,6 +229,7 @@ const QuickAccessBar = forwardRef<HTMLDivElement>((_, ref) => {
|
|||||||
onClick={config.onClick}
|
onClick={config.onClick}
|
||||||
style={getNavButtonStyle(config, activeButton, isFilesModalOpen, configModalOpen, selectedToolKey, leftPanelView)}
|
style={getNavButtonStyle(config, activeButton, isFilesModalOpen, configModalOpen, selectedToolKey, leftPanelView)}
|
||||||
className={isNavButtonActive(config, activeButton, isFilesModalOpen, configModalOpen, selectedToolKey, leftPanelView) ? 'activeIconScale' : ''}
|
className={isNavButtonActive(config, activeButton, isFilesModalOpen, configModalOpen, selectedToolKey, leftPanelView) ? 'activeIconScale' : ''}
|
||||||
|
aria-label={config.name}
|
||||||
data-testid={`${config.id}-button`}
|
data-testid={`${config.id}-button`}
|
||||||
>
|
>
|
||||||
<span className="iconContainer">
|
<span className="iconContainer">
|
||||||
@@ -237,14 +240,14 @@ const QuickAccessBar = forwardRef<HTMLDivElement>((_, ref) => {
|
|||||||
{config.name}
|
{config.name}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
))} */}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* <AppConfigModal
|
<AppConfigModal
|
||||||
opened={configModalOpen}
|
opened={configModalOpen}
|
||||||
onClose={() => setConfigModalOpen(false)}
|
onClose={() => setConfigModalOpen(false)}
|
||||||
/> */}
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -15,22 +15,28 @@ import BulkSelectionPanel from '../pageEditor/BulkSelectionPanel';
|
|||||||
import { SearchInterface } from '../viewer/SearchInterface';
|
import { SearchInterface } from '../viewer/SearchInterface';
|
||||||
import { ViewerContext } from '../../contexts/ViewerContext';
|
import { ViewerContext } from '../../contexts/ViewerContext';
|
||||||
import { useSignature } from '../../contexts/SignatureContext';
|
import { useSignature } from '../../contexts/SignatureContext';
|
||||||
|
import ViewerAnnotationControls from './rightRail/ViewerAnnotationControls';
|
||||||
|
|
||||||
import { parseSelection } from '../../utils/bulkselection/parseSelection';
|
import { parseSelection } from '../../utils/bulkselection/parseSelection';
|
||||||
|
|
||||||
|
|
||||||
|
import { useSidebarContext } from '../../contexts/SidebarContext';
|
||||||
|
|
||||||
export default function RightRail() {
|
export default function RightRail() {
|
||||||
|
const { sidebarRefs } = useSidebarContext();
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const [isPanning, setIsPanning] = useState(false);
|
const [isPanning, setIsPanning] = useState(false);
|
||||||
|
|
||||||
// Viewer context for PDF controls - safely handle when not available
|
// Viewer context for PDF controls - safely handle when not available
|
||||||
const viewerContext = React.useContext(ViewerContext);
|
const viewerContext = React.useContext(ViewerContext);
|
||||||
const { toggleTheme } = useRainbowThemeContext();
|
const { toggleTheme } = useRainbowThemeContext();
|
||||||
const { buttons, actions } = useRightRail();
|
const { buttons, actions, allButtonsDisabled } = useRightRail();
|
||||||
|
|
||||||
const topButtons = useMemo(() => buttons.filter(b => (b.section || 'top') === 'top' && (b.visible ?? true)), [buttons]);
|
const topButtons = useMemo(() => buttons.filter(b => (b.section || 'top') === 'top' && (b.visible ?? true)), [buttons]);
|
||||||
|
|
||||||
// Access PageEditor functions for page-editor-specific actions
|
// Access PageEditor functions for page-editor-specific actions
|
||||||
const { pageEditorFunctions } = useToolWorkflow();
|
const { pageEditorFunctions, toolPanelMode, leftPanelView } = useToolWorkflow();
|
||||||
|
const disableForFullscreen = toolPanelMode === 'fullscreen' && leftPanelView === 'toolPicker';
|
||||||
|
|
||||||
// CSV input state for page selection
|
// CSV input state for page selection
|
||||||
const [csvInput, setCsvInput] = useState<string>("");
|
const [csvInput, setCsvInput] = useState<string>("");
|
||||||
@@ -175,19 +181,19 @@ export default function RightRail() {
|
|||||||
}, [currentView]);
|
}, [currentView]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="right-rail">
|
<div ref={sidebarRefs.rightRailRef} className={`right-rail`} data-sidebar="right-rail">
|
||||||
<div className="right-rail-inner">
|
<div className="right-rail-inner">
|
||||||
{topButtons.length > 0 && (
|
{topButtons.length > 0 && (
|
||||||
<>
|
<>
|
||||||
<div className="right-rail-section">
|
<div className="right-rail-section">
|
||||||
{topButtons.map(btn => (
|
{topButtons.map(btn => (
|
||||||
<Tooltip key={btn.id} content={btn.tooltip} position="left" offset={12} arrow>
|
<Tooltip key={btn.id} content={btn.tooltip} position="left" offset={12} arrow portalTarget={document.body}>
|
||||||
<ActionIcon
|
<ActionIcon
|
||||||
variant="subtle"
|
variant="subtle"
|
||||||
radius="md"
|
radius="md"
|
||||||
className="right-rail-icon"
|
className="right-rail-icon"
|
||||||
onClick={() => actions[btn.id]?.()}
|
onClick={() => actions[btn.id]?.()}
|
||||||
disabled={btn.disabled}
|
disabled={btn.disabled || allButtonsDisabled || disableForFullscreen}
|
||||||
>
|
>
|
||||||
{btn.icon}
|
{btn.icon}
|
||||||
</ActionIcon>
|
</ActionIcon>
|
||||||
@@ -205,7 +211,7 @@ export default function RightRail() {
|
|||||||
>
|
>
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '1rem' }}>
|
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '1rem' }}>
|
||||||
{/* Search */}
|
{/* Search */}
|
||||||
<Tooltip content={t('rightRail.search', 'Search PDF')} position="left" offset={12} arrow>
|
<Tooltip content={t('rightRail.search', 'Search PDF')} position="left" offset={12} arrow portalTarget={document.body}>
|
||||||
<Popover position="left" withArrow shadow="md" offset={8}>
|
<Popover position="left" withArrow shadow="md" offset={8}>
|
||||||
<Popover.Target>
|
<Popover.Target>
|
||||||
<div style={{ display: 'inline-flex' }}>
|
<div style={{ display: 'inline-flex' }}>
|
||||||
@@ -213,7 +219,7 @@ export default function RightRail() {
|
|||||||
variant="subtle"
|
variant="subtle"
|
||||||
radius="md"
|
radius="md"
|
||||||
className="right-rail-icon"
|
className="right-rail-icon"
|
||||||
disabled={currentView !== 'viewer'}
|
disabled={currentView !== 'viewer' || allButtonsDisabled || disableForFullscreen}
|
||||||
aria-label={typeof t === 'function' ? t('rightRail.search', 'Search PDF') : 'Search PDF'}
|
aria-label={typeof t === 'function' ? t('rightRail.search', 'Search PDF') : 'Search PDF'}
|
||||||
>
|
>
|
||||||
<LocalIcon icon="search" width="1.5rem" height="1.5rem" />
|
<LocalIcon icon="search" width="1.5rem" height="1.5rem" />
|
||||||
@@ -233,7 +239,7 @@ export default function RightRail() {
|
|||||||
|
|
||||||
|
|
||||||
{/* Pan Mode */}
|
{/* Pan Mode */}
|
||||||
<Tooltip content={t('rightRail.panMode', 'Pan Mode')} position="left" offset={12} arrow>
|
<Tooltip content={t('rightRail.panMode', 'Pan Mode')} position="left" offset={12} arrow portalTarget={document.body}>
|
||||||
<ActionIcon
|
<ActionIcon
|
||||||
variant={isPanning ? "filled" : "subtle"}
|
variant={isPanning ? "filled" : "subtle"}
|
||||||
color={isPanning ? "blue" : undefined}
|
color={isPanning ? "blue" : undefined}
|
||||||
@@ -243,14 +249,14 @@ export default function RightRail() {
|
|||||||
viewerContext?.panActions.togglePan();
|
viewerContext?.panActions.togglePan();
|
||||||
setIsPanning(!isPanning);
|
setIsPanning(!isPanning);
|
||||||
}}
|
}}
|
||||||
disabled={currentView !== 'viewer'}
|
disabled={currentView !== 'viewer' || allButtonsDisabled || disableForFullscreen}
|
||||||
>
|
>
|
||||||
<LocalIcon icon="pan-tool-rounded" width="1.5rem" height="1.5rem" />
|
<LocalIcon icon="pan-tool-rounded" width="1.5rem" height="1.5rem" />
|
||||||
</ActionIcon>
|
</ActionIcon>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
|
|
||||||
{/* Rotate Left */}
|
{/* Rotate Left */}
|
||||||
<Tooltip content={t('rightRail.rotateLeft', 'Rotate Left')} position="left" offset={12} arrow>
|
<Tooltip content={t('rightRail.rotateLeft', 'Rotate Left')} position="left" offset={12} arrow portalTarget={document.body}>
|
||||||
<ActionIcon
|
<ActionIcon
|
||||||
variant="subtle"
|
variant="subtle"
|
||||||
radius="md"
|
radius="md"
|
||||||
@@ -258,14 +264,14 @@ export default function RightRail() {
|
|||||||
onClick={() => {
|
onClick={() => {
|
||||||
viewerContext?.rotationActions.rotateBackward();
|
viewerContext?.rotationActions.rotateBackward();
|
||||||
}}
|
}}
|
||||||
disabled={currentView !== 'viewer'}
|
disabled={currentView !== 'viewer' || allButtonsDisabled || disableForFullscreen}
|
||||||
>
|
>
|
||||||
<LocalIcon icon="rotate-left" width="1.5rem" height="1.5rem" />
|
<LocalIcon icon="rotate-left" width="1.5rem" height="1.5rem" />
|
||||||
</ActionIcon>
|
</ActionIcon>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
|
|
||||||
{/* Rotate Right */}
|
{/* Rotate Right */}
|
||||||
<Tooltip content={t('rightRail.rotateRight', 'Rotate Right')} position="left" offset={12} arrow>
|
<Tooltip content={t('rightRail.rotateRight', 'Rotate Right')} position="left" offset={12} arrow portalTarget={document.body}>
|
||||||
<ActionIcon
|
<ActionIcon
|
||||||
variant="subtle"
|
variant="subtle"
|
||||||
radius="md"
|
radius="md"
|
||||||
@@ -273,14 +279,14 @@ export default function RightRail() {
|
|||||||
onClick={() => {
|
onClick={() => {
|
||||||
viewerContext?.rotationActions.rotateForward();
|
viewerContext?.rotationActions.rotateForward();
|
||||||
}}
|
}}
|
||||||
disabled={currentView !== 'viewer'}
|
disabled={currentView !== 'viewer' || allButtonsDisabled || disableForFullscreen}
|
||||||
>
|
>
|
||||||
<LocalIcon icon="rotate-right" width="1.5rem" height="1.5rem" />
|
<LocalIcon icon="rotate-right" width="1.5rem" height="1.5rem" />
|
||||||
</ActionIcon>
|
</ActionIcon>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
|
|
||||||
{/* Sidebar Toggle */}
|
{/* Sidebar Toggle */}
|
||||||
<Tooltip content={t('rightRail.toggleSidebar', 'Toggle Sidebar')} position="left" offset={12} arrow>
|
<Tooltip content={t('rightRail.toggleSidebar', 'Toggle Sidebar')} position="left" offset={12} arrow portalTarget={document.body}>
|
||||||
<ActionIcon
|
<ActionIcon
|
||||||
variant="subtle"
|
variant="subtle"
|
||||||
radius="md"
|
radius="md"
|
||||||
@@ -288,11 +294,17 @@ export default function RightRail() {
|
|||||||
onClick={() => {
|
onClick={() => {
|
||||||
viewerContext?.toggleThumbnailSidebar();
|
viewerContext?.toggleThumbnailSidebar();
|
||||||
}}
|
}}
|
||||||
disabled={currentView !== 'viewer'}
|
disabled={currentView !== 'viewer' || allButtonsDisabled || disableForFullscreen}
|
||||||
>
|
>
|
||||||
<LocalIcon icon="view-list" width="1.5rem" height="1.5rem" />
|
<LocalIcon icon="view-list" width="1.5rem" height="1.5rem" />
|
||||||
</ActionIcon>
|
</ActionIcon>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
|
|
||||||
|
{/* Annotation Controls */}
|
||||||
|
<ViewerAnnotationControls
|
||||||
|
currentView={currentView}
|
||||||
|
disabled={currentView !== 'viewer' || allButtonsDisabled || disableForFullscreen}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<Divider className="right-rail-divider" />
|
<Divider className="right-rail-divider" />
|
||||||
</div>
|
</div>
|
||||||
@@ -304,14 +316,14 @@ export default function RightRail() {
|
|||||||
>
|
>
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '1rem' }}>
|
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '1rem' }}>
|
||||||
{/* Select All Button */}
|
{/* Select All Button */}
|
||||||
<Tooltip content={t('rightRail.selectAll', 'Select All')} position="left" offset={12} arrow>
|
<Tooltip content={t('rightRail.selectAll', 'Select All')} position="left" offset={12} arrow portalTarget={document.body}>
|
||||||
<div>
|
<div>
|
||||||
<ActionIcon
|
<ActionIcon
|
||||||
variant="subtle"
|
variant="subtle"
|
||||||
radius="md"
|
radius="md"
|
||||||
className="right-rail-icon"
|
className="right-rail-icon"
|
||||||
onClick={handleSelectAll}
|
onClick={handleSelectAll}
|
||||||
disabled={currentView === 'viewer' || totalItems === 0 || selectedCount === totalItems}
|
disabled={currentView === 'viewer' || totalItems === 0 || selectedCount === totalItems || allButtonsDisabled || disableForFullscreen}
|
||||||
>
|
>
|
||||||
<LocalIcon icon="select-all" width="1.5rem" height="1.5rem" />
|
<LocalIcon icon="select-all" width="1.5rem" height="1.5rem" />
|
||||||
</ActionIcon>
|
</ActionIcon>
|
||||||
@@ -319,14 +331,14 @@ export default function RightRail() {
|
|||||||
</Tooltip>
|
</Tooltip>
|
||||||
|
|
||||||
{/* Deselect All Button */}
|
{/* Deselect All Button */}
|
||||||
<Tooltip content={t('rightRail.deselectAll', 'Deselect All')} position="left" offset={12} arrow>
|
<Tooltip content={t('rightRail.deselectAll', 'Deselect All')} position="left" offset={12} arrow portalTarget={document.body}>
|
||||||
<div>
|
<div>
|
||||||
<ActionIcon
|
<ActionIcon
|
||||||
variant="subtle"
|
variant="subtle"
|
||||||
radius="md"
|
radius="md"
|
||||||
className="right-rail-icon"
|
className="right-rail-icon"
|
||||||
onClick={handleDeselectAll}
|
onClick={handleDeselectAll}
|
||||||
disabled={currentView === 'viewer' || selectedCount === 0}
|
disabled={currentView === 'viewer' || selectedCount === 0 || allButtonsDisabled || disableForFullscreen}
|
||||||
>
|
>
|
||||||
<LocalIcon icon="crop-square-outline" width="1.5rem" height="1.5rem" />
|
<LocalIcon icon="crop-square-outline" width="1.5rem" height="1.5rem" />
|
||||||
</ActionIcon>
|
</ActionIcon>
|
||||||
@@ -335,7 +347,7 @@ export default function RightRail() {
|
|||||||
|
|
||||||
{/* Select by Numbers - page editor only, with animated presence */}
|
{/* Select by Numbers - page editor only, with animated presence */}
|
||||||
{pageControlsMounted && (
|
{pageControlsMounted && (
|
||||||
<Tooltip content={t('rightRail.selectByNumber', 'Select by Page Numbers')} position="left" offset={12} arrow>
|
<Tooltip content={t('rightRail.selectByNumber', 'Select by Page Numbers')} position="left" offset={12} arrow portalTarget={document.body}>
|
||||||
|
|
||||||
<div className={`right-rail-fade ${pageControlsVisible ? 'enter' : 'exit'}`} aria-hidden={!pageControlsVisible}>
|
<div className={`right-rail-fade ${pageControlsVisible ? 'enter' : 'exit'}`} aria-hidden={!pageControlsVisible}>
|
||||||
<Popover position="left" withArrow shadow="md" offset={8}>
|
<Popover position="left" withArrow shadow="md" offset={8}>
|
||||||
@@ -345,7 +357,7 @@ export default function RightRail() {
|
|||||||
variant="subtle"
|
variant="subtle"
|
||||||
radius="md"
|
radius="md"
|
||||||
className="right-rail-icon"
|
className="right-rail-icon"
|
||||||
disabled={!pageControlsVisible || totalItems === 0}
|
disabled={!pageControlsVisible || totalItems === 0 || allButtonsDisabled || disableForFullscreen}
|
||||||
aria-label={typeof t === 'function' ? t('rightRail.selectByNumber', 'Select by Page Numbers') : 'Select by Page Numbers'}
|
aria-label={typeof t === 'function' ? t('rightRail.selectByNumber', 'Select by Page Numbers') : 'Select by Page Numbers'}
|
||||||
>
|
>
|
||||||
<LocalIcon icon="pin-end" width="1.5rem" height="1.5rem" />
|
<LocalIcon icon="pin-end" width="1.5rem" height="1.5rem" />
|
||||||
@@ -372,7 +384,7 @@ export default function RightRail() {
|
|||||||
|
|
||||||
{/* Delete Selected Pages - page editor only, with animated presence */}
|
{/* Delete Selected Pages - page editor only, with animated presence */}
|
||||||
{pageControlsMounted && (
|
{pageControlsMounted && (
|
||||||
<Tooltip content={t('rightRail.deleteSelected', 'Delete Selected Pages')} position="left" offset={12} arrow>
|
<Tooltip content={t('rightRail.deleteSelected', 'Delete Selected Pages')} position="left" offset={12} arrow portalTarget={document.body}>
|
||||||
|
|
||||||
<div className={`right-rail-fade ${pageControlsVisible ? 'enter' : 'exit'}`} aria-hidden={!pageControlsVisible}>
|
<div className={`right-rail-fade ${pageControlsVisible ? 'enter' : 'exit'}`} aria-hidden={!pageControlsVisible}>
|
||||||
<div style={{ display: 'inline-flex' }}>
|
<div style={{ display: 'inline-flex' }}>
|
||||||
@@ -381,7 +393,7 @@ export default function RightRail() {
|
|||||||
radius="md"
|
radius="md"
|
||||||
className="right-rail-icon"
|
className="right-rail-icon"
|
||||||
onClick={() => { pageEditorFunctions?.handleDelete?.(); }}
|
onClick={() => { pageEditorFunctions?.handleDelete?.(); }}
|
||||||
disabled={!pageControlsVisible || (pageEditorFunctions?.selectedPageIds?.length || 0) === 0}
|
disabled={!pageControlsVisible || (pageEditorFunctions?.selectedPageIds?.length || 0) === 0 || allButtonsDisabled || disableForFullscreen}
|
||||||
aria-label={typeof t === 'function' ? t('rightRail.deleteSelected', 'Delete Selected Pages') : 'Delete Selected Pages'}
|
aria-label={typeof t === 'function' ? t('rightRail.deleteSelected', 'Delete Selected Pages') : 'Delete Selected Pages'}
|
||||||
>
|
>
|
||||||
<LocalIcon icon="delete-outline-rounded" width="1.5rem" height="1.5rem" />
|
<LocalIcon icon="delete-outline-rounded" width="1.5rem" height="1.5rem" />
|
||||||
@@ -394,7 +406,7 @@ export default function RightRail() {
|
|||||||
|
|
||||||
{/* Export Selected Pages - page editor only */}
|
{/* Export Selected Pages - page editor only */}
|
||||||
{pageControlsMounted && (
|
{pageControlsMounted && (
|
||||||
<Tooltip content={t('rightRail.exportSelected', 'Export Selected Pages')} position="left" offset={12} arrow>
|
<Tooltip content={t('rightRail.exportSelected', 'Export Selected Pages')} position="left" offset={12} arrow portalTarget={document.body}>
|
||||||
<div className={`right-rail-fade ${pageControlsVisible ? 'enter' : 'exit'}`} aria-hidden={!pageControlsVisible}>
|
<div className={`right-rail-fade ${pageControlsVisible ? 'enter' : 'exit'}`} aria-hidden={!pageControlsVisible}>
|
||||||
<div style={{ display: 'inline-flex' }}>
|
<div style={{ display: 'inline-flex' }}>
|
||||||
<ActionIcon
|
<ActionIcon
|
||||||
@@ -402,7 +414,7 @@ export default function RightRail() {
|
|||||||
radius="md"
|
radius="md"
|
||||||
className="right-rail-icon"
|
className="right-rail-icon"
|
||||||
onClick={() => { pageEditorFunctions?.onExportSelected?.(); }}
|
onClick={() => { pageEditorFunctions?.onExportSelected?.(); }}
|
||||||
disabled={!pageControlsVisible || (pageEditorFunctions?.selectedPageIds?.length || 0) === 0 || pageEditorFunctions?.exportLoading}
|
disabled={!pageControlsVisible || (pageEditorFunctions?.selectedPageIds?.length || 0) === 0 || pageEditorFunctions?.exportLoading || allButtonsDisabled || disableForFullscreen}
|
||||||
aria-label={typeof t === 'function' ? t('rightRail.exportSelected', 'Export Selected Pages') : 'Export Selected Pages'}
|
aria-label={typeof t === 'function' ? t('rightRail.exportSelected', 'Export Selected Pages') : 'Export Selected Pages'}
|
||||||
>
|
>
|
||||||
<LocalIcon icon="download" width="1.5rem" height="1.5rem" />
|
<LocalIcon icon="download" width="1.5rem" height="1.5rem" />
|
||||||
@@ -413,7 +425,7 @@ export default function RightRail() {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Close (File Editor: Close Selected | Page Editor: Close PDF) */}
|
{/* Close (File Editor: Close Selected | Page Editor: Close PDF) */}
|
||||||
<Tooltip content={currentView === 'pageEditor' ? t('rightRail.closePdf', 'Close PDF') : t('rightRail.closeSelected', 'Close Selected Files')} position="left" offset={12} arrow>
|
<Tooltip content={currentView === 'pageEditor' ? t('rightRail.closePdf', 'Close PDF') : t('rightRail.closeSelected', 'Close Selected Files')} position="left" offset={12} arrow portalTarget={document.body}>
|
||||||
<div>
|
<div>
|
||||||
<ActionIcon
|
<ActionIcon
|
||||||
variant="subtle"
|
variant="subtle"
|
||||||
@@ -423,7 +435,8 @@ export default function RightRail() {
|
|||||||
disabled={
|
disabled={
|
||||||
currentView === 'viewer' ||
|
currentView === 'viewer' ||
|
||||||
(currentView === 'fileEditor' && selectedCount === 0) ||
|
(currentView === 'fileEditor' && selectedCount === 0) ||
|
||||||
(currentView === 'pageEditor' && (activeFiles.length === 0 || !pageEditorFunctions?.closePdf))
|
(currentView === 'pageEditor' && (activeFiles.length === 0 || !pageEditorFunctions?.closePdf)) ||
|
||||||
|
allButtonsDisabled || disableForFullscreen
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
<LocalIcon icon="close-rounded" width="1.5rem" height="1.5rem" />
|
<LocalIcon icon="close-rounded" width="1.5rem" height="1.5rem" />
|
||||||
@@ -437,7 +450,8 @@ export default function RightRail() {
|
|||||||
|
|
||||||
{/* Theme toggle and Language dropdown */}
|
{/* Theme toggle and Language dropdown */}
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '1rem' }}>
|
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '1rem' }}>
|
||||||
<Tooltip content={t('rightRail.toggleTheme', 'Toggle Theme')} position="left" offset={12} arrow>
|
<Tooltip content={t('rightRail.toggleTheme', 'Toggle Theme')} position="left" offset={12} arrow portalTarget={document.body}
|
||||||
|
>
|
||||||
<ActionIcon
|
<ActionIcon
|
||||||
variant="subtle"
|
variant="subtle"
|
||||||
radius="md"
|
radius="md"
|
||||||
@@ -448,13 +462,17 @@ export default function RightRail() {
|
|||||||
</ActionIcon>
|
</ActionIcon>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
|
|
||||||
<LanguageSelector position="left-start" offset={6} compact />
|
<Tooltip content={t('rightRail.language', 'Language')} position="left" offset={12} arrow portalTarget={document.body}>
|
||||||
|
<div style={{ display: 'inline-flex' }}>
|
||||||
|
<LanguageSelector position="left-start" offset={6} compact />
|
||||||
|
</div>
|
||||||
|
</Tooltip>
|
||||||
|
|
||||||
<Tooltip content={
|
<Tooltip content={
|
||||||
currentView === 'pageEditor'
|
currentView === 'pageEditor'
|
||||||
? t('rightRail.exportAll', 'Export PDF')
|
? t('rightRail.exportAll', 'Export PDF')
|
||||||
: (selectedCount > 0 ? t('rightRail.downloadSelected', 'Download Selected Files') : t('rightRail.downloadAll', 'Download All'))
|
: (selectedCount > 0 ? t('rightRail.downloadSelected', 'Download Selected Files') : t('rightRail.downloadAll', 'Download All'))
|
||||||
} position="left" offset={12} arrow>
|
} position="left" offset={12} arrow portalTarget={document.body}>
|
||||||
<div>
|
<div>
|
||||||
<ActionIcon
|
<ActionIcon
|
||||||
variant="subtle"
|
variant="subtle"
|
||||||
@@ -462,7 +480,7 @@ export default function RightRail() {
|
|||||||
className="right-rail-icon"
|
className="right-rail-icon"
|
||||||
onClick={handleExportAll}
|
onClick={handleExportAll}
|
||||||
disabled={
|
disabled={
|
||||||
currentView === 'viewer' ? !exportState?.canExport : totalItems === 0
|
disableForFullscreen || (currentView === 'viewer' ? !exportState?.canExport : totalItems === 0 || allButtonsDisabled)
|
||||||
}
|
}
|
||||||
>
|
>
|
||||||
<LocalIcon icon="download" width="1.5rem" height="1.5rem" />
|
<LocalIcon icon="download" width="1.5rem" height="1.5rem" />
|
||||||
@@ -477,4 +495,3 @@ export default function RightRail() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import React from "react";
|
||||||
|
|
||||||
|
interface ToolIconProps {
|
||||||
|
icon: React.ReactNode;
|
||||||
|
opacity?: number;
|
||||||
|
color?: string;
|
||||||
|
marginRight?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shared icon component for consistent tool icon styling across the application.
|
||||||
|
* Uses the same visual pattern as ToolButton: scaled to 0.8, centered transform, consistent spacing.
|
||||||
|
*/
|
||||||
|
export const ToolIcon: React.FC<ToolIconProps> = ({
|
||||||
|
icon,
|
||||||
|
opacity = 1,
|
||||||
|
color = "var(--tools-text-and-icon-color)",
|
||||||
|
marginRight = "0.5rem"
|
||||||
|
}) => {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="tool-button-icon"
|
||||||
|
style={{
|
||||||
|
color,
|
||||||
|
marginRight,
|
||||||
|
transform: "scale(0.8)",
|
||||||
|
transformOrigin: "center",
|
||||||
|
opacity
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{icon}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -8,6 +8,7 @@ import { TooltipContent } from './tooltip/TooltipContent';
|
|||||||
import { useSidebarContext } from '../../contexts/SidebarContext';
|
import { useSidebarContext } from '../../contexts/SidebarContext';
|
||||||
import { BASE_PATH } from '../../constants/app';
|
import { BASE_PATH } from '../../constants/app';
|
||||||
import styles from './tooltip/Tooltip.module.css';
|
import styles from './tooltip/Tooltip.module.css';
|
||||||
|
import { Z_INDEX_OVER_FULLSCREEN_SURFACE } from '../../styles/zIndex';
|
||||||
|
|
||||||
export interface TooltipProps {
|
export interface TooltipProps {
|
||||||
sidebarTooltip?: boolean;
|
sidebarTooltip?: boolean;
|
||||||
@@ -28,6 +29,10 @@ export interface TooltipProps {
|
|||||||
pinOnClick?: boolean;
|
pinOnClick?: boolean;
|
||||||
/** If true, clicking outside also closes when not pinned (default true) */
|
/** If true, clicking outside also closes when not pinned (default true) */
|
||||||
closeOnOutside?: boolean;
|
closeOnOutside?: boolean;
|
||||||
|
/** If true, tooltip interaction is disabled entirely */
|
||||||
|
disabled?: boolean;
|
||||||
|
/** If false, tooltip will not open on focus (hover only) */
|
||||||
|
openOnFocus?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const Tooltip: React.FC<TooltipProps> = ({
|
export const Tooltip: React.FC<TooltipProps> = ({
|
||||||
@@ -48,6 +53,8 @@ export const Tooltip: React.FC<TooltipProps> = ({
|
|||||||
containerStyle = {},
|
containerStyle = {},
|
||||||
pinOnClick = false,
|
pinOnClick = false,
|
||||||
closeOnOutside = true,
|
closeOnOutside = true,
|
||||||
|
disabled = false,
|
||||||
|
openOnFocus = true,
|
||||||
}) => {
|
}) => {
|
||||||
const [internalOpen, setInternalOpen] = useState(false);
|
const [internalOpen, setInternalOpen] = useState(false);
|
||||||
const [isPinned, setIsPinned] = useState(false);
|
const [isPinned, setIsPinned] = useState(false);
|
||||||
@@ -68,7 +75,7 @@ export const Tooltip: React.FC<TooltipProps> = ({
|
|||||||
const sidebarContext = sidebarTooltip ? useSidebarContext() : null;
|
const sidebarContext = sidebarTooltip ? useSidebarContext() : null;
|
||||||
|
|
||||||
const isControlled = controlledOpen !== undefined;
|
const isControlled = controlledOpen !== undefined;
|
||||||
const open = isControlled ? !!controlledOpen : internalOpen;
|
const open = (isControlled ? !!controlledOpen : internalOpen) && !disabled;
|
||||||
|
|
||||||
const setOpen = useCallback(
|
const setOpen = useCallback(
|
||||||
(newOpen: boolean) => {
|
(newOpen: boolean) => {
|
||||||
@@ -148,15 +155,16 @@ export const Tooltip: React.FC<TooltipProps> = ({
|
|||||||
// === Trigger handlers ===
|
// === Trigger handlers ===
|
||||||
const openWithDelay = useCallback(() => {
|
const openWithDelay = useCallback(() => {
|
||||||
clearTimers();
|
clearTimers();
|
||||||
|
if (disabled) return;
|
||||||
openTimeoutRef.current = setTimeout(() => setOpen(true), Math.max(0, delay || 0));
|
openTimeoutRef.current = setTimeout(() => setOpen(true), Math.max(0, delay || 0));
|
||||||
}, [clearTimers, setOpen, delay]);
|
}, [clearTimers, setOpen, delay, disabled]);
|
||||||
|
|
||||||
const handlePointerEnter = useCallback(
|
const handlePointerEnter = useCallback(
|
||||||
(e: React.PointerEvent) => {
|
(e: React.PointerEvent) => {
|
||||||
if (!isPinned) openWithDelay();
|
if (!isPinned && !disabled) openWithDelay();
|
||||||
(children.props as any)?.onPointerEnter?.(e);
|
(children.props as any)?.onPointerEnter?.(e);
|
||||||
},
|
},
|
||||||
[isPinned, openWithDelay, children.props]
|
[isPinned, openWithDelay, children.props, disabled]
|
||||||
);
|
);
|
||||||
|
|
||||||
const handlePointerLeave = useCallback(
|
const handlePointerLeave = useCallback(
|
||||||
@@ -219,10 +227,10 @@ export const Tooltip: React.FC<TooltipProps> = ({
|
|||||||
// Keyboard / focus accessibility
|
// Keyboard / focus accessibility
|
||||||
const handleFocus = useCallback(
|
const handleFocus = useCallback(
|
||||||
(e: React.FocusEvent) => {
|
(e: React.FocusEvent) => {
|
||||||
if (!isPinned) openWithDelay();
|
if (!isPinned && !disabled && openOnFocus) openWithDelay();
|
||||||
(children.props as any)?.onFocus?.(e);
|
(children.props as any)?.onFocus?.(e);
|
||||||
},
|
},
|
||||||
[isPinned, openWithDelay, children.props]
|
[isPinned, openWithDelay, children.props, disabled, openOnFocus]
|
||||||
);
|
);
|
||||||
|
|
||||||
const handleBlur = useCallback(
|
const handleBlur = useCallback(
|
||||||
@@ -291,7 +299,7 @@ export const Tooltip: React.FC<TooltipProps> = ({
|
|||||||
left: coords.left,
|
left: coords.left,
|
||||||
width: maxWidth !== undefined ? maxWidth : (sidebarTooltip ? '25rem' as const : undefined),
|
width: maxWidth !== undefined ? maxWidth : (sidebarTooltip ? '25rem' as const : undefined),
|
||||||
minWidth,
|
minWidth,
|
||||||
zIndex: 9999,
|
zIndex: Z_INDEX_OVER_FULLSCREEN_SURFACE,
|
||||||
visibility: positionReady ? 'visible' : 'hidden',
|
visibility: positionReady ? 'visible' : 'hidden',
|
||||||
opacity: positionReady ? 1 : 0,
|
opacity: positionReady ? 1 : 0,
|
||||||
color: 'var(--text-primary)',
|
color: 'var(--text-primary)',
|
||||||
@@ -345,9 +353,13 @@ export const Tooltip: React.FC<TooltipProps> = ({
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{childWithHandlers}
|
{childWithHandlers}
|
||||||
{portalTarget && document.body.contains(portalTarget)
|
{(() => {
|
||||||
? tooltipElement && createPortal(tooltipElement, portalTarget)
|
const defaultTarget = typeof document !== 'undefined' ? document.body : null;
|
||||||
: tooltipElement}
|
const target = portalTarget ?? defaultTarget;
|
||||||
|
return tooltipElement && target
|
||||||
|
? createPortal(tooltipElement, target)
|
||||||
|
: tooltipElement;
|
||||||
|
})()}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { NavKey } from './types';
|
||||||
|
import HotkeysSection from './configSections/HotkeysSection';
|
||||||
|
import GeneralSection from './configSections/GeneralSection';
|
||||||
|
|
||||||
|
export interface ConfigNavItem {
|
||||||
|
key: NavKey;
|
||||||
|
label: string;
|
||||||
|
icon: string;
|
||||||
|
component: React.ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ConfigNavSection {
|
||||||
|
title: string;
|
||||||
|
items: ConfigNavItem[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ConfigColors {
|
||||||
|
navBg: string;
|
||||||
|
sectionTitle: string;
|
||||||
|
navItem: string;
|
||||||
|
navItemActive: string;
|
||||||
|
navItemActiveBg: string;
|
||||||
|
contentBg: string;
|
||||||
|
headerBorder: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const createConfigNavSections = (
|
||||||
|
Overview: React.ComponentType<{ onLogoutClick: () => void }>,
|
||||||
|
onLogoutClick: () => void
|
||||||
|
): ConfigNavSection[] => {
|
||||||
|
const sections: ConfigNavSection[] = [
|
||||||
|
{
|
||||||
|
title: 'Account',
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
key: 'overview',
|
||||||
|
label: 'Overview',
|
||||||
|
icon: 'person-rounded',
|
||||||
|
component: <Overview onLogoutClick={onLogoutClick} />
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'Preferences',
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
key: 'general',
|
||||||
|
label: 'General',
|
||||||
|
icon: 'settings-rounded',
|
||||||
|
component: <GeneralSection />
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'hotkeys',
|
||||||
|
label: 'Keyboard Shortcuts',
|
||||||
|
icon: 'keyboard-rounded',
|
||||||
|
component: <HotkeysSection />
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
return sections;
|
||||||
|
};
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
import React, { useState, useEffect } from 'react';
|
||||||
|
import { Paper, Stack, Switch, Text, Tooltip, NumberInput, SegmentedControl } from '@mantine/core';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { usePreferences } from '../../../../contexts/PreferencesContext';
|
||||||
|
import { ToolPanelMode } from 'src/contexts/toolWorkflow/toolWorkflowState';
|
||||||
|
|
||||||
|
const DEFAULT_AUTO_UNZIP_FILE_LIMIT = 4;
|
||||||
|
|
||||||
|
const GeneralSection: React.FC = () => {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const { preferences, updatePreference } = usePreferences();
|
||||||
|
const [fileLimitInput, setFileLimitInput] = useState<number | string>(preferences.autoUnzipFileLimit);
|
||||||
|
|
||||||
|
// Sync local state with preference changes
|
||||||
|
useEffect(() => {
|
||||||
|
setFileLimitInput(preferences.autoUnzipFileLimit);
|
||||||
|
}, [preferences.autoUnzipFileLimit]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Stack gap="lg">
|
||||||
|
<div>
|
||||||
|
<Text fw={600} size="lg">{t('settings.general.title', 'General')}</Text>
|
||||||
|
<Text size="sm" c="dimmed">
|
||||||
|
{t('settings.general.description', 'Configure general application preferences.')}
|
||||||
|
</Text>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Paper withBorder p="md" radius="md">
|
||||||
|
<Stack gap="md">
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
|
||||||
|
<div>
|
||||||
|
<Text fw={500} size="sm">
|
||||||
|
{t('settings.general.defaultToolPickerMode', 'Default tool picker mode')}
|
||||||
|
</Text>
|
||||||
|
<Text size="xs" c="dimmed" mt={4}>
|
||||||
|
{t('settings.general.defaultToolPickerModeDescription', 'Choose whether the tool picker opens in fullscreen or sidebar by default')}
|
||||||
|
</Text>
|
||||||
|
</div>
|
||||||
|
<SegmentedControl
|
||||||
|
value={preferences.defaultToolPanelMode}
|
||||||
|
onChange={(val: string) => updatePreference('defaultToolPanelMode', val as ToolPanelMode)}
|
||||||
|
data={[
|
||||||
|
{ label: t('settings.general.mode.sidebar', 'Sidebar'), value: 'sidebar' },
|
||||||
|
{ label: t('settings.general.mode.fullscreen', 'Fullscreen'), value: 'fullscreen' },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<Tooltip
|
||||||
|
label={t('settings.general.autoUnzipTooltip', 'Automatically extract ZIP files returned from API operations. Disable to keep ZIP files intact. This does not affect automation workflows.')}
|
||||||
|
multiline
|
||||||
|
w={300}
|
||||||
|
withArrow
|
||||||
|
>
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', cursor: 'help' }}>
|
||||||
|
<div>
|
||||||
|
<Text fw={500} size="sm">
|
||||||
|
{t('settings.general.autoUnzip', 'Auto-unzip API responses')}
|
||||||
|
</Text>
|
||||||
|
<Text size="xs" c="dimmed" mt={4}>
|
||||||
|
{t('settings.general.autoUnzipDescription', 'Automatically extract files from ZIP responses')}
|
||||||
|
</Text>
|
||||||
|
</div>
|
||||||
|
<Switch
|
||||||
|
checked={preferences.autoUnzip}
|
||||||
|
onChange={(event) => updatePreference('autoUnzip', event.currentTarget.checked)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</Tooltip>
|
||||||
|
|
||||||
|
<Tooltip
|
||||||
|
label={t('settings.general.autoUnzipFileLimitTooltip', 'Only unzip if the ZIP contains this many files or fewer. Set higher to extract larger ZIPs.')}
|
||||||
|
multiline
|
||||||
|
w={300}
|
||||||
|
withArrow
|
||||||
|
>
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', cursor: 'help' }}>
|
||||||
|
<div>
|
||||||
|
<Text fw={500} size="sm">
|
||||||
|
{t('settings.general.autoUnzipFileLimit', 'Auto-unzip file limit')}
|
||||||
|
</Text>
|
||||||
|
<Text size="xs" c="dimmed" mt={4}>
|
||||||
|
{t('settings.general.autoUnzipFileLimitDescription', 'Maximum number of files to extract from ZIP')}
|
||||||
|
</Text>
|
||||||
|
</div>
|
||||||
|
<NumberInput
|
||||||
|
value={fileLimitInput}
|
||||||
|
onChange={setFileLimitInput}
|
||||||
|
onBlur={() => {
|
||||||
|
const numValue = Number(fileLimitInput);
|
||||||
|
const finalValue = (!fileLimitInput || isNaN(numValue) || numValue < 1 || numValue > 100) ? DEFAULT_AUTO_UNZIP_FILE_LIMIT : numValue;
|
||||||
|
setFileLimitInput(finalValue);
|
||||||
|
updatePreference('autoUnzipFileLimit', finalValue);
|
||||||
|
}}
|
||||||
|
min={1}
|
||||||
|
max={100}
|
||||||
|
step={1}
|
||||||
|
disabled={!preferences.autoUnzip}
|
||||||
|
style={{ width: 90 }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</Tooltip>
|
||||||
|
</Stack>
|
||||||
|
</Paper>
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default GeneralSection;
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
import React, { useEffect, useMemo, useState } from 'react';
|
||||||
|
import { Alert, Badge, Box, Button, Divider, Group, Paper, Stack, Text, TextInput } from '@mantine/core';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { useToolWorkflow } from '../../../../contexts/ToolWorkflowContext';
|
||||||
|
import { useHotkeys } from '../../../../contexts/HotkeyContext';
|
||||||
|
import { ToolId } from '../../../../types/toolId';
|
||||||
|
import HotkeyDisplay from '../../../hotkeys/HotkeyDisplay';
|
||||||
|
import { bindingEquals, eventToBinding, HotkeyBinding } from '../../../../utils/hotkeys';
|
||||||
|
import { ToolRegistryEntry } from 'src/data/toolsTaxonomy';
|
||||||
|
|
||||||
|
const rowStyle: React.CSSProperties = {
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
gap: '0.5rem',
|
||||||
|
};
|
||||||
|
|
||||||
|
const rowHeaderStyle: React.CSSProperties = {
|
||||||
|
display: 'flex',
|
||||||
|
flexWrap: 'wrap',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'space-between',
|
||||||
|
gap: '0.5rem',
|
||||||
|
};
|
||||||
|
|
||||||
|
const HotkeysSection: React.FC = () => {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const { toolRegistry } = useToolWorkflow();
|
||||||
|
const { hotkeys, defaults, updateHotkey, resetHotkey, pauseHotkeys, resumeHotkeys, getDisplayParts, isMac } = useHotkeys();
|
||||||
|
const [editingTool, setEditingTool] = useState<ToolId | null>(null);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [searchQuery, setSearchQuery] = useState<string>('');
|
||||||
|
|
||||||
|
const tools = useMemo(() => Object.entries(toolRegistry) as [ToolId, ToolRegistryEntry][], [toolRegistry]);
|
||||||
|
|
||||||
|
const filteredTools = useMemo(() => {
|
||||||
|
if (!searchQuery.trim()) return tools;
|
||||||
|
|
||||||
|
const query = searchQuery.toLowerCase();
|
||||||
|
return tools.filter(([toolId, tool]) =>
|
||||||
|
tool.name.toLowerCase().includes(query) ||
|
||||||
|
tool.description.toLowerCase().includes(query) ||
|
||||||
|
toolId.toLowerCase().includes(query)
|
||||||
|
);
|
||||||
|
}, [tools, searchQuery]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!editingTool) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
pauseHotkeys();
|
||||||
|
return () => {
|
||||||
|
resumeHotkeys();
|
||||||
|
};
|
||||||
|
}, [editingTool, pauseHotkeys, resumeHotkeys]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!editingTool) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleKeyDown = (event: KeyboardEvent) => {
|
||||||
|
if (event.key === 'Escape') {
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
setEditingTool(null);
|
||||||
|
setError(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
|
||||||
|
const binding = eventToBinding(event as KeyboardEvent);
|
||||||
|
if (!binding) {
|
||||||
|
const osKey = isMac ? 'mac' : 'windows';
|
||||||
|
const fallbackText = isMac
|
||||||
|
? 'Include ⌘ (Command), ⌥ (Option), or another modifier in your shortcut.'
|
||||||
|
: 'Include Ctrl, Alt, or another modifier in your shortcut.';
|
||||||
|
setError(t(`settings.hotkeys.errorModifier.${osKey}`, fallbackText));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const conflictEntry = (Object.entries(hotkeys) as [ToolId, HotkeyBinding][]).find(([toolId, existing]) => (
|
||||||
|
toolId !== editingTool && bindingEquals(existing, binding)
|
||||||
|
));
|
||||||
|
|
||||||
|
if (conflictEntry) {
|
||||||
|
const conflictKey = conflictEntry[0];
|
||||||
|
const conflictTool = (conflictKey in toolRegistry)
|
||||||
|
? toolRegistry[conflictKey as ToolId]?.name
|
||||||
|
: conflictKey;
|
||||||
|
setError(t('settings.hotkeys.errorConflict', 'Shortcut already used by {{tool}}.', { tool: conflictTool }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
updateHotkey(editingTool, binding);
|
||||||
|
setEditingTool(null);
|
||||||
|
setError(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
window.addEventListener('keydown', handleKeyDown, true);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('keydown', handleKeyDown, true);
|
||||||
|
};
|
||||||
|
}, [editingTool, hotkeys, toolRegistry, updateHotkey, t]);
|
||||||
|
|
||||||
|
const handleStartCapture = (toolId: ToolId) => {
|
||||||
|
setEditingTool(toolId);
|
||||||
|
setError(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Stack gap="lg">
|
||||||
|
<div>
|
||||||
|
<Text fw={600} size="lg">Keyboard Shortcuts</Text>
|
||||||
|
<Text size="sm" c="dimmed">
|
||||||
|
Customize keyboard shortcuts for quick tool access. Click "Change shortcut" and press a new key combination. Press Esc to cancel.
|
||||||
|
</Text>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<TextInput
|
||||||
|
placeholder={t('settings.hotkeys.searchPlaceholder', 'Search tools...')}
|
||||||
|
value={searchQuery}
|
||||||
|
onChange={(event) => setSearchQuery(event.currentTarget.value)}
|
||||||
|
size="md"
|
||||||
|
radius="md"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Paper withBorder p="md" radius="md">
|
||||||
|
<Stack gap="md">
|
||||||
|
{filteredTools.length === 0 ? (
|
||||||
|
<Text c="dimmed" ta="center" py="xl">
|
||||||
|
{t('toolPicker.noToolsFound', 'No tools found')}
|
||||||
|
</Text>
|
||||||
|
) : (
|
||||||
|
filteredTools.map(([toolId, tool], index) => {
|
||||||
|
const currentBinding = hotkeys[toolId];
|
||||||
|
const defaultBinding = defaults[toolId];
|
||||||
|
const isEditing = editingTool === toolId;
|
||||||
|
const defaultParts = getDisplayParts(defaultBinding);
|
||||||
|
const defaultLabel = defaultParts.length > 0
|
||||||
|
? defaultParts.join(' + ')
|
||||||
|
: t('settings.hotkeys.none', 'Not assigned');
|
||||||
|
|
||||||
|
return (
|
||||||
|
<React.Fragment key={toolId}>
|
||||||
|
<Box style={rowStyle} data-testid={`hotkey-row-${toolId}`}>
|
||||||
|
<div style={rowHeaderStyle}>
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', gap: '0.25rem', minWidth: 0 }}>
|
||||||
|
<Text fw={600}>{tool.name}</Text>
|
||||||
|
<Group gap="xs" wrap="wrap" align="center">
|
||||||
|
<HotkeyDisplay binding={currentBinding} size="md" />
|
||||||
|
{!bindingEquals(currentBinding, defaultBinding) && (
|
||||||
|
<Badge variant="light" color="orange" radius="sm">
|
||||||
|
{t('settings.hotkeys.customBadge', 'Custom')}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
<Text size="xs" c="dimmed">
|
||||||
|
{t('settings.hotkeys.defaultLabel', 'Default: {{shortcut}}', { shortcut: defaultLabel })}
|
||||||
|
</Text>
|
||||||
|
</Group>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Group gap="xs">
|
||||||
|
<Button
|
||||||
|
size="xs"
|
||||||
|
variant={isEditing ? 'filled' : 'default'}
|
||||||
|
color={isEditing ? 'blue' : undefined}
|
||||||
|
onClick={() => handleStartCapture(toolId)}
|
||||||
|
>
|
||||||
|
{isEditing
|
||||||
|
? t('settings.hotkeys.capturing', 'Press keys… (Esc to cancel)')
|
||||||
|
: t('settings.hotkeys.change', 'Change shortcut')}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size="xs"
|
||||||
|
variant="subtle"
|
||||||
|
disabled={bindingEquals(currentBinding, defaultBinding)}
|
||||||
|
onClick={() => resetHotkey(toolId)}
|
||||||
|
>
|
||||||
|
{t('settings.hotkeys.reset', 'Reset')}
|
||||||
|
</Button>
|
||||||
|
</Group>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{isEditing && error && (
|
||||||
|
<Alert color="red" radius="sm" variant="filled">
|
||||||
|
{error}
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
</Box>
|
||||||
|
|
||||||
|
{index < filteredTools.length - 1 && <Divider />}
|
||||||
|
</React.Fragment>
|
||||||
|
);
|
||||||
|
})
|
||||||
|
)}
|
||||||
|
</Stack>
|
||||||
|
</Paper>
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default HotkeysSection;
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { Stack, Text, Code, Group, Badge, Alert, Loader } from '@mantine/core';
|
||||||
|
import { useAppConfig } from '../../../../hooks/useAppConfig';
|
||||||
|
|
||||||
|
const Overview: React.FC = () => {
|
||||||
|
const { config, loading, error } = useAppConfig();
|
||||||
|
|
||||||
|
const renderConfigSection = (title: string, data: any) => {
|
||||||
|
if (!data || typeof data !== 'object') return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Stack gap="xs" mb="md">
|
||||||
|
<Text fw={600} size="md" c="blue">{title}</Text>
|
||||||
|
<Stack gap="xs" pl="md">
|
||||||
|
{Object.entries(data).map(([key, value]) => (
|
||||||
|
<Group key={key} wrap="nowrap" align="flex-start">
|
||||||
|
<Text size="sm" w={150} style={{ flexShrink: 0 }} c="dimmed">
|
||||||
|
{key}:
|
||||||
|
</Text>
|
||||||
|
{typeof value === 'boolean' ? (
|
||||||
|
<Badge color={value ? 'green' : 'red'} size="sm">
|
||||||
|
{value ? 'true' : 'false'}
|
||||||
|
</Badge>
|
||||||
|
) : typeof value === 'object' ? (
|
||||||
|
<Code block>{JSON.stringify(value, null, 2)}</Code>
|
||||||
|
) : (
|
||||||
|
String(value) || 'null'
|
||||||
|
)}
|
||||||
|
</Group>
|
||||||
|
))}
|
||||||
|
</Stack>
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const basicConfig = config ? {
|
||||||
|
appName: config.appName,
|
||||||
|
appNameNavbar: config.appNameNavbar,
|
||||||
|
baseUrl: config.baseUrl,
|
||||||
|
contextPath: config.contextPath,
|
||||||
|
serverPort: config.serverPort,
|
||||||
|
} : null;
|
||||||
|
|
||||||
|
const securityConfig = config ? {
|
||||||
|
enableLogin: config.enableLogin,
|
||||||
|
} : null;
|
||||||
|
|
||||||
|
const systemConfig = config ? {
|
||||||
|
enableAlphaFunctionality: config.enableAlphaFunctionality,
|
||||||
|
enableAnalytics: config.enableAnalytics,
|
||||||
|
} : null;
|
||||||
|
|
||||||
|
const integrationConfig = config ? {
|
||||||
|
SSOAutoLogin: config.SSOAutoLogin,
|
||||||
|
} : null;
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<Stack align="center" py="md">
|
||||||
|
<Loader size="sm" />
|
||||||
|
<Text size="sm" c="dimmed">Loading configuration...</Text>
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return (
|
||||||
|
<Alert color="red" title="Error">
|
||||||
|
{error}
|
||||||
|
</Alert>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Stack gap="lg">
|
||||||
|
<div>
|
||||||
|
<Text fw={600} size="lg">Application Configuration</Text>
|
||||||
|
<Text size="sm" c="dimmed">
|
||||||
|
Current application settings and configuration details.
|
||||||
|
</Text>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{config && (
|
||||||
|
<>
|
||||||
|
{renderConfigSection('Basic Configuration', basicConfig)}
|
||||||
|
{renderConfigSection('Security Configuration', securityConfig)}
|
||||||
|
{renderConfigSection('System Configuration', systemConfig)}
|
||||||
|
{renderConfigSection('Integration Configuration', integrationConfig)}
|
||||||
|
|
||||||
|
{config.error && (
|
||||||
|
<Alert color="yellow" title="Configuration Warning">
|
||||||
|
{config.error}
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default Overview;
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
export type NavKey =
|
||||||
|
| 'overview'
|
||||||
|
| 'preferences'
|
||||||
|
| 'notifications'
|
||||||
|
| 'connections'
|
||||||
|
| 'general'
|
||||||
|
| 'people'
|
||||||
|
| 'teams'
|
||||||
|
| 'security'
|
||||||
|
| 'identity'
|
||||||
|
| 'plan'
|
||||||
|
| 'payments'
|
||||||
|
| 'requests'
|
||||||
|
| 'developer'
|
||||||
|
| 'api-keys'
|
||||||
|
| 'hotkeys';
|
||||||
|
|
||||||
|
|
||||||
|
// some of these are not used yet, but appear in figma designs
|
||||||
@@ -36,6 +36,7 @@ const DocumentThumbnail: React.FC<DocumentThumbnailProps> = ({
|
|||||||
return (
|
return (
|
||||||
<Box style={containerStyle} onClick={onClick}>
|
<Box style={containerStyle} onClick={onClick}>
|
||||||
<Image
|
<Image
|
||||||
|
className='ph-no-capture'
|
||||||
src={thumbnail}
|
src={thumbnail}
|
||||||
alt={`Preview of ${file.name}`}
|
alt={`Preview of ${file.name}`}
|
||||||
fit="contain"
|
fit="contain"
|
||||||
@@ -50,6 +51,7 @@ const DocumentThumbnail: React.FC<DocumentThumbnailProps> = ({
|
|||||||
<Box style={containerStyle} onClick={onClick}>
|
<Box style={containerStyle} onClick={onClick}>
|
||||||
<Center style={{ width: '100%', height: '100%', backgroundColor: 'var(--mantine-color-gray-1)', borderRadius: '0.25rem' }}>
|
<Center style={{ width: '100%', height: '100%', backgroundColor: 'var(--mantine-color-gray-1)', borderRadius: '0.25rem' }}>
|
||||||
<PictureAsPdfIcon
|
<PictureAsPdfIcon
|
||||||
|
className='ph-no-capture'
|
||||||
style={{
|
style={{
|
||||||
fontSize: '2rem',
|
fontSize: '2rem',
|
||||||
color: 'var(--mantine-color-gray-6)'
|
color: 'var(--mantine-color-gray-6)'
|
||||||
|
|||||||
@@ -46,6 +46,13 @@
|
|||||||
background-color: transparent !important;
|
background-color: transparent !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* When all buttons are disabled via context */
|
||||||
|
.right-rail--all-disabled .right-rail-icon {
|
||||||
|
color: var(--right-rail-icon-disabled) !important;
|
||||||
|
background-color: transparent !important;
|
||||||
|
pointer-events: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
.right-rail-spacer {
|
.right-rail-spacer {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
}
|
}
|
||||||
@@ -67,7 +74,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.right-rail-slot.visible {
|
.right-rail-slot.visible {
|
||||||
max-height: 18rem; /* increased to fit additional controls + divider */
|
max-height: 40rem; /* increased to fit additional controls + divider */
|
||||||
opacity: 1;
|
opacity: 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -77,14 +84,14 @@
|
|||||||
opacity: 0;
|
opacity: 0;
|
||||||
}
|
}
|
||||||
100% {
|
100% {
|
||||||
max-height: 18rem;
|
max-height: 40rem;
|
||||||
opacity: 1;
|
opacity: 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@keyframes rightRailShrinkUp {
|
@keyframes rightRailShrinkUp {
|
||||||
0% {
|
0% {
|
||||||
max-height: 18rem;
|
max-height: 40rem;
|
||||||
opacity: 1;
|
opacity: 1;
|
||||||
}
|
}
|
||||||
100% {
|
100% {
|
||||||
|
|||||||
@@ -0,0 +1,233 @@
|
|||||||
|
import React, { useState, useEffect } from 'react';
|
||||||
|
import { ActionIcon, Popover } from '@mantine/core';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import LocalIcon from '../LocalIcon';
|
||||||
|
import { Tooltip } from '../Tooltip';
|
||||||
|
import { ViewerContext } from '../../../contexts/ViewerContext';
|
||||||
|
import { useSignature } from '../../../contexts/SignatureContext';
|
||||||
|
import { ColorSwatchButton, ColorPicker } from '../../annotation/shared/ColorPicker';
|
||||||
|
import { useFileState, useFileContext } from '../../../contexts/FileContext';
|
||||||
|
import { generateThumbnailWithMetadata } from '../../../utils/thumbnailUtils';
|
||||||
|
import { createProcessedFile } from '../../../contexts/file/fileActions';
|
||||||
|
import { createStirlingFile, createNewStirlingFileStub } from '../../../types/fileContext';
|
||||||
|
import { useNavigationState } from '../../../contexts/NavigationContext';
|
||||||
|
|
||||||
|
interface ViewerAnnotationControlsProps {
|
||||||
|
currentView: string;
|
||||||
|
disabled?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function ViewerAnnotationControls({ currentView, disabled = false }: ViewerAnnotationControlsProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [selectedColor, setSelectedColor] = useState('#000000');
|
||||||
|
const [isColorPickerOpen, setIsColorPickerOpen] = useState(false);
|
||||||
|
const [isHoverColorPickerOpen, setIsHoverColorPickerOpen] = useState(false);
|
||||||
|
|
||||||
|
// Viewer context for PDF controls - safely handle when not available
|
||||||
|
const viewerContext = React.useContext(ViewerContext);
|
||||||
|
|
||||||
|
// Signature context for accessing drawing API
|
||||||
|
const { signatureApiRef, isPlacementMode } = useSignature();
|
||||||
|
|
||||||
|
// File state for save functionality
|
||||||
|
const { state, selectors } = useFileState();
|
||||||
|
const { actions: fileActions } = useFileContext();
|
||||||
|
const activeFiles = selectors.getFiles();
|
||||||
|
|
||||||
|
// Check if we're in sign mode
|
||||||
|
const { selectedTool } = useNavigationState();
|
||||||
|
const isSignMode = selectedTool === 'sign';
|
||||||
|
|
||||||
|
// Turn off annotation mode when switching away from viewer
|
||||||
|
useEffect(() => {
|
||||||
|
if (currentView !== 'viewer' && viewerContext?.isAnnotationMode) {
|
||||||
|
viewerContext.setAnnotationMode(false);
|
||||||
|
}
|
||||||
|
}, [currentView, viewerContext]);
|
||||||
|
|
||||||
|
// Don't show any annotation controls in sign mode
|
||||||
|
if (isSignMode) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{/* Annotation Visibility Toggle */}
|
||||||
|
<Tooltip content={t('rightRail.toggleAnnotations', 'Toggle Annotations Visibility')} position="left" offset={12} arrow portalTarget={document.body}>
|
||||||
|
<ActionIcon
|
||||||
|
variant="subtle"
|
||||||
|
radius="md"
|
||||||
|
className="right-rail-icon"
|
||||||
|
onClick={() => {
|
||||||
|
viewerContext?.toggleAnnotationsVisibility();
|
||||||
|
}}
|
||||||
|
disabled={disabled || currentView !== 'viewer' || viewerContext?.isAnnotationMode || isPlacementMode}
|
||||||
|
>
|
||||||
|
<LocalIcon
|
||||||
|
icon={viewerContext?.isAnnotationsVisible ? "visibility" : "visibility-off-rounded"}
|
||||||
|
width="1.5rem"
|
||||||
|
height="1.5rem"
|
||||||
|
/>
|
||||||
|
</ActionIcon>
|
||||||
|
</Tooltip>
|
||||||
|
|
||||||
|
{/* Annotation Mode Toggle with Drawing Controls */}
|
||||||
|
{viewerContext?.isAnnotationMode ? (
|
||||||
|
// When active: Show color picker on hover
|
||||||
|
<div
|
||||||
|
onMouseEnter={() => setIsHoverColorPickerOpen(true)}
|
||||||
|
onMouseLeave={() => setIsHoverColorPickerOpen(false)}
|
||||||
|
style={{ display: 'inline-flex' }}
|
||||||
|
>
|
||||||
|
<Popover
|
||||||
|
opened={isHoverColorPickerOpen}
|
||||||
|
onClose={() => setIsHoverColorPickerOpen(false)}
|
||||||
|
position="left"
|
||||||
|
withArrow
|
||||||
|
shadow="md"
|
||||||
|
offset={8}
|
||||||
|
>
|
||||||
|
<Popover.Target>
|
||||||
|
<ActionIcon
|
||||||
|
variant="filled"
|
||||||
|
color="blue"
|
||||||
|
radius="md"
|
||||||
|
className="right-rail-icon"
|
||||||
|
onClick={() => {
|
||||||
|
viewerContext?.toggleAnnotationMode();
|
||||||
|
setIsHoverColorPickerOpen(false); // Close hover color picker when toggling off
|
||||||
|
// Deactivate drawing tool when exiting annotation mode
|
||||||
|
if (signatureApiRef?.current) {
|
||||||
|
try {
|
||||||
|
signatureApiRef.current.deactivateTools();
|
||||||
|
} catch (error) {
|
||||||
|
console.log('Signature API not ready:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
disabled={disabled}
|
||||||
|
aria-label="Drawing mode active"
|
||||||
|
>
|
||||||
|
<LocalIcon icon="edit" width="1.5rem" height="1.5rem" />
|
||||||
|
</ActionIcon>
|
||||||
|
</Popover.Target>
|
||||||
|
<Popover.Dropdown>
|
||||||
|
<div style={{ minWidth: '8rem' }}>
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '0.5rem', padding: '0.5rem' }}>
|
||||||
|
<div style={{ fontSize: '0.8rem', fontWeight: 500 }}>Drawing Color</div>
|
||||||
|
<ColorSwatchButton
|
||||||
|
color={selectedColor}
|
||||||
|
size={32}
|
||||||
|
onClick={() => {
|
||||||
|
setIsHoverColorPickerOpen(false); // Close hover picker
|
||||||
|
setIsColorPickerOpen(true); // Open main color picker modal
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Popover.Dropdown>
|
||||||
|
</Popover>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
// When inactive: Show "Draw" tooltip
|
||||||
|
<Tooltip content={t('rightRail.draw', 'Draw')} position="left" offset={12} arrow portalTarget={document.body}>
|
||||||
|
<ActionIcon
|
||||||
|
variant="subtle"
|
||||||
|
radius="md"
|
||||||
|
className="right-rail-icon"
|
||||||
|
onClick={() => {
|
||||||
|
viewerContext?.toggleAnnotationMode();
|
||||||
|
// Activate ink drawing tool when entering annotation mode
|
||||||
|
if (signatureApiRef?.current && currentView === 'viewer') {
|
||||||
|
try {
|
||||||
|
signatureApiRef.current.activateDrawMode();
|
||||||
|
signatureApiRef.current.updateDrawSettings(selectedColor, 2);
|
||||||
|
} catch (error) {
|
||||||
|
console.log('Signature API not ready:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
disabled={disabled}
|
||||||
|
aria-label={typeof t === 'function' ? t('rightRail.draw', 'Draw') : 'Draw'}
|
||||||
|
>
|
||||||
|
<LocalIcon icon="edit" width="1.5rem" height="1.5rem" />
|
||||||
|
</ActionIcon>
|
||||||
|
</Tooltip>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Save PDF with Annotations */}
|
||||||
|
<Tooltip content={t('rightRail.save', 'Save')} position="left" offset={12} arrow portalTarget={document.body}>
|
||||||
|
<ActionIcon
|
||||||
|
variant="subtle"
|
||||||
|
radius="md"
|
||||||
|
className="right-rail-icon"
|
||||||
|
onClick={async () => {
|
||||||
|
if (viewerContext?.exportActions?.saveAsCopy && currentView === 'viewer') {
|
||||||
|
try {
|
||||||
|
const pdfArrayBuffer = await viewerContext.exportActions.saveAsCopy();
|
||||||
|
if (pdfArrayBuffer) {
|
||||||
|
// Create new File object with flattened annotations
|
||||||
|
const blob = new Blob([pdfArrayBuffer], { type: 'application/pdf' });
|
||||||
|
|
||||||
|
// Get the original file name or use a default
|
||||||
|
const originalFileName = activeFiles.length > 0 ? activeFiles[0].name : 'document.pdf';
|
||||||
|
const newFile = new File([blob], originalFileName, { type: 'application/pdf' });
|
||||||
|
|
||||||
|
// Replace the current file in context with the saved version (exact same logic as Sign tool)
|
||||||
|
if (activeFiles.length > 0) {
|
||||||
|
// Generate thumbnail and metadata for the saved file
|
||||||
|
const thumbnailResult = await generateThumbnailWithMetadata(newFile);
|
||||||
|
const processedFileMetadata = createProcessedFile(thumbnailResult.pageCount, thumbnailResult.thumbnail);
|
||||||
|
|
||||||
|
// Get current file info
|
||||||
|
const currentFileIds = state.files.ids;
|
||||||
|
if (currentFileIds.length > 0) {
|
||||||
|
const currentFileId = currentFileIds[0];
|
||||||
|
const currentRecord = selectors.getStirlingFileStub(currentFileId);
|
||||||
|
|
||||||
|
if (!currentRecord) {
|
||||||
|
console.error('No file record found for:', currentFileId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create output stub and file (exact same as Sign tool)
|
||||||
|
const outputStub = createNewStirlingFileStub(newFile, undefined, thumbnailResult.thumbnail, processedFileMetadata);
|
||||||
|
const outputStirlingFile = createStirlingFile(newFile, outputStub.id);
|
||||||
|
|
||||||
|
// Replace the original file with the saved version
|
||||||
|
await fileActions.consumeFiles([currentFileId], [outputStirlingFile], [outputStub]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error saving PDF:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
disabled={disabled}
|
||||||
|
>
|
||||||
|
<LocalIcon icon="save" width="1.5rem" height="1.5rem" />
|
||||||
|
</ActionIcon>
|
||||||
|
</Tooltip>
|
||||||
|
|
||||||
|
{/* Color Picker Modal */}
|
||||||
|
<ColorPicker
|
||||||
|
isOpen={isColorPickerOpen}
|
||||||
|
onClose={() => setIsColorPickerOpen(false)}
|
||||||
|
selectedColor={selectedColor}
|
||||||
|
onColorChange={(color) => {
|
||||||
|
setSelectedColor(color);
|
||||||
|
// Update drawing tool color if annotation mode is active
|
||||||
|
if (viewerContext?.isAnnotationMode && signatureApiRef?.current && currentView === 'viewer') {
|
||||||
|
try {
|
||||||
|
signatureApiRef.current.updateDrawSettings(color, 2);
|
||||||
|
} catch (error) {
|
||||||
|
console.log('Unable to update drawing settings:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
title="Choose Drawing Color"
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { Slider, Text, Group, NumberInput } from '@mantine/core';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
label: string;
|
||||||
|
value: number;
|
||||||
|
onChange: (value: number) => void;
|
||||||
|
disabled?: boolean;
|
||||||
|
min?: number;
|
||||||
|
max?: number;
|
||||||
|
step?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function SliderWithInput({
|
||||||
|
label,
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
disabled,
|
||||||
|
min = 0,
|
||||||
|
max = 200,
|
||||||
|
step = 1,
|
||||||
|
}: Props) {
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<Text size="sm" fw={600} mb={4}>{label}: {Math.round(value)}%</Text>
|
||||||
|
<Group gap="sm" align="center">
|
||||||
|
<div style={{ flex: 1 }}>
|
||||||
|
<Slider min={min} max={max} step={step} value={value} onChange={onChange} disabled={disabled} />
|
||||||
|
</div>
|
||||||
|
<NumberInput
|
||||||
|
value={value}
|
||||||
|
onChange={(v) => onChange(Number(v) || 0)}
|
||||||
|
min={min}
|
||||||
|
max={max}
|
||||||
|
step={step}
|
||||||
|
disabled={disabled}
|
||||||
|
style={{ width: 90 }}
|
||||||
|
/>
|
||||||
|
</Group>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user