Compare commits
41
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
464ab0dee0 | ||
|
|
68ccb0f970 | ||
|
|
b126fb3bd6 | ||
|
|
d5653499ac | ||
|
|
a00b636be2 | ||
|
|
5852b27d49 | ||
|
|
aaafa12bc7 | ||
|
|
1fa0ca4cd2 | ||
|
|
e172874dbb | ||
|
|
37565cf7b7 | ||
|
|
6947a05fdd | ||
|
|
9d5674f0ca | ||
|
|
7d3c5faacd | ||
|
|
e05a55f919 | ||
|
|
b3a7458f44 | ||
|
|
dc739efddf | ||
|
|
534064e303 | ||
|
|
833e56826d | ||
|
|
f596423f75 | ||
|
|
be5ea72ea6 | ||
|
|
6bc78b481e | ||
|
|
f1d84d599d | ||
|
|
ff9c0e9bd4 | ||
|
|
a949019d5d | ||
|
|
cd71075f79 | ||
|
|
1a8d2f3d33 | ||
|
|
a660e332e3 | ||
|
|
ae1fa54d4a | ||
|
|
44e09f47ce | ||
|
|
b06ae41a49 | ||
|
|
99bc3a1ebf | ||
|
|
07eb28194d | ||
|
|
285e024b00 | ||
|
|
6c43558975 | ||
|
|
019fe714c5 | ||
|
|
bf03a6011b | ||
|
|
ac8ced8a03 | ||
|
|
e00baeb033 | ||
|
|
6a09ec6091 | ||
|
|
070f8b73e5 | ||
|
|
91631bb1de |
@@ -3,15 +3,7 @@ name: Auto PR V2 Deployment
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened, closed]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
pr:
|
||||
description: "PR number to deploy"
|
||||
required: true
|
||||
allow_fork:
|
||||
description: "Allow deploying fork PR?"
|
||||
required: false
|
||||
default: "false"
|
||||
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -20,93 +12,102 @@ permissions:
|
||||
|
||||
jobs:
|
||||
check-pr:
|
||||
if: (github.event_name == 'pull_request' && github.event.action != 'closed') || github.event_name == 'workflow_dispatch'
|
||||
if: github.event.action != 'closed'
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
should_deploy: ${{ steps.decide.outputs.should_deploy }}
|
||||
is_fork: ${{ steps.resolve.outputs.is_fork }}
|
||||
allow_fork: ${{ steps.decide.outputs.allow_fork }}
|
||||
pr_number: ${{ steps.resolve.outputs.pr_number }}
|
||||
pr_repository: ${{ steps.resolve.outputs.repository }}
|
||||
pr_ref: ${{ steps.resolve.outputs.ref }}
|
||||
should_deploy: ${{ steps.check-conditions.outputs.should_deploy }}
|
||||
pr_number: ${{ github.event.number }}
|
||||
pr_repository: ${{ steps.get-pr-info.outputs.repository }}
|
||||
pr_ref: ${{ steps.get-pr-info.outputs.ref }}
|
||||
steps:
|
||||
- name: Harden Runner
|
||||
uses: step-security/harden-runner@6c439dc8bdf85cadbbce9ed30d1c7b959517bc49 # v2.12.2
|
||||
uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1
|
||||
with:
|
||||
egress-policy: audit
|
||||
|
||||
- name: Resolve PR info
|
||||
id: resolve
|
||||
uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1
|
||||
with:
|
||||
script: |
|
||||
const { owner, repo } = context.repo;
|
||||
let prNumber = context.eventName === 'workflow_dispatch'
|
||||
? parseInt(process.env.INPUT_PR, 10)
|
||||
: context.payload.number;
|
||||
|
||||
if (!Number.isInteger(prNumber)) { core.setFailed('Invalid PR number'); return; }
|
||||
|
||||
const { data: pr } = await github.rest.pulls.get({ owner, repo, pull_number: prNumber });
|
||||
core.setOutput('pr_number', String(prNumber));
|
||||
core.setOutput('repository', pr.head.repo.full_name);
|
||||
core.setOutput('ref', pr.head.ref);
|
||||
core.setOutput('is_fork', String(pr.head.repo.fork));
|
||||
core.setOutput('base_ref', pr.base.ref);
|
||||
core.setOutput('author', pr.user.login);
|
||||
core.setOutput('state', pr.state);
|
||||
|
||||
- name: Decide deploy
|
||||
id: decide
|
||||
shell: bash
|
||||
- name: Check deployment conditions
|
||||
id: check-conditions
|
||||
env:
|
||||
EVENT_NAME: ${{ github.event_name }}
|
||||
STATE: ${{ steps.resolve.outputs.state }}
|
||||
IS_FORK: ${{ steps.resolve.outputs.is_fork }}
|
||||
# nur bei workflow_dispatch gesetzt:
|
||||
ALLOW_FORK_INPUT: ${{ inputs.allow_fork }}
|
||||
# für Auto-PR-Logik:
|
||||
PR_TITLE: ${{ github.event.pull_request.title }}
|
||||
PR_AUTHOR: ${{ github.event.pull_request.user.login }}
|
||||
PR_BRANCH: ${{ github.event.pull_request.head.ref }}
|
||||
PR_BASE: ${{ steps.resolve.outputs.base_ref }}
|
||||
PR_AUTHOR: ${{ steps.resolve.outputs.author }}
|
||||
run: |
|
||||
set -e
|
||||
# Standard: nichts deployen
|
||||
should=false
|
||||
allow_fork="$(echo "${ALLOW_FORK_INPUT:-false}" | tr '[:upper:]' '[:lower:]')"
|
||||
|
||||
if [ "$EVENT_NAME" = "workflow_dispatch" ]; then
|
||||
if [ "$STATE" != "open" ]; then
|
||||
echo "PR not open -> skip"
|
||||
else
|
||||
if [ "$IS_FORK" = "true" ] && [ "$allow_fork" != "true" ]; then
|
||||
echo "Fork PR and allow_fork=false -> skip"
|
||||
else
|
||||
should=true
|
||||
fi
|
||||
echo "PR Title: $PR_TITLE"
|
||||
echo "PR Author: $PR_AUTHOR"
|
||||
echo "PR Branch: $PR_BRANCH"
|
||||
echo "PR Base Branch: ${{ github.event.pull_request.base.ref }}"
|
||||
|
||||
# Define authorized users
|
||||
authorized_users=(
|
||||
"Frooodle"
|
||||
"sf298"
|
||||
"Ludy87"
|
||||
"LaserKaspar"
|
||||
"sbplat"
|
||||
"reecebrowne"
|
||||
"DarioGii"
|
||||
"ConnorYoh"
|
||||
"EthanHealy01"
|
||||
"jbrunton96"
|
||||
)
|
||||
|
||||
# Check if author is in the authorized list
|
||||
is_authorized=false
|
||||
for user in "${authorized_users[@]}"; do
|
||||
if [[ "$PR_AUTHOR" == "$user" ]]; then
|
||||
is_authorized=true
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
# If PR is targeting V2 and user is authorized, deploy unconditionally
|
||||
PR_BASE_BRANCH="${{ github.event.pull_request.base.ref }}"
|
||||
if [[ "$PR_BASE_BRANCH" == "V2" && "$is_authorized" == "true" ]]; then
|
||||
echo "✅ Deployment forced: PR targets V2 and author is authorized."
|
||||
echo "should_deploy=true" >> $GITHUB_OUTPUT
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Otherwise, continue with original keyword checks
|
||||
has_v2_keyword=false
|
||||
if [[ "$PR_TITLE" =~ [Vv]2 ]] || [[ "$PR_TITLE" =~ [Vv]ersion.?2 ]] || [[ "$PR_TITLE" =~ [Vv]ersion.?[Tt]wo ]]; then
|
||||
has_v2_keyword=true
|
||||
fi
|
||||
|
||||
has_branch_keyword=false
|
||||
if [[ "$PR_BRANCH" =~ [Vv]2 ]] || [[ "$PR_BRANCH" =~ [Rr]eact ]]; then
|
||||
has_branch_keyword=true
|
||||
fi
|
||||
|
||||
if [[ "$is_authorized" == "true" && ( "$has_v2_keyword" == "true" || "$has_branch_keyword" == "true" ) ]]; then
|
||||
echo "✅ Deployment conditions met"
|
||||
echo "should_deploy=true" >> $GITHUB_OUTPUT
|
||||
else
|
||||
auth_users=("Frooodle" "sf298" "Ludy87" "LaserKaspar" "sbplat" "reecebrowne" "DarioGii" "ConnorYoh" "EthanHealy01" "jbrunton96")
|
||||
is_auth=false; for u in "${auth_users[@]}"; do [ "$u" = "$PR_AUTHOR" ] && is_auth=true && break; done
|
||||
if [ "$PR_BASE" = "V2" ] && [ "$is_auth" = true ]; then
|
||||
should=true
|
||||
else
|
||||
title_has_v2=false; echo "$PR_TITLE" | grep -qiE 'v2|version.?2|version.?two' && title_has_v2=true
|
||||
branch_has_kw=false; echo "$PR_BRANCH" | grep -qiE 'v2|react' && branch_has_kw=true
|
||||
if [ "$is_auth" = true ] && { [ "$title_has_v2" = true ] || [ "$branch_has_kw" = true ]; }; then
|
||||
should=true
|
||||
fi
|
||||
fi
|
||||
echo "❌ Deployment conditions not met"
|
||||
echo " - Authorized user: $is_authorized"
|
||||
echo " - Has V2 keyword in title: $has_v2_keyword"
|
||||
echo " - Has V2/React keyword in branch: $has_branch_keyword"
|
||||
echo "should_deploy=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
echo "should_deploy=$should" >> $GITHUB_OUTPUT
|
||||
echo "allow_fork=${allow_fork:-false}" >> $GITHUB_OUTPUT
|
||||
- name: Get PR repository and ref
|
||||
id: get-pr-info
|
||||
if: steps.check-conditions.outputs.should_deploy == 'true'
|
||||
run: |
|
||||
# For forks, use the full repository name, for internal PRs use the current repo
|
||||
if [[ "${{ github.event.pull_request.head.repo.fork }}" == "true" ]]; then
|
||||
repository="${{ github.event.pull_request.head.repo.full_name }}"
|
||||
else
|
||||
repository="${{ github.repository }}"
|
||||
fi
|
||||
|
||||
echo "repository=$repository" >> $GITHUB_OUTPUT
|
||||
echo "ref=${{ github.event.pull_request.head.ref }}" >> $GITHUB_OUTPUT
|
||||
|
||||
deploy-v2-pr:
|
||||
needs: check-pr
|
||||
runs-on: ubuntu-latest
|
||||
if: needs.check-pr.outputs.should_deploy == 'true' && (needs.check-pr.outputs.is_fork == 'false' || needs.check-pr.outputs.allow_fork == 'true')
|
||||
if: needs.check-pr.outputs.should_deploy == 'true'
|
||||
# Concurrency control - only one deployment per PR at a time
|
||||
concurrency:
|
||||
group: v2-deploy-pr-${{ needs.check-pr.outputs.pr_number }}
|
||||
@@ -118,7 +119,7 @@ jobs:
|
||||
|
||||
steps:
|
||||
- name: Harden Runner
|
||||
uses: step-security/harden-runner@6c439dc8bdf85cadbbce9ed30d1c7b959517bc49 # v2.12.2
|
||||
uses: step-security/harden-runner@002fdce3c6a235733a90a27c80493a3241e56863 # v2.12.1
|
||||
with:
|
||||
egress-policy: audit
|
||||
|
||||
@@ -153,13 +154,13 @@ jobs:
|
||||
issue_number: prNumber,
|
||||
per_page: 100
|
||||
});
|
||||
|
||||
|
||||
const v2Comments = comments.filter(comment =>
|
||||
comment.body.includes('🚀 **Auto-deploying V2 version**') ||
|
||||
comment.body.includes('## 🚀 V2 Auto-Deployment Complete!') ||
|
||||
comment.body.includes('❌ **V2 Auto-deployment failed**')
|
||||
);
|
||||
|
||||
|
||||
for (const comment of v2Comments) {
|
||||
console.log(`Deleting old V2 comment: ${comment.id}`);
|
||||
await github.rest.issues.deleteComment({
|
||||
@@ -176,6 +177,7 @@ jobs:
|
||||
issue_number: prNumber,
|
||||
body: `🚀 **Auto-deploying V2 version** for PR #${prNumber}...\n\n_This is an automated deployment triggered by V2/version2 keywords in the PR title or V2/React keywords in the branch name._\n\n⚠️ **Note:** If new commits are pushed during deployment, this build will be cancelled and replaced with the latest version.`
|
||||
});
|
||||
|
||||
return newComment.id;
|
||||
|
||||
- name: Checkout PR
|
||||
@@ -186,6 +188,7 @@ jobs:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
fetch-depth: 0 # Fetch full history for commit hash detection
|
||||
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435 # v3.11.1
|
||||
|
||||
@@ -209,7 +212,7 @@ jobs:
|
||||
if [ -z "$FRONTEND_HASH" ]; then
|
||||
FRONTEND_HASH="no-frontend-changes"
|
||||
fi
|
||||
|
||||
|
||||
# Get last commit that touched backend code, docker/backend, or docker/compose
|
||||
BACKEND_HASH=$(git log -1 --format="%H" -- app/ docker/backend/ docker/compose/ 2>/dev/null || echo "")
|
||||
if [ -z "$BACKEND_HASH" ]; then
|
||||
@@ -318,7 +321,7 @@ jobs:
|
||||
SWAGGER_SERVER_URL: "https://${V2_PORT}.ssl.stirlingpdf.cloud"
|
||||
baseUrl: "https://${V2_PORT}.ssl.stirlingpdf.cloud"
|
||||
restart: on-failure:5
|
||||
|
||||
|
||||
stirling-pdf-v2-frontend:
|
||||
container_name: stirling-pdf-v2-frontend-pr-${{ needs.check-pr.outputs.pr_number }}
|
||||
image: ${{ secrets.DOCKER_HUB_USERNAME }}/test:v2-frontend-${{ steps.commit-hashes.outputs.frontend_short }}
|
||||
@@ -351,7 +354,7 @@ jobs:
|
||||
|
||||
# Clean up unused Docker resources to save space
|
||||
docker system prune -af --volumes || true
|
||||
|
||||
|
||||
# Clean up old backend/frontend images (older than 2 weeks)
|
||||
docker image prune -af --filter "until=336h" --filter "label!=keep=true" || true
|
||||
ENDSSH
|
||||
@@ -489,7 +492,7 @@ jobs:
|
||||
|
||||
# Clean up old unused images (older than 2 weeks) but keep recent ones for reuse
|
||||
docker image prune -af --filter "until=336h" --filter "label!=keep=true" || true
|
||||
|
||||
|
||||
# Note: We don't remove the commit-based images since they can be reused across PRs
|
||||
# Only remove PR-specific containers and directories
|
||||
ENDSSH
|
||||
@@ -498,4 +501,5 @@ jobs:
|
||||
if: always()
|
||||
run: |
|
||||
rm -f ../private.key
|
||||
continue-on-error: true
|
||||
continue-on-error: true
|
||||
|
||||
|
||||
@@ -145,8 +145,8 @@ jobs:
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: frontend/package-lock.json
|
||||
- name: Clean and install frontend dependencies
|
||||
run: cd frontend && rm -rf node_modules package-lock.json && npm install
|
||||
- name: Install frontend dependencies
|
||||
run: cd frontend && npm ci
|
||||
- name: Lint frontend
|
||||
run: cd frontend && npm run lint
|
||||
- name: Build frontend
|
||||
|
||||
@@ -32,29 +32,18 @@ jobs:
|
||||
with:
|
||||
egress-policy: audit
|
||||
|
||||
- name: Checkout PR head (default)
|
||||
- name: Check out code
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup GitHub App Bot
|
||||
if: github.event_name == 'push' || (github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork == false)
|
||||
id: setup-bot
|
||||
uses: ./.github/actions/setup-bot
|
||||
with:
|
||||
app-id: ${{ secrets.GH_APP_ID }}
|
||||
private-key: ${{ secrets.GH_APP_PRIVATE_KEY }}
|
||||
|
||||
- name: Checkout BASE branch (safe script)
|
||||
if: github.event_name == 'pull_request'
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.base.sha }}
|
||||
path: base
|
||||
fetch-depth: 1
|
||||
persist-credentials: false
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0
|
||||
with:
|
||||
@@ -64,45 +53,12 @@ jobs:
|
||||
|
||||
- name: Install frontend dependencies
|
||||
working-directory: frontend
|
||||
env:
|
||||
NPM_CONFIG_IGNORE_SCRIPTS: "true"
|
||||
run: npm ci --ignore-scripts --audit=false --fund=false
|
||||
run: npm ci
|
||||
|
||||
- name: Generate frontend license report (internal PR)
|
||||
if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork == false
|
||||
- name: Generate frontend license report
|
||||
working-directory: frontend
|
||||
env:
|
||||
PR_IS_FORK: "false"
|
||||
run: npm run generate-licenses
|
||||
|
||||
- name: Generate frontend license report (fork PRs, pinned)
|
||||
if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork == true
|
||||
env:
|
||||
NPM_CONFIG_IGNORE_SCRIPTS: "true"
|
||||
working-directory: frontend
|
||||
run: |
|
||||
mkdir -p src/assets
|
||||
npx --yes license-report --only=prod --output=json > src/assets/3rdPartyLicenses.json
|
||||
|
||||
- name: Postprocess with project script (BASE version)
|
||||
if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork == true
|
||||
env:
|
||||
PR_IS_FORK: "true"
|
||||
run: |
|
||||
node base/frontend/scripts/generate-licenses.js \
|
||||
--input frontend/src/assets/3rdPartyLicenses.json
|
||||
|
||||
- name: Copy postprocessed artifacts back (fork PRs)
|
||||
if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork == true
|
||||
run: |
|
||||
mkdir -p frontend/src/assets
|
||||
if [ -f "base/frontend/src/assets/3rdPartyLicenses.json" ]; then
|
||||
cp base/frontend/src/assets/3rdPartyLicenses.json frontend/src/assets/3rdPartyLicenses.json
|
||||
fi
|
||||
if [ -f "base/frontend/src/assets/license-warnings.json" ]; then
|
||||
cp base/frontend/src/assets/license-warnings.json frontend/src/assets/license-warnings.json
|
||||
fi
|
||||
|
||||
- name: Check for license warnings
|
||||
run: |
|
||||
if [ -f "frontend/src/assets/license-warnings.json" ]; then
|
||||
@@ -113,7 +69,7 @@ jobs:
|
||||
|
||||
# PR Event: Check licenses and comment on PR
|
||||
- name: Delete previous license check comments
|
||||
if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork == false
|
||||
if: github.event_name == 'pull_request'
|
||||
uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1
|
||||
with:
|
||||
github-token: ${{ steps.setup-bot.outputs.token }}
|
||||
@@ -145,28 +101,8 @@ jobs:
|
||||
});
|
||||
}
|
||||
|
||||
- name: Summarize results (fork PRs)
|
||||
if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork == true
|
||||
run: |
|
||||
{
|
||||
echo "## Frontend License Check"
|
||||
echo ""
|
||||
if [ "${LICENSE_WARNINGS_EXIST}" = "true" ]; then
|
||||
echo "❌ **Failed** – incompatible or unknown licenses found."
|
||||
if [ -f "frontend/src/assets/license-warnings.json" ]; then
|
||||
echo ""
|
||||
echo "### Warnings"
|
||||
jq -r '.warnings[] | "- \(.message)"' frontend/src/assets/license-warnings.json || true
|
||||
fi
|
||||
else
|
||||
echo "✅ **Passed** – no license warnings detected."
|
||||
fi
|
||||
echo ""
|
||||
echo "_Note: This is a fork PR. PR comments are disabled; use this summary._"
|
||||
} >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
- name: Comment on PR - License Check Results
|
||||
if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork == false
|
||||
if: github.event_name == 'pull_request'
|
||||
uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1
|
||||
with:
|
||||
github-token: ${{ steps.setup-bot.outputs.token }}
|
||||
|
||||
+15
-43
@@ -237,54 +237,34 @@ public class StampController {
|
||||
|
||||
PDRectangle pageSize = page.getMediaBox();
|
||||
float x, y;
|
||||
// Split the stampText into multiple lines
|
||||
String[] lines = stampText.split("\\r?\\n|\\\\n");
|
||||
|
||||
// Calculate dynamic line height based on font ascent and descent
|
||||
float ascent = font.getFontDescriptor().getAscent();
|
||||
float descent = font.getFontDescriptor().getDescent();
|
||||
float lineHeight = ((ascent - descent) / 1000) * fontSize;
|
||||
|
||||
// Compute a single pivot for the entire text block to avoid line-by-line wobble
|
||||
float capHeight = calculateTextCapHeight(font, fontSize);
|
||||
float blockHeight = Math.max(lineHeight, lineHeight * Math.max(1, lines.length));
|
||||
float maxWidth = 0f;
|
||||
for (String ln : lines) {
|
||||
maxWidth = Math.max(maxWidth, calculateTextWidth(ln, font, fontSize));
|
||||
}
|
||||
|
||||
if (overrideX >= 0 && overrideY >= 0) {
|
||||
// Use override values if provided
|
||||
x = overrideX;
|
||||
y = overrideY;
|
||||
} else {
|
||||
// Base positioning on the true multi-line block size
|
||||
x = calculatePositionX(pageSize, position, maxWidth, null, 0, null, margin);
|
||||
y = calculatePositionY(pageSize, position, blockHeight, margin);
|
||||
x = calculatePositionX(pageSize, position, fontSize, font, fontSize, stampText, margin);
|
||||
y =
|
||||
calculatePositionY(
|
||||
pageSize, position, calculateTextCapHeight(font, fontSize), margin);
|
||||
}
|
||||
// Split the stampText into multiple lines
|
||||
String[] lines = stampText.split("\\\\n");
|
||||
|
||||
// After anchoring the block, draw from the top line downward
|
||||
float adjustedX = x;
|
||||
float adjustedY = y;
|
||||
float pivotX = adjustedX + maxWidth / 2f;
|
||||
float pivotY = adjustedY + blockHeight / 2f;
|
||||
|
||||
// Apply rotation about the block center at the graphics state level
|
||||
contentStream.saveGraphicsState();
|
||||
contentStream.transform(Matrix.getTranslateInstance(pivotX, pivotY));
|
||||
contentStream.transform(Matrix.getRotateInstance(Math.toRadians(rotation), 0, 0));
|
||||
contentStream.transform(Matrix.getTranslateInstance(-pivotX, -pivotY));
|
||||
// Calculate dynamic line height based on font ascent and descent
|
||||
float ascent = font.getFontDescriptor().getAscent();
|
||||
float descent = font.getFontDescriptor().getDescent();
|
||||
float lineHeight = ((ascent - descent) / 1000) * fontSize;
|
||||
|
||||
contentStream.beginText();
|
||||
for (int i = 0; i < lines.length; i++) {
|
||||
String line = lines[i];
|
||||
// Start from top line: yTop = adjustedY + blockHeight - capHeight
|
||||
float yLine = adjustedY + blockHeight - capHeight - (i * lineHeight);
|
||||
contentStream.setTextMatrix(Matrix.getTranslateInstance(adjustedX, yLine));
|
||||
// Set the text matrix for each line with rotation
|
||||
contentStream.setTextMatrix(
|
||||
Matrix.getRotateInstance(Math.toRadians(rotation), x, y - (i * lineHeight)));
|
||||
contentStream.showText(line);
|
||||
}
|
||||
contentStream.endText();
|
||||
contentStream.restoreGraphicsState();
|
||||
}
|
||||
|
||||
private void addImageStamp(
|
||||
@@ -328,17 +308,9 @@ public class StampController {
|
||||
}
|
||||
|
||||
contentStream.saveGraphicsState();
|
||||
// Rotate and scale about the center of the image
|
||||
float centerX = x + (desiredPhysicalWidth / 2f);
|
||||
float centerY = y + (desiredPhysicalHeight / 2f);
|
||||
contentStream.transform(Matrix.getTranslateInstance(centerX, centerY));
|
||||
contentStream.transform(Matrix.getTranslateInstance(x, y));
|
||||
contentStream.transform(Matrix.getRotateInstance(Math.toRadians(rotation), 0, 0));
|
||||
contentStream.drawImage(
|
||||
xobject,
|
||||
-desiredPhysicalWidth / 2f,
|
||||
-desiredPhysicalHeight / 2f,
|
||||
desiredPhysicalWidth,
|
||||
desiredPhysicalHeight);
|
||||
contentStream.drawImage(xobject, 0, 0, desiredPhysicalWidth, desiredPhysicalHeight);
|
||||
contentStream.restoreGraphicsState();
|
||||
}
|
||||
|
||||
|
||||
@@ -6,11 +6,6 @@ http {
|
||||
include /etc/nginx/mime.types;
|
||||
default_type application/octet-stream;
|
||||
|
||||
# Add .mjs MIME type mapping
|
||||
types {
|
||||
text/javascript mjs;
|
||||
}
|
||||
|
||||
# Gzip compression
|
||||
gzip on;
|
||||
gzip_vary on;
|
||||
@@ -95,15 +90,7 @@ http {
|
||||
proxy_set_header X-Forwarded-Port $server_port;
|
||||
}
|
||||
|
||||
# Serve .mjs files with correct MIME type (must come before general static assets)
|
||||
location ~* \.mjs$ {
|
||||
try_files $uri =404;
|
||||
add_header Content-Type "text/javascript; charset=utf-8" always;
|
||||
expires 1y;
|
||||
add_header Cache-Control "public, immutable";
|
||||
}
|
||||
|
||||
# Cache other static assets
|
||||
# Cache static assets
|
||||
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
|
||||
expires 1y;
|
||||
add_header Cache-Control "public, immutable";
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
<html lang="en-GB">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<base href="%BASE_URL%" />
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="theme-color" content="#000000" />
|
||||
|
||||
Generated
+3572
-3028
File diff suppressed because it is too large
Load Diff
+59
-76
@@ -5,49 +5,52 @@
|
||||
"license": "SEE LICENSE IN https://raw.githubusercontent.com/Stirling-Tools/Stirling-PDF/refs/heads/main/proprietary/LICENSE",
|
||||
"proxy": "http://localhost:8080",
|
||||
"dependencies": {
|
||||
"@atlaskit/pragmatic-drag-and-drop": "^1.7.7",
|
||||
"@embedpdf/core": "^1.2.1",
|
||||
"@embedpdf/engines": "^1.2.1",
|
||||
"@embedpdf/plugin-interaction-manager": "^1.2.1",
|
||||
"@embedpdf/plugin-loader": "^1.2.1",
|
||||
"@embedpdf/plugin-pan": "^1.2.1",
|
||||
"@embedpdf/plugin-render": "^1.2.1",
|
||||
"@embedpdf/plugin-rotate": "^1.2.1",
|
||||
"@embedpdf/plugin-scroll": "^1.2.1",
|
||||
"@embedpdf/plugin-search": "^1.2.1",
|
||||
"@embedpdf/plugin-selection": "^1.2.1",
|
||||
"@embedpdf/plugin-spread": "^1.2.1",
|
||||
"@embedpdf/plugin-thumbnail": "^1.2.1",
|
||||
"@embedpdf/plugin-tiling": "^1.2.1",
|
||||
"@embedpdf/plugin-viewport": "^1.2.1",
|
||||
"@embedpdf/plugin-zoom": "^1.2.1",
|
||||
"@atlaskit/pragmatic-drag-and-drop": "^1.7.4",
|
||||
"@embedpdf/core": "^1.1.1",
|
||||
"@embedpdf/engines": "^1.1.1",
|
||||
"@embedpdf/plugin-interaction-manager": "^1.1.1",
|
||||
"@embedpdf/plugin-loader": "^1.1.1",
|
||||
"@embedpdf/plugin-pan": "^1.1.1",
|
||||
"@embedpdf/plugin-render": "^1.1.1",
|
||||
"@embedpdf/plugin-rotate": "^1.1.1",
|
||||
"@embedpdf/plugin-scroll": "^1.1.1",
|
||||
"@embedpdf/plugin-search": "^1.1.1",
|
||||
"@embedpdf/plugin-selection": "^1.1.1",
|
||||
"@embedpdf/plugin-spread": "^1.1.1",
|
||||
"@embedpdf/plugin-thumbnail": "^1.1.1",
|
||||
"@embedpdf/plugin-tiling": "^1.1.1",
|
||||
"@embedpdf/plugin-viewport": "^1.1.1",
|
||||
"@embedpdf/plugin-zoom": "^1.1.1",
|
||||
"@emotion/react": "^11.14.0",
|
||||
"@emotion/styled": "^11.14.1",
|
||||
"@iconify/react": "^6.0.2",
|
||||
"@mantine/core": "8.3.1",
|
||||
"@mantine/dates": "8.3.1",
|
||||
"@mantine/dropzone": "8.3.1",
|
||||
"@mantine/hooks": "8.3.1",
|
||||
"@mui/icons-material": "^7.3.2",
|
||||
"@mui/material": "^7.3.2",
|
||||
"@tailwindcss/postcss": "^4.1.13",
|
||||
"@emotion/styled": "^11.14.0",
|
||||
"@iconify/react": "^6.0.0",
|
||||
"@mantine/core": "^8.0.1",
|
||||
"@mantine/dates": "^8.0.1",
|
||||
"@mantine/dropzone": "^8.0.1",
|
||||
"@mantine/hooks": "^8.0.1",
|
||||
"@mui/icons-material": "^7.1.0",
|
||||
"@mui/material": "^7.1.0",
|
||||
"@tailwindcss/postcss": "^4.1.8",
|
||||
"@tanstack/react-virtual": "^3.13.12",
|
||||
"@testing-library/dom": "^10.4.0",
|
||||
"@testing-library/jest-dom": "^6.6.3",
|
||||
"@testing-library/react": "^16.3.0",
|
||||
"@testing-library/user-event": "^13.5.0",
|
||||
"autoprefixer": "^10.4.21",
|
||||
"axios": "^1.12.2",
|
||||
"i18next": "^25.5.2",
|
||||
"i18next-browser-languagedetector": "^8.2.0",
|
||||
"axios": "^1.9.0",
|
||||
"i18next": "^25.2.1",
|
||||
"i18next-browser-languagedetector": "^8.1.0",
|
||||
"i18next-http-backend": "^3.0.2",
|
||||
"jszip": "^3.10.1",
|
||||
"license-report": "^6.8.0",
|
||||
"pdf-lib": "^1.17.1",
|
||||
"pdfjs-dist": "^5.4.149",
|
||||
"posthog-js": "^1.268.0",
|
||||
"react": "^19.1.1",
|
||||
"react-dom": "^19.1.1",
|
||||
"react-i18next": "^15.7.3",
|
||||
"react-router-dom": "^7.9.1",
|
||||
"tailwindcss": "^4.1.13",
|
||||
"web-vitals": "^5.1.0"
|
||||
"pdfjs-dist": "^3.11.174",
|
||||
"posthog-js": "^1.261.0",
|
||||
"react": "^19.1.0",
|
||||
"react-dom": "^19.1.0",
|
||||
"react-i18next": "^15.5.2",
|
||||
"react-router-dom": "^7.6.0",
|
||||
"tailwindcss": "^4.1.8",
|
||||
"web-vitals": "^2.1.4"
|
||||
},
|
||||
"scripts": {
|
||||
"predev": "npm run generate-icons",
|
||||
@@ -67,17 +70,12 @@
|
||||
"test:coverage": "vitest --coverage",
|
||||
"test:e2e": "playwright test",
|
||||
"test:e2e:ui": "playwright test --ui",
|
||||
"test:e2e:install": "playwright install",
|
||||
"update:minor": "npm outdated || npm update && npm audit fix && npm test",
|
||||
"update:major": "npx npm-check-updates -u && npm install",
|
||||
"update:interactive": "npx npm-check-updates -i",
|
||||
"update:minor-strict": "npx npm-check-updates -u --target minor && npm install"
|
||||
"test:e2e:install": "playwright install"
|
||||
},
|
||||
"eslintConfig": {
|
||||
"extends": [
|
||||
"eslint:recommended",
|
||||
"plugin:@typescript-eslint/recommended",
|
||||
"plugin:react-hooks/recommended"
|
||||
"react-app",
|
||||
"react-app/jest"
|
||||
]
|
||||
},
|
||||
"browserslist": {
|
||||
@@ -93,41 +91,26 @@
|
||||
]
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.36.0",
|
||||
"@iconify-json/material-symbols": "^1.2.37",
|
||||
"@iconify/utils": "^3.0.2",
|
||||
"@playwright/test": "^1.55.0",
|
||||
"@testing-library/dom": "^10.4.1",
|
||||
"@testing-library/jest-dom": "^6.8.0",
|
||||
"@testing-library/react": "^16.3.0",
|
||||
"@testing-library/user-event": "^14.6.1",
|
||||
"@types/node": "^24.5.2",
|
||||
"@types/react": "^19.1.13",
|
||||
"@types/react-dom": "^19.1.9",
|
||||
"@typescript-eslint/eslint-plugin": "^8.44.1",
|
||||
"@typescript-eslint/parser": "^8.44.1",
|
||||
"@vitejs/plugin-react-swc": "^4.1.0",
|
||||
"@vitest/coverage-v8": "^3.2.4",
|
||||
"eslint": "^9.36.0",
|
||||
"eslint-plugin-react-hooks": "^5.2.0",
|
||||
"jsdom": "^27.0.0",
|
||||
"@eslint/js": "^9.34.0",
|
||||
"@iconify-json/material-symbols": "^1.2.33",
|
||||
"@iconify/utils": "^3.0.1",
|
||||
"@playwright/test": "^1.40.0",
|
||||
"@types/node": "^24.2.1",
|
||||
"@types/react": "^19.1.4",
|
||||
"@types/react-dom": "^19.1.5",
|
||||
"@vitejs/plugin-react": "^4.5.0",
|
||||
"@vitest/coverage-v8": "^1.0.0",
|
||||
"eslint": "^9.34.0",
|
||||
"jsdom": "^23.0.0",
|
||||
"license-checker": "^25.0.1",
|
||||
"madge": "^8.0.0",
|
||||
"postcss": "^8.5.6",
|
||||
"postcss": "^8.5.3",
|
||||
"postcss-cli": "^11.0.1",
|
||||
"postcss-preset-mantine": "^1.18.0",
|
||||
"postcss-preset-mantine": "^1.17.0",
|
||||
"postcss-simple-vars": "^7.0.1",
|
||||
"typescript": "^5.9.2",
|
||||
"typescript-eslint": "^8.44.1",
|
||||
"vite": "^7.1.7",
|
||||
"vitest": "^3.2.4"
|
||||
},
|
||||
"depcheck": {
|
||||
"ignoreMatches": [
|
||||
"@emotion/*",
|
||||
"tailwindcss",
|
||||
"@testing-library/user-event",
|
||||
"@vitest/coverage-v8"
|
||||
]
|
||||
"typescript-eslint": "^8.42.0",
|
||||
"vite": "^6.3.5",
|
||||
"vitest": "^1.0.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,7 +145,6 @@
|
||||
"noFileSelected": "No file selected. Please upload one.",
|
||||
"legal": {
|
||||
"privacy": "Privacy Policy",
|
||||
"iAgreeToThe": "I agree to all of the",
|
||||
"terms": "Terms and Conditions",
|
||||
"accessibility": "Accessibility",
|
||||
"cookie": "Cookie Policy",
|
||||
@@ -2383,7 +2382,6 @@
|
||||
"tags": "Stamp, Add image, center image, Watermark, PDF, Embed, Customize,Customise",
|
||||
"header": "Stamp PDF",
|
||||
"title": "Stamp PDF",
|
||||
"stampSetup": "Stamp Setup",
|
||||
"stampType": "Stamp Type",
|
||||
"stampText": "Stamp Text",
|
||||
"stampImage": "Stamp Image",
|
||||
@@ -2396,8 +2394,7 @@
|
||||
"overrideY": "Override Y Coordinate",
|
||||
"customMargin": "Custom Margin",
|
||||
"customColor": "Custom Text Colour",
|
||||
"submit": "Submit",
|
||||
"noStampSelected": "No stamp selected. Return to Step 1."
|
||||
"submit": "Submit"
|
||||
},
|
||||
"removeImagePdf": {
|
||||
"tags": "Remove Image,Page operations,Back end,server side"
|
||||
@@ -2476,8 +2473,6 @@
|
||||
"title": "Sign in",
|
||||
"header": "Sign in",
|
||||
"signin": "Sign in",
|
||||
"signInWith": "Sign in with",
|
||||
"signInAnonymously": "Sign Up as a Guest",
|
||||
"rememberme": "Remember me",
|
||||
"invalid": "Invalid username or password.",
|
||||
"locked": "Your account has been locked.",
|
||||
@@ -2496,54 +2491,7 @@
|
||||
"alreadyLoggedIn": "You are already logged in to",
|
||||
"alreadyLoggedIn2": "devices. Please log out of the devices and try again.",
|
||||
"toManySessions": "You have too many active sessions",
|
||||
"logoutMessage": "You have been logged out.",
|
||||
"youAreLoggedIn": "You are logged in!",
|
||||
"email": "Email",
|
||||
"password": "Password",
|
||||
"enterEmail": "Enter your email",
|
||||
"enterPassword": "Enter your password",
|
||||
"loggingIn": "Logging In...",
|
||||
"signingIn": "Signing in...",
|
||||
"login": "Login",
|
||||
"or": "Or",
|
||||
"useMagicLink": "Use magic link instead",
|
||||
"enterEmailForMagicLink": "Enter your email for magic link",
|
||||
"sending": "Sending…",
|
||||
"sendMagicLink": "Send Magic Link",
|
||||
"cancel": "Cancel",
|
||||
"dontHaveAccount": "Don't have an account? Sign up",
|
||||
"home": "Home",
|
||||
"debug": "Debug",
|
||||
"signOut": "Sign Out",
|
||||
"pleaseEnterBoth": "Please enter both email and password",
|
||||
"pleaseEnterEmail": "Please enter your email address",
|
||||
"magicLinkSent": "Magic link sent to {{email}}! Check your email and click the link to sign in.",
|
||||
"passwordResetSent": "Password reset link sent to {{email}}! Check your email and follow the instructions.",
|
||||
"failedToSignIn": "Failed to sign in with {{provider}}: {{message}}",
|
||||
"unexpectedError": "Unexpected error: {{message}}"
|
||||
},
|
||||
"signup": {
|
||||
"title": "Create an account",
|
||||
"subtitle": "Join Stirling PDF to get started",
|
||||
"name": "Name",
|
||||
"email": "Email",
|
||||
"password": "Password",
|
||||
"confirmPassword": "Confirm password",
|
||||
"enterName": "Enter your name",
|
||||
"enterEmail": "Enter your email",
|
||||
"enterPassword": "Enter your password",
|
||||
"confirmPasswordPlaceholder": "Confirm password",
|
||||
"or": "or",
|
||||
"creatingAccount": "Creating Account...",
|
||||
"signUp": "Sign Up",
|
||||
"alreadyHaveAccount": "Already have an account? Sign in",
|
||||
"pleaseFillAllFields": "Please fill in all fields",
|
||||
"passwordsDoNotMatch": "Passwords do not match",
|
||||
"passwordTooShort": "Password must be at least 6 characters long",
|
||||
"invalidEmail": "Please enter a valid email address",
|
||||
"checkEmailConfirmation": "Check your email for a confirmation link to complete your registration.",
|
||||
"accountCreatedSuccessfully": "Account created successfully! You can now sign in.",
|
||||
"unexpectedError": "Unexpected error: {{message}}"
|
||||
"logoutMessage": "You have been logged out."
|
||||
},
|
||||
"pdfToSinglePage": {
|
||||
"title": "PDF To Single Page",
|
||||
@@ -2601,28 +2549,6 @@
|
||||
"grayscale": {
|
||||
"label": "Apply Grayscale for Compression"
|
||||
},
|
||||
"tooltip": {
|
||||
"header": {
|
||||
"title": "Compress Settings Overview"
|
||||
},
|
||||
"description": {
|
||||
"title": "Description",
|
||||
"text": "Compression is an easy way to reduce your file size. Pick File Size to enter a target size and have us adjust quality for you. Pick Quality to set compression strength manually."
|
||||
},
|
||||
"qualityAdjustment": {
|
||||
"title": "Quality Adjustment",
|
||||
"text": "Drag the slider to adjust the compression strength. Lower values (1-3) preserve quality but result in larger files. Higher values (7-9) shrink the file more but reduce image clarity.",
|
||||
"bullet1": "Lower values preserve quality",
|
||||
"bullet2": "Higher values reduce file size"
|
||||
},
|
||||
"grayscale": {
|
||||
"title": "Grayscale",
|
||||
"text": "Select this option to convert all images to black and white, which can significantly reduce file size especially for scanned PDFs or image-heavy documents."
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
"failed": "An error occurred while compressing the PDF."
|
||||
},
|
||||
"selectText": {
|
||||
"1": {
|
||||
"_value": "Compression Settings",
|
||||
@@ -2871,16 +2797,6 @@
|
||||
"rotateRight": "Rotate Right",
|
||||
"toggleSidebar": "Toggle Sidebar"
|
||||
},
|
||||
"search": {
|
||||
"title": "Search PDF",
|
||||
"placeholder": "Enter search term..."
|
||||
},
|
||||
"guestBanner": {
|
||||
"title": "You're using Stirling PDF as a guest!",
|
||||
"message": "Create a free account to save your work, access more features, and support the project.",
|
||||
"dismiss": "Dismiss banner",
|
||||
"signUp": "Sign Up Free"
|
||||
},
|
||||
"toolPicker": {
|
||||
"searchPlaceholder": "Search tools...",
|
||||
"noToolsFound": "No tools found",
|
||||
@@ -3245,63 +3161,5 @@
|
||||
"processImages": "Process Images",
|
||||
"processImagesDesc": "Converts multiple image files into a single PDF document, then applies OCR technology to extract searchable text from the images."
|
||||
}
|
||||
},
|
||||
"common": {
|
||||
"copy": "Copy",
|
||||
"copied": "Copied!",
|
||||
"refresh": "Refresh",
|
||||
"retry": "Retry",
|
||||
"remaining": "remaining",
|
||||
"used": "used",
|
||||
"available": "available",
|
||||
"cancel": "Cancel"
|
||||
},
|
||||
"config": {
|
||||
"account": {
|
||||
"overview": {
|
||||
"title": "Account Settings",
|
||||
"manageAccountPreferences": "Manage your account preferences",
|
||||
"guestDescription": "You are signed in as a guest. Consider upgrading your account above."
|
||||
},
|
||||
"upgrade": {
|
||||
"title": "Upgrade Guest Account",
|
||||
"description": "Link your account to preserve your history and access more features!",
|
||||
"socialLogin": "Upgrade with Social Account",
|
||||
"linkWith": "Link with",
|
||||
"emailPassword": "or enter your email & password",
|
||||
"email": "Email",
|
||||
"emailPlaceholder": "Enter your email",
|
||||
"password": "Password (optional)",
|
||||
"passwordPlaceholder": "Set a password",
|
||||
"passwordNote": "Leave empty to use email verification only",
|
||||
"upgradeButton": "Upgrade Account"
|
||||
}
|
||||
},
|
||||
"apiKeys": {
|
||||
"description": "Your API key for accessing Stirling's suite of PDF tools. Copy it to your project or refresh to generate a new one.",
|
||||
"publicKeyAriaLabel": "Public API key",
|
||||
"copyKeyAriaLabel": "Copy API key",
|
||||
"refreshAriaLabel": "Refresh API key",
|
||||
"includedCredits": "Included credits",
|
||||
"purchasedCredits": "Purchased credits",
|
||||
"totalCredits": "Total Credits",
|
||||
"chartAriaLabel": "Credits usage: included {{includedUsed}} of {{includedTotal}}, purchased {{purchasedUsed}} of {{purchasedTotal}}",
|
||||
"nextReset": "Next Reset",
|
||||
"lastApiUse": "Last API Use",
|
||||
"overlayMessage": "Generate a key to see credits and available credits",
|
||||
"label": "API Key",
|
||||
"guestInfo": "Guest users do not receive API keys. Create an account to get an API key you can use in your applications.",
|
||||
"goToAccount": "Go to Account",
|
||||
"refreshModal": {
|
||||
"title": "Refresh API Keys",
|
||||
"warning": "⚠️ Warning: This action will generate new API keys and make your previous keys invalid.",
|
||||
"impact": "Any applications or services currently using these keys will stop working until you update them with the new keys.",
|
||||
"confirmPrompt": "Are you sure you want to continue?",
|
||||
"confirmCta": "Refresh Keys"
|
||||
},
|
||||
"generateError": "We couldn't generate your API key."
|
||||
}
|
||||
},
|
||||
"termsAndConditions": "Terms & Conditions",
|
||||
"logOut": "Log out"
|
||||
}
|
||||
}
|
||||
@@ -1470,7 +1470,6 @@
|
||||
"tags": "Stamp, Add image, center image, Watermark, PDF, Embed, Customize",
|
||||
"header": "Stamp PDF",
|
||||
"title": "Stamp PDF",
|
||||
"stampSetup": "Stamp Setup",
|
||||
"stampType": "Stamp Type",
|
||||
"stampText": "Stamp Text",
|
||||
"stampImage": "Stamp Image",
|
||||
@@ -1483,8 +1482,7 @@
|
||||
"overrideY": "Override Y Coordinate",
|
||||
"customMargin": "Custom Margin",
|
||||
"customColor": "Custom Text Color",
|
||||
"submit": "Submit",
|
||||
"noStampSelected": "No stamp selected. Return to Step 1."
|
||||
"submit": "Submit"
|
||||
},
|
||||
"removeImagePdf": {
|
||||
"tags": "Remove Image,Page operations,Back end,server side"
|
||||
|
||||
File diff suppressed because one or more lines are too long
Vendored
+58353
File diff suppressed because one or more lines are too long
@@ -1,17 +1,8 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { execSync } from 'node:child_process';
|
||||
import { existsSync, mkdirSync, writeFileSync, readFileSync } from 'node:fs';
|
||||
import * as path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import { argv } from 'node:process';
|
||||
const inputIdx = argv.indexOf('--input');
|
||||
const INPUT_FILE = inputIdx > -1 ? argv[inputIdx + 1] : null;
|
||||
const POSTPROCESS_ONLY = !!INPUT_FILE;
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
const { execSync } = require('child_process');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
/**
|
||||
* Generate 3rd party licenses for frontend dependencies
|
||||
@@ -23,54 +14,59 @@ const PACKAGE_JSON = path.join(__dirname, '..', 'package.json');
|
||||
|
||||
// Ensure the output directory exists
|
||||
const outputDir = path.dirname(OUTPUT_FILE);
|
||||
if (!existsSync(outputDir)) {
|
||||
mkdirSync(outputDir, { recursive: true });
|
||||
if (!fs.existsSync(outputDir)) {
|
||||
fs.mkdirSync(outputDir, { recursive: true });
|
||||
}
|
||||
|
||||
console.log('🔍 Generating frontend license report...');
|
||||
|
||||
try {
|
||||
// Safety guard: don't run this script on fork PRs (workflow setzt PR_IS_FORK)
|
||||
if (process.env.PR_IS_FORK === 'true' && !POSTPROCESS_ONLY) {
|
||||
console.error('Fork PR detected: only --input (postprocess-only) mode is allowed.');
|
||||
process.exit(2);
|
||||
// Install license-checker if not present
|
||||
try {
|
||||
require.resolve('license-checker');
|
||||
} catch {
|
||||
console.log('📦 Installing license-checker...');
|
||||
execSync('npm install --save-dev license-checker', { stdio: 'inherit' });
|
||||
}
|
||||
|
||||
// Generate license report using license-checker (more reliable)
|
||||
const licenseReport = execSync('npx license-checker --production --json', {
|
||||
encoding: 'utf8',
|
||||
cwd: path.dirname(PACKAGE_JSON)
|
||||
});
|
||||
|
||||
let licenseData;
|
||||
// Generate license report using pinned license-checker; disable lifecycle scripts
|
||||
if (POSTPROCESS_ONLY) {
|
||||
if (!INPUT_FILE || !existsSync(INPUT_FILE)) {
|
||||
console.error('❌ --input file missing or not found');
|
||||
try {
|
||||
licenseData = JSON.parse(licenseReport);
|
||||
} catch (parseError) {
|
||||
console.error('❌ Failed to parse license data:', parseError.message);
|
||||
console.error('Raw output:', licenseReport.substring(0, 500) + '...');
|
||||
process.exit(1);
|
||||
}
|
||||
licenseData = JSON.parse(readFileSync(INPUT_FILE, 'utf8'));
|
||||
} else {
|
||||
const licenseReport = execSync(
|
||||
// 'npx --yes license-checker@25.0.1 --production --json',
|
||||
'npx --yes license-report --only=prod --output=json',
|
||||
{
|
||||
encoding: 'utf8',
|
||||
cwd: path.dirname(PACKAGE_JSON),
|
||||
env: { ...process.env, NPM_CONFIG_IGNORE_SCRIPTS: 'true' }
|
||||
}
|
||||
);
|
||||
try {
|
||||
licenseData = JSON.parse(licenseReport);
|
||||
} catch (parseError) {
|
||||
console.error('❌ Failed to parse license data:', parseError.message);
|
||||
console.error('Raw output:', licenseReport.substring(0, 500) + '...');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
if (!Array.isArray(licenseData)) {
|
||||
if (!licenseData || typeof licenseData !== 'object') {
|
||||
console.error('❌ Invalid license data structure');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Convert license-checker format to array
|
||||
const licenseArray = licenseData.map(dep => {
|
||||
let licenseType = dep.licenseType;
|
||||
const licenseArray = Object.entries(licenseData).map(([key, value]) => {
|
||||
let name, version;
|
||||
|
||||
// Handle scoped packages like @mantine/core@1.0.0
|
||||
if (key.startsWith('@')) {
|
||||
const parts = key.split('@');
|
||||
name = `@${parts[1]}`;
|
||||
version = parts[2];
|
||||
} else {
|
||||
// Handle regular packages like react@18.0.0
|
||||
const lastAtIndex = key.lastIndexOf('@');
|
||||
name = key.substring(0, lastAtIndex);
|
||||
version = key.substring(lastAtIndex + 1);
|
||||
}
|
||||
|
||||
// Normalize license types for edge cases
|
||||
let licenseType = value.licenses;
|
||||
|
||||
// Handle missing or null licenses
|
||||
if (!licenseType || licenseType === null || licenseType === undefined) {
|
||||
@@ -92,17 +88,13 @@ try {
|
||||
licenseType = 'Unknown';
|
||||
}
|
||||
|
||||
if ( "posthog-js" === dep.name && licenseType.startsWith("SEE LICENSE IN LICENSE")) {
|
||||
licenseType = "SEE LICENSE IN LICENSE https://github.com/PostHog/posthog-js/blob/main/LICENSE";
|
||||
}
|
||||
|
||||
return {
|
||||
name: dep.name,
|
||||
version: dep.installedVersion || dep.definedVersion || dep.remoteVersion || 'unknown',
|
||||
name: name,
|
||||
version: version || value.version || 'unknown',
|
||||
licenseType: licenseType,
|
||||
repository: dep.link,
|
||||
url: dep.link,
|
||||
link: dep.link
|
||||
repository: value.repository,
|
||||
url: value.url,
|
||||
link: value.licenseUrl
|
||||
};
|
||||
});
|
||||
|
||||
@@ -161,7 +153,7 @@ try {
|
||||
|
||||
// Write license warnings to a separate file for CI/CD
|
||||
const warningsFile = path.join(__dirname, '..', 'src', 'assets', 'license-warnings.json');
|
||||
writeFileSync(warningsFile, JSON.stringify({
|
||||
fs.writeFileSync(warningsFile, JSON.stringify({
|
||||
warnings: problematicLicenses,
|
||||
generated: new Date().toISOString()
|
||||
}, null, 2));
|
||||
@@ -171,7 +163,7 @@ try {
|
||||
}
|
||||
|
||||
// Write to file
|
||||
writeFileSync(OUTPUT_FILE, JSON.stringify(transformedData, null, 4));
|
||||
fs.writeFileSync(OUTPUT_FILE, JSON.stringify(transformedData, null, 4));
|
||||
|
||||
console.log(`✅ License report generated successfully!`);
|
||||
console.log(`📄 Found ${transformedData.dependencies.length} dependencies`);
|
||||
@@ -282,8 +274,7 @@ function checkLicenseCompatibility(licenseSummary, licenseArray) {
|
||||
'MIT', 'MIT*', 'Apache-2.0', 'Apache License 2.0', 'BSD-2-Clause', 'BSD-3-Clause', 'BSD',
|
||||
'ISC', 'CC0-1.0', 'Public Domain', 'Unlicense', '0BSD', 'BlueOak-1.0.0',
|
||||
'Zlib', 'Artistic-2.0', 'Python-2.0', 'Ruby', 'MPL-2.0', 'CC-BY-4.0',
|
||||
'SEE LICENSE IN https://raw.githubusercontent.com/Stirling-Tools/Stirling-PDF/refs/heads/main/proprietary/LICENSE',
|
||||
'SEE LICENSE IN LICENSE https://github.com/PostHog/posthog-js/blob/main/LICENSE'
|
||||
'SEE LICENSE IN https://raw.githubusercontent.com/Stirling-Tools/Stirling-PDF/refs/heads/main/proprietary/LICENSE'
|
||||
]);
|
||||
|
||||
// Helper function to normalize license names for comparison
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -4,6 +4,7 @@ import { useToolWorkflow } from '../../contexts/ToolWorkflowContext';
|
||||
import { useFileHandler } from '../../hooks/useFileHandler';
|
||||
import { useFileState } from '../../contexts/FileContext';
|
||||
import { useNavigationState, useNavigationActions } from '../../contexts/NavigationContext';
|
||||
import { useToolManagement } from '../../hooks/useToolManagement';
|
||||
import './Workbench.css';
|
||||
|
||||
import TopControls from '../shared/TopControls';
|
||||
@@ -38,8 +39,8 @@ export default function Workbench() {
|
||||
// Get navigation state - this is the source of truth
|
||||
const { selectedTool: selectedToolId } = useNavigationState();
|
||||
|
||||
// Get tool registry from context (instead of direct hook call)
|
||||
const { toolRegistry } = useToolWorkflow();
|
||||
// Get tool registry to look up selected tool
|
||||
const { toolRegistry } = useToolManagement();
|
||||
const selectedTool = selectedToolId ? toolRegistry[selectedToolId] : null;
|
||||
const { addFiles } = useFileHandler();
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { Button, Group, Stack, Text } from "@mantine/core";
|
||||
import FitText from "./FitText";
|
||||
|
||||
export interface ButtonOption<T> {
|
||||
value: T;
|
||||
@@ -14,8 +13,6 @@ interface ButtonSelectorProps<T> {
|
||||
label?: string;
|
||||
disabled?: boolean;
|
||||
fullWidth?: boolean;
|
||||
buttonClassName?: string;
|
||||
textClassName?: string;
|
||||
}
|
||||
|
||||
const ButtonSelector = <T extends string | number>({
|
||||
@@ -25,8 +22,6 @@ const ButtonSelector = <T extends string | number>({
|
||||
label = undefined,
|
||||
disabled = false,
|
||||
fullWidth = true,
|
||||
buttonClassName,
|
||||
textClassName,
|
||||
}: ButtonSelectorProps<T>) => {
|
||||
return (
|
||||
<Stack gap='var(--mantine-spacing-sm)'>
|
||||
@@ -46,7 +41,6 @@ const ButtonSelector = <T extends string | number>({
|
||||
color={value === option.value ? 'var(--color-primary-500)' : 'var(--text-muted)'}
|
||||
onClick={() => onChange(option.value)}
|
||||
disabled={disabled || option.disabled}
|
||||
className={buttonClassName}
|
||||
style={{
|
||||
flex: fullWidth ? 1 : undefined,
|
||||
height: 'auto',
|
||||
@@ -57,13 +51,7 @@ const ButtonSelector = <T extends string | number>({
|
||||
paddingBottom: '0.5rem'
|
||||
}}
|
||||
>
|
||||
<FitText
|
||||
text={option.label}
|
||||
lines={1}
|
||||
minimumFontScale={0.5}
|
||||
fontSize={10}
|
||||
className={textClassName}
|
||||
/>
|
||||
{option.label}
|
||||
</Button>
|
||||
))}
|
||||
</Group>
|
||||
|
||||
@@ -5,7 +5,6 @@ import LocalIcon from './LocalIcon';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useFileHandler } from '../../hooks/useFileHandler';
|
||||
import { useFilesModalContext } from '../../contexts/FilesModalContext';
|
||||
import { BASE_PATH } from '../../constants/app';
|
||||
|
||||
const LandingPage = () => {
|
||||
const { addFiles } = useFileHandler();
|
||||
@@ -73,7 +72,7 @@ const LandingPage = () => {
|
||||
}}
|
||||
>
|
||||
<img
|
||||
src={colorScheme === 'dark' ? `${BASE_PATH}/branding/StirlingPDFLogoNoTextDark.svg` : `${BASE_PATH}/branding/StirlingPDFLogoNoTextLight.svg`}
|
||||
src={colorScheme === 'dark' ? '/branding/StirlingPDFLogoNoTextDark.svg' : '/branding/StirlingPDFLogoNoTextLight.svg'}
|
||||
alt="Stirling PDF Logo"
|
||||
style={{
|
||||
height: 'auto',
|
||||
@@ -99,7 +98,7 @@ const LandingPage = () => {
|
||||
{/* Stirling PDF Branding */}
|
||||
<Group gap="xs" align="center">
|
||||
<img
|
||||
src={colorScheme === 'dark' ? `${BASE_PATH}/branding/StirlingPDFLogoWhiteText.svg` : `${BASE_PATH}/branding/StirlingPDFLogoGreyText.svg`}
|
||||
src={colorScheme === 'dark' ? '/branding/StirlingPDFLogoWhiteText.svg' : '/branding/StirlingPDFLogoGreyText.svg'}
|
||||
alt="Stirling PDF"
|
||||
style={{ height: '2.2rem', width: 'auto' }}
|
||||
/>
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
import React from 'react';
|
||||
import styles from './ObscuredOverlay/ObscuredOverlay.module.css';
|
||||
|
||||
type ObscuredOverlayProps = {
|
||||
obscured: boolean;
|
||||
overlayMessage?: React.ReactNode;
|
||||
buttonText?: string;
|
||||
onButtonClick?: () => void;
|
||||
children: React.ReactNode;
|
||||
// Optional border radius for the overlay container. If undefined, no radius is applied.
|
||||
borderRadius?: string | number;
|
||||
};
|
||||
|
||||
export default function ObscuredOverlay({
|
||||
obscured,
|
||||
overlayMessage,
|
||||
buttonText,
|
||||
onButtonClick,
|
||||
children,
|
||||
borderRadius,
|
||||
}: ObscuredOverlayProps) {
|
||||
return (
|
||||
<div className={styles.container}>
|
||||
{children}
|
||||
{obscured && (
|
||||
<div
|
||||
className={styles.overlay}
|
||||
style={{
|
||||
...(borderRadius !== undefined ? { borderRadius } : {}),
|
||||
}}
|
||||
>
|
||||
<div className={styles.overlayContent}>
|
||||
{overlayMessage && (
|
||||
<div className={styles.overlayMessage}>
|
||||
{overlayMessage}
|
||||
</div>
|
||||
)}
|
||||
{buttonText && onButtonClick && (
|
||||
<button type="button" onClick={onButtonClick} className={styles.overlayButton}>
|
||||
{buttonText}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
.container {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.overlay {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
text-align: center;
|
||||
padding: 16px;
|
||||
color: #ffffff;
|
||||
font-weight: 600;
|
||||
background: rgba(16, 18, 27, 0.55);
|
||||
backdrop-filter: blur(6px);
|
||||
-webkit-backdrop-filter: blur(6px);
|
||||
border: 1px solid rgba(255, 255, 255, 0.06);
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
.overlayContent {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.overlayMessage {
|
||||
color: #ffffff;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.overlayButton {
|
||||
padding: 8px 12px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.12);
|
||||
background: rgba(255, 255, 255, 0.06);
|
||||
color: #ffffff;
|
||||
cursor: pointer;
|
||||
}
|
||||
@@ -6,7 +6,6 @@ import { useTooltipPosition } from '../../hooks/useTooltipPosition';
|
||||
import { TooltipTip } from '../../types/tips';
|
||||
import { TooltipContent } from './tooltip/TooltipContent';
|
||||
import { useSidebarContext } from '../../contexts/SidebarContext';
|
||||
import { BASE_PATH } from '../../constants/app';
|
||||
import styles from './tooltip/Tooltip.module.css';
|
||||
|
||||
export interface TooltipProps {
|
||||
@@ -329,7 +328,7 @@ export const Tooltip: React.FC<TooltipProps> = ({
|
||||
<div className={styles['tooltip-logo']}>
|
||||
{header.logo || (
|
||||
<img
|
||||
src={`${BASE_PATH}/logo-tooltip.svg`}
|
||||
src="/logo-tooltip.svg"
|
||||
alt="Stirling PDF"
|
||||
style={{ width: '1.4rem', height: '1.4rem', display: 'block' }}
|
||||
/>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { Suspense } from "react";
|
||||
import { useToolWorkflow } from "../../contexts/ToolWorkflowContext";
|
||||
import { useToolManagement } from "../../hooks/useToolManagement";
|
||||
import { BaseToolProps } from "../../types/tool";
|
||||
import ToolLoadingFallback from "./ToolLoadingFallback";
|
||||
|
||||
@@ -14,8 +14,8 @@ const ToolRenderer = ({
|
||||
onComplete,
|
||||
onError,
|
||||
}: ToolRendererProps) => {
|
||||
// Get the tool from context (instead of direct hook call)
|
||||
const { toolRegistry } = useToolWorkflow();
|
||||
// Get the tool from registry
|
||||
const { toolRegistry } = useToolManagement();
|
||||
const selectedTool = toolRegistry[selectedToolKey];
|
||||
|
||||
if (!selectedTool || !selectedTool.component) {
|
||||
|
||||
@@ -1,195 +0,0 @@
|
||||
/* StampPreview.module.css */
|
||||
|
||||
/* Container styles */
|
||||
.container {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.containerWithThumbnail {
|
||||
background-color: transparent;
|
||||
}
|
||||
|
||||
.containerWithoutThumbnail {
|
||||
background-color: rgba(255, 255, 255, 0.03);
|
||||
}
|
||||
|
||||
.containerBorder {
|
||||
border: 1px solid var(--border-default, #333);
|
||||
}
|
||||
|
||||
/* Page thumbnail styles */
|
||||
.pageThumbnail {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: contain;
|
||||
filter: grayscale(10%) contrast(95%) brightness(105%);
|
||||
}
|
||||
|
||||
/* Stamp item styles */
|
||||
.stampItem {
|
||||
position: absolute;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: flex-start;
|
||||
line-height: 1;
|
||||
transform-origin: left bottom;
|
||||
}
|
||||
|
||||
.stampItemDraggable {
|
||||
cursor: move;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.stampItemGridMode {
|
||||
cursor: default;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* Text stamp styles */
|
||||
.textLine {
|
||||
white-space: pre;
|
||||
display: block;
|
||||
word-break: keep-all;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
/* Image stamp styles */
|
||||
.stampImage {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
bottom: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
/* Quick grid overlay styles */
|
||||
.quickGrid {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
grid-template-rows: repeat(3, 1fr);
|
||||
gap: 8px;
|
||||
padding: 8px;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.gridTile {
|
||||
border: 1px dashed rgba(0, 0, 0, 0.15);
|
||||
background-color: transparent;
|
||||
color: transparent;
|
||||
border-radius: 10px;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 14px;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.gridTileSelected,
|
||||
.gridTileHovered {
|
||||
border: 2px solid var(--mantine-primary-color-filled, #3b82f6);
|
||||
}
|
||||
|
||||
/* Preview header */
|
||||
.previewHeader {
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.divider {
|
||||
height: 1px;
|
||||
background-color: var(--border-default, #333);
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.previewLabel {
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
color: var(--text-primary);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* Preview disclaimer */
|
||||
.previewDisclaimer {
|
||||
margin-top: 8px;
|
||||
opacity: 0.7;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
/* AddStamp.tsx specific styles */
|
||||
|
||||
/* Information text container */
|
||||
.informationContainer {
|
||||
background-color: var(--information-text-bg);
|
||||
padding: 2px;
|
||||
padding-left: 8px;
|
||||
padding-right: 8px;
|
||||
border-radius: 10px;
|
||||
margin-top: 8px;
|
||||
margin-bottom: 8px;
|
||||
width: 100%;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.informationText {
|
||||
font-size: 0.75rem;
|
||||
font-weight: 400;
|
||||
color: var(--information-text-color);
|
||||
}
|
||||
|
||||
/* Mode toggle buttons */
|
||||
.modeToggleGroup {
|
||||
gap: 0.25rem;
|
||||
flex-grow: 1;
|
||||
}
|
||||
|
||||
.modeToggleButton {
|
||||
border-radius: 0.125rem;
|
||||
font-size: 0.75rem;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* Icon pill buttons */
|
||||
.iconPillGroup {
|
||||
gap: 0.25rem;
|
||||
flex-grow: 1;
|
||||
}
|
||||
|
||||
.iconPillButton {
|
||||
border-radius: 0.125rem;
|
||||
font-size: 0.75rem;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* Slider controls */
|
||||
.sliderGroup {
|
||||
gap: 1rem;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.numberInput {
|
||||
width: 80px;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.slider {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.sliderWide {
|
||||
flex: 1.2;
|
||||
}
|
||||
|
||||
/* Label text */
|
||||
.labelText {
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
@@ -1,343 +0,0 @@
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { AddStampParameters } from './useAddStampParameters';
|
||||
import { pdfWorkerManager } from '../../../services/pdfWorkerManager';
|
||||
import { useThumbnailGeneration } from '../../../hooks/useThumbnailGeneration';
|
||||
import { A4_ASPECT_RATIO, getFirstSelectedPage, getFontFamily, computeStampPreviewStyle, getAlphabetPreviewScale } from './StampPreviewUtils';
|
||||
import styles from './StampPreview.module.css';
|
||||
|
||||
type Props = {
|
||||
parameters: AddStampParameters;
|
||||
onParameterChange: <K extends keyof AddStampParameters>(key: K, value: AddStampParameters[K]) => void;
|
||||
file?: File | null;
|
||||
showQuickGrid?: boolean;
|
||||
};
|
||||
|
||||
export default function StampPreview({ parameters, onParameterChange, file, showQuickGrid }: Props) {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const [containerSize, setContainerSize] = useState<{ width: number; height: number }>({ width: 0, height: 0 });
|
||||
const [imageMeta, setImageMeta] = useState<{ url: string; width: number; height: number } | null>(null);
|
||||
const [pageSize, setPageSize] = useState<{ widthPts: number; heightPts: number } | null>(null);
|
||||
const [pageThumbnail, setPageThumbnail] = useState<string | null>(null);
|
||||
const { requestThumbnail } = useThumbnailGeneration();
|
||||
const [hoverTile, setHoverTile] = useState<number | null>(null);
|
||||
|
||||
// Load image URL and meta for aspect ratio if an image is selected
|
||||
useEffect(() => {
|
||||
if (parameters.stampType === 'image' && parameters.stampImage) {
|
||||
const url = URL.createObjectURL(parameters.stampImage);
|
||||
const img = new Image();
|
||||
img.onload = () => {
|
||||
setImageMeta({ url, width: img.width, height: img.height });
|
||||
};
|
||||
img.src = url;
|
||||
return () => URL.revokeObjectURL(url);
|
||||
} else {
|
||||
setImageMeta(null);
|
||||
}
|
||||
}, [parameters.stampType, parameters.stampImage]);
|
||||
|
||||
// Observe container size for responsive positioning
|
||||
useEffect(() => {
|
||||
const node = containerRef.current;
|
||||
if (!node) return;
|
||||
const resize = () => {
|
||||
const aspect = pageSize ? (pageSize.widthPts / pageSize.heightPts) : A4_ASPECT_RATIO;
|
||||
setContainerSize({ width: node.clientWidth, height: node.clientWidth / aspect });
|
||||
};
|
||||
resize();
|
||||
const ro = new ResizeObserver(resize);
|
||||
ro.observe(node);
|
||||
return () => ro.disconnect();
|
||||
}, [pageSize]);
|
||||
|
||||
// Load first PDF page size in points for accurate scaling
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const load = async () => {
|
||||
if (!file || file.type !== 'application/pdf') {
|
||||
setPageSize(null);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const buffer = await file.arrayBuffer();
|
||||
const pdf = await pdfWorkerManager.createDocument(buffer, { disableAutoFetch: true, disableStream: true });
|
||||
const page = await pdf.getPage(1);
|
||||
const viewport = page.getViewport({ scale: 1 });
|
||||
if (!cancelled) {
|
||||
setPageSize({ widthPts: viewport.width, heightPts: viewport.height });
|
||||
}
|
||||
pdfWorkerManager.destroyDocument(pdf);
|
||||
} catch {
|
||||
// Fallback to A4 if we cannot read page
|
||||
if (!cancelled) setPageSize(null);
|
||||
}
|
||||
};
|
||||
load();
|
||||
return () => { cancelled = true; };
|
||||
}, [file]);
|
||||
|
||||
// Load first-page thumbnail for background preview so users see the content
|
||||
useEffect(() => {
|
||||
let isActive = true;
|
||||
const loadThumb = async () => {
|
||||
if (!file || file.type !== 'application/pdf') {
|
||||
setPageThumbnail(null);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const pageNumber = Math.max(1, getFirstSelectedPage(parameters.pageNumbers));
|
||||
const pageId = `${file.name}:${file.size}:${file.lastModified}:page:${pageNumber}`;
|
||||
const thumb = await requestThumbnail(pageId, file, pageNumber);
|
||||
if (isActive) setPageThumbnail(thumb || null);
|
||||
} catch {
|
||||
if (isActive) setPageThumbnail(null);
|
||||
}
|
||||
};
|
||||
loadThumb();
|
||||
return () => { isActive = false; };
|
||||
}, [file, parameters.pageNumbers, requestThumbnail]);
|
||||
|
||||
const style = useMemo(() => (
|
||||
computeStampPreviewStyle(
|
||||
parameters,
|
||||
imageMeta,
|
||||
pageSize,
|
||||
containerSize,
|
||||
showQuickGrid,
|
||||
hoverTile,
|
||||
!!pageThumbnail
|
||||
)
|
||||
), [containerSize, parameters, imageMeta, pageSize, showQuickGrid, hoverTile, pageThumbnail]);
|
||||
|
||||
// Keep center fixed when scaling via slider (or any fontSize changes)
|
||||
const prevDimsRef = useRef<{ fontSize: number; widthPx: number; heightPx: number; leftPx: number; bottomPx: number } | null>(null);
|
||||
useEffect(() => {
|
||||
const itemStyle = style.item as any;
|
||||
if (!itemStyle || containerSize.width <= 0 || containerSize.height <= 0) return;
|
||||
|
||||
const parse = (v: any) => parseFloat(String(v).replace('px', '')) || 0;
|
||||
const leftPx = parse(itemStyle.left);
|
||||
const bottomPx = parse(itemStyle.bottom);
|
||||
const widthPx = parse(itemStyle.width);
|
||||
const heightPx = parse(itemStyle.height);
|
||||
|
||||
const prev = prevDimsRef.current;
|
||||
const hasOverrides = parameters.overrideX >= 0 && parameters.overrideY >= 0;
|
||||
const canAdjust = hasOverrides && !showQuickGrid;
|
||||
if (
|
||||
prev &&
|
||||
canAdjust &&
|
||||
parameters.fontSize !== prev.fontSize &&
|
||||
prev.widthPx > 0 &&
|
||||
prev.heightPx > 0 &&
|
||||
widthPx > 0 &&
|
||||
heightPx > 0
|
||||
) {
|
||||
const centerX = prev.leftPx + prev.widthPx / 2;
|
||||
const centerY = prev.bottomPx + prev.heightPx / 2;
|
||||
const newLeftPx = centerX - widthPx / 2;
|
||||
const newBottomPx = centerY - heightPx / 2;
|
||||
|
||||
const widthPts = pageSize?.widthPts ?? 595.28;
|
||||
const heightPts = pageSize?.heightPts ?? 841.89;
|
||||
const scaleX = containerSize.width / widthPts;
|
||||
const scaleY = containerSize.height / heightPts;
|
||||
const newLeftPts = Math.max(0, Math.min(containerSize.width, newLeftPx)) / scaleX;
|
||||
const newBottomPts = Math.max(0, Math.min(containerSize.height, newBottomPx)) / scaleY;
|
||||
onParameterChange('overrideX', newLeftPts as any);
|
||||
onParameterChange('overrideY', newBottomPts as any);
|
||||
}
|
||||
|
||||
prevDimsRef.current = { fontSize: parameters.fontSize, widthPx, heightPx, leftPx, bottomPx };
|
||||
}, [parameters.fontSize, style.item, containerSize, pageSize, showQuickGrid, parameters.overrideX, parameters.overrideY, onParameterChange]);
|
||||
|
||||
// Drag/resize/rotate interactions
|
||||
const draggingRef = useRef<{ type: 'move' | 'resize' | 'rotate'; startX: number; startY: number; initLeft: number; initBottom: number; initHeight: number; centerX: number; centerY: number } | null>(null);
|
||||
|
||||
const ensureOverrides = () => {
|
||||
const pageWidth = containerSize.width;
|
||||
const pageHeight = containerSize.height;
|
||||
if (pageWidth <= 0 || pageHeight <= 0) return;
|
||||
|
||||
// Recompute current x,y from style (so that we start from visual position)
|
||||
const itemStyle = style.item as any;
|
||||
const leftPx = parseFloat(String(itemStyle.left).replace('px', '')) || 0;
|
||||
const bottomPx = parseFloat(String(itemStyle.bottom).replace('px', '')) || 0;
|
||||
const widthPts = pageSize?.widthPts ?? 595.28;
|
||||
const heightPts = pageSize?.heightPts ?? 841.89;
|
||||
const scaleX = containerSize.width / widthPts;
|
||||
const scaleY = containerSize.height / heightPts;
|
||||
if (parameters.overrideX < 0 || parameters.overrideY < 0) {
|
||||
onParameterChange('overrideX', Math.max(0, Math.min(pageWidth, leftPx)) / scaleX as any);
|
||||
onParameterChange('overrideY', Math.max(0, Math.min(pageHeight, bottomPx)) / scaleY as any);
|
||||
}
|
||||
};
|
||||
|
||||
const handlePointerDown = (e: React.PointerEvent, type: 'move' | 'resize' | 'rotate') => {
|
||||
e.preventDefault();
|
||||
ensureOverrides();
|
||||
|
||||
const item = style.item as any;
|
||||
const left = parseFloat(String(item.left).replace('px', '')) || 0;
|
||||
const bottom = parseFloat(String(item.bottom).replace('px', '')) || 0;
|
||||
const width = parseFloat(String(item.width).replace('px', '')) || parameters.fontSize;
|
||||
const height = parseFloat(String(item.height).replace('px', '')) || parameters.fontSize;
|
||||
|
||||
const rect = (e.currentTarget.parentElement as HTMLElement)?.getBoundingClientRect();
|
||||
const centerX = left + width / 2;
|
||||
const centerY = bottom + height / 2;
|
||||
|
||||
draggingRef.current = {
|
||||
type,
|
||||
startX: e.clientX - (rect?.left || 0),
|
||||
startY: (rect ? rect.bottom - e.clientY : 0), // convert to bottom-based coords
|
||||
initLeft: left,
|
||||
initBottom: bottom,
|
||||
initHeight: height,
|
||||
centerX,
|
||||
centerY,
|
||||
};
|
||||
|
||||
(e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);
|
||||
};
|
||||
|
||||
const handlePointerMove = (e: React.PointerEvent) => {
|
||||
if (!draggingRef.current) return;
|
||||
const node = containerRef.current;
|
||||
if (!node) return;
|
||||
const rect = node.getBoundingClientRect();
|
||||
const x = e.clientX - rect.left;
|
||||
const y = rect.bottom - e.clientY; // bottom-based
|
||||
|
||||
const drag = draggingRef.current;
|
||||
|
||||
if (drag.type === 'move') {
|
||||
const dx = x - drag.startX;
|
||||
const dy = y - drag.startY;
|
||||
const newLeftPx = Math.max(0, Math.min(containerSize.width, drag.initLeft + dx));
|
||||
const newBottomPx = Math.max(0, Math.min(containerSize.height, drag.initBottom + dy));
|
||||
const widthPts = pageSize?.widthPts ?? 595.28;
|
||||
const heightPts = pageSize?.heightPts ?? 841.89;
|
||||
const scaleX = containerSize.width / widthPts;
|
||||
const scaleY = containerSize.height / heightPts;
|
||||
const newLeftPts = newLeftPx / scaleX;
|
||||
const newBottomPts = newBottomPx / scaleY;
|
||||
onParameterChange('overrideX', newLeftPts as any);
|
||||
onParameterChange('overrideY', newBottomPts as any);
|
||||
}
|
||||
|
||||
if (drag.type === 'resize') {
|
||||
// Height is our canonical size (fontSize)
|
||||
const heightPts = pageSize?.heightPts ?? 841.89;
|
||||
const scaleY = containerSize.height / heightPts;
|
||||
const newHeightPx = Math.max(1, drag.initHeight + (y - drag.startY));
|
||||
const newHeightPts = newHeightPx / scaleY;
|
||||
onParameterChange('fontSize', newHeightPts as any);
|
||||
}
|
||||
|
||||
if (drag.type === 'rotate') {
|
||||
const angle = Math.atan2(y - drag.centerY, x - drag.centerX) * (180 / Math.PI);
|
||||
onParameterChange('rotation', angle as any);
|
||||
}
|
||||
};
|
||||
|
||||
const handlePointerUp = (e: React.PointerEvent) => {
|
||||
if (!draggingRef.current) return;
|
||||
draggingRef.current = null;
|
||||
(e.currentTarget as HTMLElement).releasePointerCapture(e.pointerId);
|
||||
};
|
||||
|
||||
const itemHandles = null; // Drag-only per request
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className={styles.previewHeader}>
|
||||
<div className={styles.divider} />
|
||||
<div className={styles.previewLabel}>Preview Stamp</div>
|
||||
</div>
|
||||
<div
|
||||
ref={containerRef}
|
||||
className={`${styles.container} ${styles.containerBorder} ${pageThumbnail ? styles.containerWithThumbnail : styles.containerWithoutThumbnail}`}
|
||||
style={style.container as React.CSSProperties}
|
||||
onPointerMove={handlePointerMove}
|
||||
onPointerUp={handlePointerUp}
|
||||
>
|
||||
{pageThumbnail && (
|
||||
<img
|
||||
src={pageThumbnail}
|
||||
alt="page preview"
|
||||
className={styles.pageThumbnail}
|
||||
draggable={false}
|
||||
/>
|
||||
)}
|
||||
{parameters.stampType === 'text' && (
|
||||
<div
|
||||
className={`${styles.stampItem} ${styles.stampItemGridMode}`}
|
||||
style={style.item as React.CSSProperties}
|
||||
>
|
||||
{(parameters.stampText || '').split('\n').map((line, idx) => (
|
||||
<span
|
||||
key={idx}
|
||||
className={styles.textLine}
|
||||
style={{
|
||||
fontFamily: getFontFamily(parameters.alphabet),
|
||||
fontSize: `${Math.max(1, (parameters.fontSize * getAlphabetPreviewScale(parameters.alphabet)) / 2)}px`,
|
||||
whiteSpace: 'nowrap',
|
||||
}}
|
||||
>
|
||||
{line || '\u00A0'}
|
||||
</span>
|
||||
))}
|
||||
{itemHandles}
|
||||
</div>
|
||||
)}
|
||||
{parameters.stampType === 'image' && imageMeta && (
|
||||
<div
|
||||
className={`${styles.stampItem} ${showQuickGrid ? styles.stampItemGridMode : styles.stampItemDraggable}`}
|
||||
style={style.item as React.CSSProperties}
|
||||
onPointerDown={(e) => handlePointerDown(e, 'move')}
|
||||
>
|
||||
<img
|
||||
src={imageMeta.url}
|
||||
alt="stamp preview"
|
||||
className={styles.stampImage}
|
||||
/>
|
||||
{itemHandles}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Quick position overlay grid */}
|
||||
{showQuickGrid && (
|
||||
<div className={styles.quickGrid}>
|
||||
{Array.from({ length: 9 }).map((_, i) => {
|
||||
const idx = (i + 1) as 1|2|3|4|5|6|7|8|9;
|
||||
const selected = parameters.position === idx && (parameters.overrideX < 0 || parameters.overrideY < 0);
|
||||
return (
|
||||
<button
|
||||
key={idx}
|
||||
type="button"
|
||||
className={`${styles.gridTile} ${selected || hoverTile === idx ? styles.gridTileSelected : ''} ${hoverTile === idx ? styles.gridTileHovered : ''}`}
|
||||
onClick={() => {
|
||||
// Clear overrides to use grid positioning and set position
|
||||
onParameterChange('overrideX', -1 as any);
|
||||
onParameterChange('overrideY', -1 as any);
|
||||
onParameterChange('position', idx as any);
|
||||
}}
|
||||
onMouseEnter={() => setHoverTile(idx)}
|
||||
onMouseLeave={() => setHoverTile(null)}
|
||||
>
|
||||
{idx}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className={styles.previewDisclaimer}>
|
||||
Preview is approximate. Final output may vary due to PDF font metrics.
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,235 +0,0 @@
|
||||
import type { AddStampParameters } from './useAddStampParameters';
|
||||
|
||||
export type ContainerSize = { width: number; height: number };
|
||||
export type PageSizePts = { widthPts: number; heightPts: number } | null;
|
||||
export type ImageMeta = { url: string; width: number; height: number } | null;
|
||||
|
||||
// Map UI margin option to backend margin factor
|
||||
export const marginFactorMap: Record<AddStampParameters['customMargin'], number> = {
|
||||
'small': 0.02,
|
||||
'medium': 0.035,
|
||||
'large': 0.05,
|
||||
'x-large': 0.075,
|
||||
};
|
||||
|
||||
export const A4_ASPECT_RATIO = 0.707; // width/height used elsewhere in legacy UI
|
||||
|
||||
// Get font family based on selected alphabet (matching backend logic)
|
||||
export const getFontFamily = (alphabet: string): string => {
|
||||
switch (alphabet) {
|
||||
case 'arabic':
|
||||
return 'Noto Sans Arabic, Arial Unicode MS, sans-serif';
|
||||
case 'japanese':
|
||||
return 'Meiryo, Yu Gothic, Hiragino Sans, sans-serif';
|
||||
case 'korean':
|
||||
return 'Malgun Gothic, Dotum, sans-serif';
|
||||
case 'chinese':
|
||||
return 'SimSun, Microsoft YaHei, sans-serif';
|
||||
case 'thai':
|
||||
return 'Noto Sans Thai, Tahoma, sans-serif';
|
||||
case 'roman':
|
||||
default:
|
||||
return 'Noto Sans, Arial, Helvetica, sans-serif';
|
||||
}
|
||||
};
|
||||
|
||||
// Lightweight parser: returns first page number from CSV/range input, otherwise 1
|
||||
export const getFirstSelectedPage = (input: string): number => {
|
||||
if (!input) return 1;
|
||||
const parts = input.split(',').map(s => s.trim()).filter(Boolean);
|
||||
for (const part of parts) {
|
||||
if (/^\d+\s*-\s*\d+$/.test(part)) {
|
||||
const low = parseInt(part.split('-')[0].trim(), 10);
|
||||
if (Number.isFinite(low) && low > 0) return low;
|
||||
}
|
||||
const n = parseInt(part, 10);
|
||||
if (Number.isFinite(n) && n > 0) return n;
|
||||
}
|
||||
return 1;
|
||||
};
|
||||
|
||||
export type StampPreviewStyle = { container: any; item: any };
|
||||
|
||||
// Unified per-alphabet preview adjustments
|
||||
export type Alphabet = 'roman' | 'arabic' | 'japanese' | 'korean' | 'chinese' | 'thai';
|
||||
export type AlphabetTweaks = { scale: number; rowOffsetRem: [number, number, number]; lineHeight: number; capHeightRatio: number; defaultFontSize: number };
|
||||
export const ALPHABET_PREVIEW_TWEAKS: Record<Alphabet, AlphabetTweaks> = {
|
||||
// [top, middle, bottom] row offsets in rem
|
||||
roman: { scale: 1.0/1.18, rowOffsetRem: [0, 1, 2.2], lineHeight: 1.28, capHeightRatio: 0.70, defaultFontSize: 80 },
|
||||
arabic: { scale: 1.2, rowOffsetRem: [0, 1.5, 2.5], lineHeight: 1, capHeightRatio: 0.68, defaultFontSize: 80 },
|
||||
japanese: { scale: 1/1.2, rowOffsetRem: [-0.1, 1, 2], lineHeight: 1, capHeightRatio: 0.72, defaultFontSize: 80 },
|
||||
korean: { scale: 1.0/1.05, rowOffsetRem: [-0.2, 0.5, 1.4], lineHeight: 1, capHeightRatio: 0.72, defaultFontSize: 80 },
|
||||
chinese: { scale: 1/1.2, rowOffsetRem: [0, 2, 2.8], lineHeight: 1, capHeightRatio: 0.72, defaultFontSize: 30 }, // temporary default font size so that it fits on the PDF
|
||||
thai: { scale: 1/1.2, rowOffsetRem: [-1, 0, .8], lineHeight: 1, capHeightRatio: 0.66, defaultFontSize: 80 },
|
||||
};
|
||||
export const getAlphabetPreviewScale = (alphabet: string): number => (ALPHABET_PREVIEW_TWEAKS as any)[alphabet]?.scale ?? 1.0;
|
||||
|
||||
export const getDefaultFontSizeForAlphabet = (alphabet: string): number => {
|
||||
return (ALPHABET_PREVIEW_TWEAKS as any)[alphabet]?.defaultFontSize ?? 80;
|
||||
};
|
||||
|
||||
export function computeStampPreviewStyle(
|
||||
parameters: AddStampParameters,
|
||||
imageMeta: ImageMeta,
|
||||
pageSize: PageSizePts,
|
||||
containerSize: ContainerSize,
|
||||
showQuickGrid: boolean | undefined,
|
||||
_hoverTile: number | null,
|
||||
hasPageThumbnail: boolean
|
||||
): StampPreviewStyle {
|
||||
const pageWidthPx = containerSize.width;
|
||||
const pageHeightPx = containerSize.height;
|
||||
const widthPts = pageSize?.widthPts ?? 595.28; // A4 width at 72 DPI
|
||||
const heightPts = pageSize?.heightPts ?? 841.89; // A4 height at 72 DPI
|
||||
const scaleX = pageWidthPx / widthPts;
|
||||
const scaleY = pageHeightPx / heightPts;
|
||||
if (pageWidthPx <= 0 || pageHeightPx <= 0) return { item: {}, container: {} } as any;
|
||||
|
||||
const marginPts = (widthPts + heightPts) / 2 * (marginFactorMap[parameters.customMargin] ?? 0.035);
|
||||
|
||||
// Compute content dimensions
|
||||
const heightPtsContent = parameters.fontSize * getAlphabetPreviewScale(parameters.alphabet);
|
||||
let widthPtsContent = heightPtsContent;
|
||||
|
||||
|
||||
if (parameters.stampType === 'image' && imageMeta) {
|
||||
const aspect = imageMeta.width / imageMeta.height;
|
||||
widthPtsContent = heightPtsContent * aspect;
|
||||
} else if (parameters.stampType === 'text') {
|
||||
// Use Canvas 2D to measure text width for better fidelity than DOM spans
|
||||
const textLine = (parameters.stampText || '').split('\n')[0] ?? '';
|
||||
const fontPx = heightPtsContent * scaleY; // Convert point size to px using vertical scale
|
||||
const fontFamily = getFontFamily(parameters.alphabet);
|
||||
|
||||
const canvas = document.createElement('canvas');
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (ctx) {
|
||||
ctx.font = `${fontPx}px ${fontFamily}`;
|
||||
const metrics = ctx.measureText(textLine);
|
||||
const measuredWidthPx = metrics.width;
|
||||
// Convert measured px width back to PDF points using horizontal scale
|
||||
widthPtsContent = measuredWidthPx / scaleX;
|
||||
|
||||
let adjustmentFactor = 1.0;
|
||||
switch (parameters.alphabet) {
|
||||
case 'roman':
|
||||
adjustmentFactor = 0.90;
|
||||
break;
|
||||
case 'arabic':
|
||||
case 'thai':
|
||||
adjustmentFactor = 0.92;
|
||||
break;
|
||||
case 'japanese':
|
||||
case 'korean':
|
||||
case 'chinese':
|
||||
adjustmentFactor = 0.88;
|
||||
break;
|
||||
default:
|
||||
adjustmentFactor = 0.93;
|
||||
}
|
||||
widthPtsContent *= adjustmentFactor;
|
||||
}
|
||||
}
|
||||
|
||||
// Positioning helpers - mirror backend logic
|
||||
const position = parameters.position;
|
||||
const calcX = () => {
|
||||
if (parameters.overrideX >= 0 && parameters.overrideY >= 0) return parameters.overrideX;
|
||||
switch (position % 3) {
|
||||
case 1: // Left
|
||||
return marginPts;
|
||||
case 2: // Center
|
||||
return (widthPts - widthPtsContent) / 2;
|
||||
case 0: // Right
|
||||
return widthPts - widthPtsContent - marginPts;
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
const calcY = () => {
|
||||
if (parameters.overrideX >= 0 && parameters.overrideY >= 0) return parameters.overrideY;
|
||||
// For text, backend positions using cap height, not full font size
|
||||
const heightForY = parameters.stampType === 'text'
|
||||
? heightPtsContent * ((ALPHABET_PREVIEW_TWEAKS as any)[parameters.alphabet]?.capHeightRatio ?? 0.70)
|
||||
: heightPtsContent;
|
||||
switch (Math.floor((position - 1) / 3)) {
|
||||
case 0: // Top
|
||||
return heightPts - heightForY - marginPts;
|
||||
case 1: // Middle
|
||||
return (heightPts - heightForY) / 2;
|
||||
case 2: // Bottom
|
||||
return marginPts;
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
|
||||
const xPts = calcX();
|
||||
const yPts = calcY();
|
||||
let xPx = xPts * scaleX;
|
||||
let yPx = yPts * scaleY;
|
||||
if (parameters.stampType === 'text') {
|
||||
try {
|
||||
const rootFontSizePx = parseFloat(getComputedStyle(document.documentElement).fontSize || '16') || 16;
|
||||
const rowIndex = Math.floor((position - 1) / 3); // 0 top, 1 middle, 2 bottom
|
||||
const offsets = (ALPHABET_PREVIEW_TWEAKS as any)[parameters.alphabet]?.rowOffsetRem ?? [0, 0, 0];
|
||||
const offsetRem = offsets[rowIndex] ?? 0;
|
||||
yPx += offsetRem * rootFontSizePx;
|
||||
} catch (e) {
|
||||
// no-op
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
const widthPx = widthPtsContent * scaleX;
|
||||
const heightPx = heightPtsContent * scaleY;
|
||||
|
||||
xPx = Math.max(0, Math.min(xPx, pageWidthPx - widthPx));
|
||||
yPx = Math.max(0, Math.min(yPx, pageHeightPx - heightPx));
|
||||
|
||||
const opacity = Math.max(0, Math.min(1, parameters.opacity / 100));
|
||||
const displayOpacity = opacity;
|
||||
|
||||
let alignItems: 'flex-start' | 'center' | 'flex-end' = 'flex-start';
|
||||
if (parameters.stampType === 'text') {
|
||||
const colIndex = position % 3; // 1: left, 2: center, 0: right
|
||||
switch (colIndex) {
|
||||
case 2: // center column
|
||||
alignItems = 'center';
|
||||
break;
|
||||
case 0: // right column
|
||||
alignItems = 'flex-end';
|
||||
break;
|
||||
default:
|
||||
alignItems = 'flex-start';
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
container: {
|
||||
position: 'relative',
|
||||
width: '100%',
|
||||
aspectRatio: `${(pageSize?.widthPts ?? 595.28) / (pageSize?.heightPts ?? 841.89)} / 1`,
|
||||
backgroundColor: hasPageThumbnail ? 'transparent' : 'rgba(255,255,255,0.03)',
|
||||
border: '1px solid var(--border-default, #333)',
|
||||
overflow: 'hidden'
|
||||
},
|
||||
item: {
|
||||
position: 'absolute',
|
||||
left: `${xPx}px`,
|
||||
bottom: `${yPx}px`,
|
||||
width: `${widthPx}px`,
|
||||
height: `${heightPx}px`,
|
||||
opacity: displayOpacity,
|
||||
transform: `rotate(${-parameters.rotation}deg)`,
|
||||
transformOrigin: 'center center',
|
||||
color: parameters.customColor,
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
justifyContent: 'flex-start',
|
||||
lineHeight: (ALPHABET_PREVIEW_TWEAKS as any)[parameters.alphabet]?.lineHeight ?? 1,
|
||||
alignItems,
|
||||
cursor: showQuickGrid ? 'default' : 'move',
|
||||
pointerEvents: showQuickGrid ? 'none' : 'auto',
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ToolType, useToolOperation } from '../../../hooks/tools/shared/useToolOperation';
|
||||
import { createStandardErrorHandler } from '../../../utils/toolErrorHandler';
|
||||
import { AddStampParameters, defaultParameters } from './useAddStampParameters';
|
||||
|
||||
export const buildAddStampFormData = (parameters: AddStampParameters, file: File): FormData => {
|
||||
const formData = new FormData();
|
||||
formData.append('fileInput', file);
|
||||
formData.append('pageNumbers', parameters.pageNumbers);
|
||||
formData.append('customMargin', parameters.customMargin || 'medium');
|
||||
formData.append('position', String(parameters.position));
|
||||
const effectiveFontSize = parameters.fontSize;
|
||||
formData.append('fontSize', String(effectiveFontSize));
|
||||
formData.append('rotation', String(parameters.rotation));
|
||||
formData.append('opacity', String(parameters.opacity / 100));
|
||||
formData.append('overrideX', String(parameters.overrideX));
|
||||
formData.append('overrideY', String(parameters.overrideY));
|
||||
formData.append('customColor', parameters.customColor.startsWith('#') ? parameters.customColor : `#${parameters.customColor}`);
|
||||
formData.append('alphabet', parameters.alphabet);
|
||||
|
||||
// Stamp type and payload
|
||||
formData.append('stampType', parameters.stampType || 'text');
|
||||
if (parameters.stampType === 'text') {
|
||||
formData.append('stampText', parameters.stampText);
|
||||
} else if (parameters.stampType === 'image' && parameters.stampImage) {
|
||||
formData.append('stampImage', parameters.stampImage);
|
||||
}
|
||||
|
||||
return formData;
|
||||
};
|
||||
|
||||
export const addStampOperationConfig = {
|
||||
toolType: ToolType.singleFile,
|
||||
buildFormData: buildAddStampFormData,
|
||||
operationType: 'addStamp',
|
||||
endpoint: '/api/v1/misc/add-stamp',
|
||||
defaultParameters,
|
||||
} as const;
|
||||
|
||||
export const useAddStampOperation = () => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return useToolOperation<AddStampParameters>({
|
||||
...addStampOperationConfig,
|
||||
getErrorMessage: createStandardErrorHandler(
|
||||
t('AddStampRequest.error.failed', 'An error occurred while adding stamp to the PDF.')
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
import { BaseParameters } from '../../../types/parameters';
|
||||
import { useBaseParameters, type BaseParametersHook } from '../../../hooks/tools/shared/useBaseParameters';
|
||||
|
||||
export interface AddStampParameters extends BaseParameters {
|
||||
stampType?: 'text' | 'image';
|
||||
stampText: string;
|
||||
stampImage?: File;
|
||||
alphabet: 'roman' | 'arabic' | 'japanese' | 'korean' | 'chinese' | 'thai';
|
||||
fontSize: number;
|
||||
rotation: number;
|
||||
opacity: number;
|
||||
position: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
|
||||
overrideX: number;
|
||||
overrideY: number;
|
||||
customMargin: 'small' | 'medium' | 'large' | 'x-large';
|
||||
customColor: string;
|
||||
pageNumbers: string;
|
||||
_activePill: 'fontSize' | 'rotation' | 'opacity';
|
||||
}
|
||||
|
||||
export const defaultParameters: AddStampParameters = {
|
||||
stampType: 'text',
|
||||
stampText: '',
|
||||
alphabet: 'roman',
|
||||
fontSize: 80,
|
||||
rotation: 0,
|
||||
opacity: 50,
|
||||
position: 5,
|
||||
overrideX: -1,
|
||||
overrideY: -1,
|
||||
customMargin: 'medium',
|
||||
customColor: '#d3d3d3',
|
||||
pageNumbers: '1',
|
||||
_activePill: 'fontSize',
|
||||
};
|
||||
|
||||
export type AddStampParametersHook = BaseParametersHook<AddStampParameters>;
|
||||
|
||||
export const useAddStampParameters = (): AddStampParametersHook => {
|
||||
return useBaseParameters<AddStampParameters>({
|
||||
defaultParameters,
|
||||
endpointName: 'add-stamp',
|
||||
validateFn: (params): boolean => {
|
||||
if (!params.stampType) return false;
|
||||
if (params.stampType === 'text') {
|
||||
return params.stampText.trim().length > 0;
|
||||
}
|
||||
return params.stampImage !== undefined;
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -15,8 +15,6 @@ export interface ReviewToolStepProps<TParams = unknown> {
|
||||
title?: string;
|
||||
onFileClick?: (file: File) => void;
|
||||
onUndo: () => void;
|
||||
isCollapsed?: boolean;
|
||||
onCollapsedClick?: () => void;
|
||||
}
|
||||
|
||||
function ReviewStepContent<TParams = unknown>({
|
||||
@@ -113,8 +111,6 @@ export function createReviewToolStep<TParams = unknown>(
|
||||
t("review", "Review"),
|
||||
{
|
||||
isVisible: props.isVisible,
|
||||
isCollapsed: props.isCollapsed,
|
||||
onCollapsedClick: props.onCollapsedClick,
|
||||
_excludeFromCount: true,
|
||||
_noPadding: true,
|
||||
},
|
||||
|
||||
@@ -113,4 +113,4 @@ export function createToolFlow(config: ToolFlowConfig) {
|
||||
</ToolStepProvider>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,19 +5,3 @@ export const getBaseUrl = (): string => {
|
||||
const { config } = useAppConfig();
|
||||
return config?.baseUrl || 'https://stirling.com';
|
||||
};
|
||||
|
||||
// Base path from Vite config - build-time constant, normalized (no trailing slash)
|
||||
// When no subpath, use empty string instead of '.' to avoid relative path issues
|
||||
export const BASE_PATH = (import.meta.env.BASE_URL || '/').replace(/\/$/, '').replace(/^\.$/, '');
|
||||
|
||||
/** For in-app navigations when you must touch window.location (rare). */
|
||||
export const withBasePath = (path: string): string => {
|
||||
const clean = path.startsWith('/') ? path : `/${path}`;
|
||||
return `${BASE_PATH}${clean}`;
|
||||
};
|
||||
|
||||
/** For OAuth (needs absolute URL with scheme+host) */
|
||||
export const absoluteWithBasePath = (path: string): string => {
|
||||
const clean = path.startsWith('/') ? path : `/${path}`;
|
||||
return `${window.location.origin}${BASE_PATH}${clean}`;
|
||||
};
|
||||
|
||||
@@ -75,7 +75,6 @@ interface ToolWorkflowContextValue extends ToolWorkflowState {
|
||||
selectedToolKey: string | null;
|
||||
selectedTool: ToolRegistryEntry | null;
|
||||
toolRegistry: any; // From useToolManagement
|
||||
getSelectedTool: (toolId: string | null) => ToolRegistryEntry | null;
|
||||
|
||||
// UI Actions
|
||||
setSidebarsVisible: (visible: boolean) => void;
|
||||
@@ -248,7 +247,6 @@ export function ToolWorkflowProvider({ children }: ToolWorkflowProviderProps) {
|
||||
selectedToolKey: navigationState.selectedTool,
|
||||
selectedTool,
|
||||
toolRegistry,
|
||||
getSelectedTool,
|
||||
|
||||
// Actions
|
||||
setSidebarsVisible,
|
||||
@@ -278,7 +276,6 @@ export function ToolWorkflowProvider({ children }: ToolWorkflowProviderProps) {
|
||||
navigationState.selectedTool,
|
||||
selectedTool,
|
||||
toolRegistry,
|
||||
getSelectedTool,
|
||||
setSidebarsVisible,
|
||||
setLeftPanelView,
|
||||
setReaderMode,
|
||||
|
||||
@@ -13,7 +13,6 @@ import RemovePages from "../tools/RemovePages";
|
||||
import RemovePassword from "../tools/RemovePassword";
|
||||
import { SubcategoryId, ToolCategoryId, ToolRegistry } from "./toolsTaxonomy";
|
||||
import AddWatermark from "../tools/AddWatermark";
|
||||
import AddStamp from "../tools/AddStamp";
|
||||
import Merge from '../tools/Merge';
|
||||
import Repair from "../tools/Repair";
|
||||
import AutoRename from "../tools/AutoRename";
|
||||
@@ -33,7 +32,6 @@ import { removePasswordOperationConfig } from "../hooks/tools/removePassword/use
|
||||
import { sanitizeOperationConfig } from "../hooks/tools/sanitize/useSanitizeOperation";
|
||||
import { repairOperationConfig } from "../hooks/tools/repair/useRepairOperation";
|
||||
import { addWatermarkOperationConfig } from "../hooks/tools/addWatermark/useAddWatermarkOperation";
|
||||
import { addStampOperationConfig } from "../components/tools/addStamp/useAddStampOperation";
|
||||
import { unlockPdfFormsOperationConfig } from "../hooks/tools/unlockPdfForms/useUnlockPdfFormsOperation";
|
||||
import { singleLargePageOperationConfig } from "../hooks/tools/singleLargePage/useSingleLargePageOperation";
|
||||
import { ocrOperationConfig } from "../hooks/tools/ocr/useOCROperation";
|
||||
@@ -215,13 +213,10 @@ export function useFlatToolRegistry(): ToolRegistry {
|
||||
addStamp: {
|
||||
icon: <LocalIcon icon="approval-rounded" width="1.5rem" height="1.5rem" />,
|
||||
name: t("home.addStamp.title", "Add Stamp to PDF"),
|
||||
component: AddStamp,
|
||||
component: null,
|
||||
description: t("home.addStamp.desc", "Add text or add image stamps at set locations"),
|
||||
categoryId: ToolCategoryId.STANDARD_TOOLS,
|
||||
subcategoryId: SubcategoryId.DOCUMENT_SECURITY,
|
||||
maxFiles: -1,
|
||||
endpoints: ["add-stamp"],
|
||||
operationConfig: addStampOperationConfig,
|
||||
},
|
||||
sanitize: {
|
||||
icon: <LocalIcon icon="cleaning-services-outline-rounded" width="1.5rem" height="1.5rem" />,
|
||||
|
||||
Vendored
-1
@@ -17,7 +17,6 @@ declare module '../assets/material-symbols-icons.json' {
|
||||
export default value;
|
||||
}
|
||||
|
||||
declare module 'pdfjs-dist/legacy/build/pdf.mjs'
|
||||
// TODO: Add proper EmbedPDF types for local submodule integration
|
||||
|
||||
export {};
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { BASE_PATH } from '../constants/app';
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
@@ -38,17 +37,17 @@ export const useCookieConsent = ({ analyticsEnabled = false }: CookieConsentConf
|
||||
// Load the cookie consent CSS files first
|
||||
const mainCSS = document.createElement('link');
|
||||
mainCSS.rel = 'stylesheet';
|
||||
mainCSS.href = `${BASE_PATH}/css/cookieconsent.css`;
|
||||
mainCSS.href = '/css/cookieconsent.css';
|
||||
document.head.appendChild(mainCSS);
|
||||
|
||||
const customCSS = document.createElement('link');
|
||||
customCSS.rel = 'stylesheet';
|
||||
customCSS.href = `${BASE_PATH}/css/cookieconsentCustomisation.css`;
|
||||
customCSS.href = '/css/cookieconsentCustomisation.css';
|
||||
document.head.appendChild(customCSS);
|
||||
|
||||
// Load the cookie consent library
|
||||
const script = document.createElement('script');
|
||||
script.src = `${BASE_PATH}/js/thirdParty/cookieconsent.umd.js`;
|
||||
script.src = '/js/thirdParty/cookieconsent.umd.js';
|
||||
script.onload = () => {
|
||||
// Small delay to ensure DOM is ready
|
||||
setTimeout(() => {
|
||||
|
||||
@@ -8,31 +8,31 @@ export function usePDFProcessor() {
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const generatePageThumbnail = useCallback(async (
|
||||
file: File,
|
||||
pageNumber: number,
|
||||
file: File,
|
||||
pageNumber: number,
|
||||
scale: number = 0.5
|
||||
): Promise<string> => {
|
||||
try {
|
||||
const arrayBuffer = await file.arrayBuffer();
|
||||
const pdf = await pdfWorkerManager.createDocument(arrayBuffer);
|
||||
const page = await pdf.getPage(pageNumber);
|
||||
|
||||
|
||||
const viewport = page.getViewport({ scale });
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = viewport.width;
|
||||
canvas.height = viewport.height;
|
||||
|
||||
|
||||
const context = canvas.getContext('2d');
|
||||
if (!context) {
|
||||
throw new Error('Could not get canvas context');
|
||||
}
|
||||
|
||||
await page.render({ canvasContext: context, viewport, canvas }).promise;
|
||||
|
||||
await page.render({ canvasContext: context, viewport }).promise;
|
||||
const thumbnail = canvas.toDataURL();
|
||||
|
||||
|
||||
// Clean up using worker manager
|
||||
pdfWorkerManager.destroyDocument(pdf);
|
||||
|
||||
|
||||
return thumbnail;
|
||||
} catch (error) {
|
||||
console.error('Failed to generate thumbnail:', error);
|
||||
@@ -42,22 +42,22 @@ export function usePDFProcessor() {
|
||||
|
||||
// Internal function to generate thumbnail from already-opened PDF
|
||||
const generateThumbnailFromPDF = useCallback(async (
|
||||
pdf: any,
|
||||
pageNumber: number,
|
||||
pdf: any,
|
||||
pageNumber: number,
|
||||
scale: number = 0.5
|
||||
): Promise<string> => {
|
||||
const page = await pdf.getPage(pageNumber);
|
||||
|
||||
|
||||
const viewport = page.getViewport({ scale });
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = viewport.width;
|
||||
canvas.height = viewport.height;
|
||||
|
||||
|
||||
const context = canvas.getContext('2d');
|
||||
if (!context) {
|
||||
throw new Error('Could not get canvas context');
|
||||
}
|
||||
|
||||
|
||||
await page.render({ canvasContext: context, viewport }).promise;
|
||||
return canvas.toDataURL();
|
||||
}, []);
|
||||
@@ -65,14 +65,14 @@ export function usePDFProcessor() {
|
||||
const processPDFFile = useCallback(async (file: File): Promise<PDFDocument> => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
|
||||
try {
|
||||
const arrayBuffer = await file.arrayBuffer();
|
||||
const pdf = await pdfWorkerManager.createDocument(arrayBuffer);
|
||||
const totalPages = pdf.numPages;
|
||||
|
||||
|
||||
const pages: PDFPage[] = [];
|
||||
|
||||
|
||||
// Create pages without thumbnails initially - load them lazily
|
||||
for (let i = 1; i <= totalPages; i++) {
|
||||
pages.push({
|
||||
@@ -84,7 +84,7 @@ export function usePDFProcessor() {
|
||||
selected: false
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// Generate thumbnails for first 10 pages immediately using the same PDF instance
|
||||
const priorityPages = Math.min(10, totalPages);
|
||||
for (let i = 1; i <= priorityPages; i++) {
|
||||
@@ -95,10 +95,10 @@ export function usePDFProcessor() {
|
||||
console.warn(`Failed to generate thumbnail for page ${i}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Clean up using worker manager
|
||||
pdfWorkerManager.destroyDocument(pdf);
|
||||
|
||||
|
||||
const document: PDFDocument = {
|
||||
id: `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
|
||||
name: file.name,
|
||||
@@ -106,7 +106,7 @@ export function usePDFProcessor() {
|
||||
pages,
|
||||
totalPages
|
||||
};
|
||||
|
||||
|
||||
return document;
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Failed to process PDF';
|
||||
@@ -123,4 +123,4 @@ export function usePDFProcessor() {
|
||||
loading,
|
||||
error
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback } from 'react';
|
||||
import { useToolNavigation } from './useToolNavigation';
|
||||
import { useToolWorkflow } from '../contexts/ToolWorkflowContext';
|
||||
import { useToolManagement } from './useToolManagement';
|
||||
import { handleUnlessSpecialClick } from '../utils/clickHandlers';
|
||||
|
||||
export interface SidebarNavigationProps {
|
||||
@@ -19,7 +19,7 @@ export function useSidebarNavigation(): {
|
||||
getToolNavigation: (toolId: string) => SidebarNavigationProps | null;
|
||||
} {
|
||||
const { getToolNavigation: getToolNavProps } = useToolNavigation();
|
||||
const { getSelectedTool } = useToolWorkflow();
|
||||
const { getSelectedTool } = useToolManagement();
|
||||
|
||||
const defaultNavClick = useCallback((e: React.MouseEvent) => {
|
||||
handleUnlessSpecialClick(e, () => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useNavigationState } from '../contexts/NavigationContext';
|
||||
import { useToolNavigation } from './useToolNavigation';
|
||||
import { useToolWorkflow } from '../contexts/ToolWorkflowContext';
|
||||
import { useToolManagement } from './useToolManagement';
|
||||
import { ToolId } from '../types/toolId';
|
||||
|
||||
// Material UI Icons
|
||||
@@ -50,7 +50,7 @@ const ALL_SUGGESTED_TOOLS: Omit<SuggestedTool, 'href' | 'onClick'>[] = [
|
||||
export function useSuggestedTools(): SuggestedTool[] {
|
||||
const { selectedTool } = useNavigationState();
|
||||
const { getToolNavigation } = useToolNavigation();
|
||||
const { getSelectedTool } = useToolWorkflow();
|
||||
const { getSelectedTool } = useToolManagement();
|
||||
|
||||
return useMemo(() => {
|
||||
// Filter out the current tool
|
||||
|
||||
@@ -7,7 +7,6 @@ import { ToolId } from '../types/toolId';
|
||||
import { parseToolRoute, updateToolRoute, clearToolRoute } from '../utils/urlRouting';
|
||||
import { ToolRegistry } from '../data/toolsTaxonomy';
|
||||
import { firePixel } from '../utils/scarfTracking';
|
||||
import { withBasePath } from '../constants/app';
|
||||
|
||||
/**
|
||||
* Hook to sync workbench and tool with URL using registry
|
||||
@@ -52,8 +51,7 @@ export function useNavigationUrlSync(
|
||||
} else if (prevSelectedTool.current !== null) {
|
||||
// Only clear URL if we had a tool before (user navigated away)
|
||||
// Don't clear on initial load when both current and previous are null
|
||||
const homePath = withBasePath('/');
|
||||
if (window.location.pathname !== homePath) {
|
||||
if (window.location.pathname !== '/') {
|
||||
clearToolRoute(false); // Use pushState for user navigation
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,9 +74,7 @@ i18n
|
||||
loadPath: (lngs: string[], namespaces: string[]) => {
|
||||
// Map 'en' to 'en-GB' for loading translations
|
||||
const lng = lngs[0] === 'en' ? 'en-GB' : lngs[0];
|
||||
const basePath = import.meta.env.BASE_URL || '/';
|
||||
const cleanBasePath = basePath.endsWith('/') ? basePath.slice(0, -1) : basePath;
|
||||
return `${cleanBasePath}/locales/${lng}/${namespaces[0]}.json`;
|
||||
return `/locales/${lng}/${namespaces[0]}.json`;
|
||||
},
|
||||
},
|
||||
|
||||
|
||||
@@ -10,7 +10,6 @@ import App from './App';
|
||||
import './i18n'; // Initialize i18next
|
||||
import posthog from 'posthog-js';
|
||||
import { PostHogProvider } from 'posthog-js/react';
|
||||
import { BASE_PATH } from './constants/app';
|
||||
|
||||
// Compute initial color scheme
|
||||
function getInitialScheme(): 'light' | 'dark' {
|
||||
@@ -61,7 +60,7 @@ root.render(
|
||||
<PostHogProvider
|
||||
client={posthog}
|
||||
>
|
||||
<BrowserRouter basename={BASE_PATH}>
|
||||
<BrowserRouter>
|
||||
<App />
|
||||
</BrowserRouter>
|
||||
</PostHogProvider>
|
||||
|
||||
@@ -110,7 +110,7 @@ export class PDFProcessingService {
|
||||
|
||||
const context = canvas.getContext('2d');
|
||||
if (context) {
|
||||
await page.render({ canvasContext: context, viewport, canvas }).promise;
|
||||
await page.render({ canvasContext: context, viewport }).promise;
|
||||
const thumbnail = canvas.toDataURL();
|
||||
|
||||
pages.push({
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
* and ensuring proper cleanup when operations complete.
|
||||
*/
|
||||
|
||||
import { GlobalWorkerOptions, getDocument, PDFDocumentProxy } from 'pdfjs-dist/legacy/build/pdf.mjs';
|
||||
import * as pdfjsLib from 'pdfjs-dist';
|
||||
import { PDFDocumentProxy } from 'pdfjs-dist/types/src/display/api';
|
||||
const { getDocument, GlobalWorkerOptions } = pdfjsLib;
|
||||
|
||||
class PDFWorkerManager {
|
||||
private static instance: PDFWorkerManager;
|
||||
@@ -30,10 +32,7 @@ class PDFWorkerManager {
|
||||
*/
|
||||
private initializeWorker(): void {
|
||||
if (!this.isInitialized) {
|
||||
GlobalWorkerOptions.workerSrc = new URL(
|
||||
'pdfjs-dist/legacy/build/pdf.worker.min.mjs',
|
||||
import.meta.url
|
||||
).toString();
|
||||
GlobalWorkerOptions.workerSrc = '/pdf.worker.js';
|
||||
this.isInitialized = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -191,8 +191,6 @@
|
||||
--checkbox-checked-bg: #3FAFFF;
|
||||
--checkbox-tick: #FFFFFF;
|
||||
|
||||
--information-text-bg: #eaeaea;
|
||||
--information-text-color: #5e5e5e;
|
||||
/* Bulk selection panel specific colors (light mode) */
|
||||
--bulk-panel-bg: #ffffff; /* white background for parent container */
|
||||
--bulk-card-bg: #ffffff; /* white background for cards */
|
||||
@@ -353,9 +351,6 @@
|
||||
/* Tool panel search bar background colors (dark mode) */
|
||||
--tool-panel-search-bg: #1F2329;
|
||||
--tool-panel-search-border-bottom: #4B525A;
|
||||
|
||||
--information-text-bg: #292e34;
|
||||
--information-text-color: #ececec;
|
||||
|
||||
/* Bulk selection panel specific colors (dark mode) */
|
||||
--bulk-panel-bg: var(--bg-raised); /* dark background for parent container */
|
||||
|
||||
@@ -1,413 +0,0 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useFileSelection } from "../contexts/FileContext";
|
||||
import { createToolFlow } from "../components/tools/shared/createToolFlow";
|
||||
import { BaseToolProps, ToolComponent } from "../types/tool";
|
||||
import { useEndpointEnabled } from "../hooks/useEndpointConfig";
|
||||
import { useAddStampParameters } from "../components/tools/addStamp/useAddStampParameters";
|
||||
import { useAddStampOperation } from "../components/tools/addStamp/useAddStampOperation";
|
||||
import { Group, Select, Stack, Textarea, TextInput, ColorInput, Button, Slider, Text, NumberInput, Divider } from "@mantine/core";
|
||||
import StampPreview from "../components/tools/addStamp/StampPreview";
|
||||
import LocalIcon from "../components/shared/LocalIcon";
|
||||
import styles from "../components/tools/addStamp/StampPreview.module.css";
|
||||
import { Tooltip } from "../components/shared/Tooltip";
|
||||
import ButtonSelector from "../components/shared/ButtonSelector";
|
||||
import { useAccordionSteps } from "../hooks/tools/shared/useAccordionSteps";
|
||||
import ObscuredOverlay from "../components/shared/ObscuredOverlay";
|
||||
import { getDefaultFontSizeForAlphabet } from "../components/tools/addStamp/StampPreviewUtils";
|
||||
|
||||
const AddStamp = ({ onPreviewFile, onComplete, onError }: BaseToolProps) => {
|
||||
const { t } = useTranslation();
|
||||
const { selectedFiles } = useFileSelection();
|
||||
|
||||
const [quickPositionModeSelected, setQuickPositionModeSelected] = useState(false);
|
||||
const [customPositionModeSelected, setCustomPositionModeSelected] = useState(true);
|
||||
|
||||
const params = useAddStampParameters();
|
||||
const operation = useAddStampOperation();
|
||||
|
||||
const { enabled: endpointEnabled, loading: endpointLoading } = useEndpointEnabled("add-stamp");
|
||||
|
||||
useEffect(() => {
|
||||
operation.resetResults();
|
||||
onPreviewFile?.(null);
|
||||
}, [params.parameters]);
|
||||
|
||||
|
||||
const handleExecute = async () => {
|
||||
try {
|
||||
await operation.executeOperation(params.parameters, selectedFiles);
|
||||
if (operation.files && onComplete) {
|
||||
onComplete(operation.files);
|
||||
}
|
||||
} catch (error: any) {
|
||||
onError?.(error?.message || t("AddStampRequest.error.failed", "Add stamp operation failed"));
|
||||
}
|
||||
};
|
||||
|
||||
const hasFiles = selectedFiles.length > 0;
|
||||
const hasResults = operation.files.length > 0 || operation.downloadUrl !== null;
|
||||
|
||||
enum AddStampStep {
|
||||
NONE = 'none',
|
||||
STAMP_SETUP = 'stampSetup',
|
||||
POSITION_FORMATTING = 'positionFormatting'
|
||||
}
|
||||
|
||||
const accordion = useAccordionSteps<AddStampStep>({
|
||||
noneValue: AddStampStep.NONE,
|
||||
initialStep: AddStampStep.STAMP_SETUP,
|
||||
stateConditions: {
|
||||
hasFiles,
|
||||
hasResults
|
||||
},
|
||||
afterResults: () => {
|
||||
operation.resetResults();
|
||||
onPreviewFile?.(null);
|
||||
}
|
||||
});
|
||||
|
||||
const getSteps = () => {
|
||||
const steps: any[] = [];
|
||||
|
||||
// Step 1: Stamp Setup
|
||||
steps.push({
|
||||
title: t("AddStampRequest.stampSetup", "Stamp Setup"),
|
||||
isCollapsed: accordion.getCollapsedState(AddStampStep.STAMP_SETUP),
|
||||
onCollapsedClick: () => accordion.handleStepToggle(AddStampStep.STAMP_SETUP),
|
||||
isVisible: hasFiles || hasResults,
|
||||
content: (
|
||||
<Stack gap="md">
|
||||
<TextInput
|
||||
label={t('pageSelectionPrompt', 'Page Selection (e.g. 1,3,2 or 4-8,2,10-12 or 2n-1)')}
|
||||
value={params.parameters.pageNumbers}
|
||||
onChange={(e) => params.updateParameter('pageNumbers', e.currentTarget.value)}
|
||||
disabled={endpointLoading}
|
||||
/>
|
||||
<Divider/>
|
||||
<div>
|
||||
<Text size="sm" fw={500} mb="xs">{t('AddStampRequest.stampType', 'Stamp Type')}</Text>
|
||||
<ButtonSelector
|
||||
value={params.parameters.stampType}
|
||||
onChange={(v: 'text' | 'image') => params.updateParameter('stampType', v)}
|
||||
options={[
|
||||
{ value: 'text', label: t('watermark.type.1', 'Text') },
|
||||
{ value: 'image', label: t('watermark.type.2', 'Image') },
|
||||
]}
|
||||
disabled={endpointLoading}
|
||||
buttonClassName={styles.modeToggleButton}
|
||||
textClassName={styles.modeToggleButtonText}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{params.parameters.stampType === 'text' && (
|
||||
<>
|
||||
<Textarea
|
||||
label={t('AddStampRequest.stampText', 'Stamp Text')}
|
||||
value={params.parameters.stampText}
|
||||
onChange={(e) => params.updateParameter('stampText', e.currentTarget.value)}
|
||||
autosize
|
||||
minRows={2}
|
||||
disabled={endpointLoading}
|
||||
/>
|
||||
<Select
|
||||
label={t('AddStampRequest.alphabet', 'Alphabet')}
|
||||
value={params.parameters.alphabet}
|
||||
onChange={(v) => {
|
||||
const nextAlphabet = (v as any) || 'roman';
|
||||
params.updateParameter('alphabet', nextAlphabet);
|
||||
const nextDefault = getDefaultFontSizeForAlphabet(nextAlphabet);
|
||||
params.updateParameter('fontSize', nextDefault);
|
||||
}}
|
||||
data={[
|
||||
{ value: 'roman', label: 'Roman' },
|
||||
{ value: 'arabic', label: 'العربية' },
|
||||
{ value: 'japanese', label: '日本語' },
|
||||
{ value: 'korean', label: '한국어' },
|
||||
{ value: 'chinese', label: '简体中文' },
|
||||
{ value: 'thai', label: 'ไทย' },
|
||||
]}
|
||||
disabled={endpointLoading}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{params.parameters.stampType === 'image' && (
|
||||
<Stack gap="xs">
|
||||
<input
|
||||
type="file"
|
||||
accept=".png,.jpg,.jpeg,.gif,.bmp,.tiff,.tif,.webp"
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) params.updateParameter('stampImage', file);
|
||||
}}
|
||||
disabled={endpointLoading}
|
||||
style={{ display: 'none' }}
|
||||
id="stamp-image-input"
|
||||
/>
|
||||
<Button
|
||||
size="xs"
|
||||
component="label"
|
||||
htmlFor="stamp-image-input"
|
||||
disabled={endpointLoading}
|
||||
>
|
||||
{t('chooseFile', 'Choose File')}
|
||||
</Button>
|
||||
{params.parameters.stampImage && (
|
||||
<Stack gap="xs">
|
||||
<img
|
||||
src={URL.createObjectURL(params.parameters.stampImage)}
|
||||
alt="Selected stamp image"
|
||||
className="max-h-24 w-full object-contain border border-gray-200 rounded bg-gray-50"
|
||||
/>
|
||||
<Text size="xs" c="dimmed">
|
||||
{params.parameters.stampImage.name}
|
||||
</Text>
|
||||
</Stack>
|
||||
)}
|
||||
</Stack>
|
||||
)}
|
||||
</Stack>
|
||||
),
|
||||
});
|
||||
|
||||
// Step 3: Formatting & Position
|
||||
steps.push({
|
||||
title: t("AddStampRequest.positionAndFormatting", "Position & Formatting"),
|
||||
isCollapsed: accordion.getCollapsedState(AddStampStep.POSITION_FORMATTING),
|
||||
onCollapsedClick: () => accordion.handleStepToggle(AddStampStep.POSITION_FORMATTING),
|
||||
isVisible: hasFiles || hasResults,
|
||||
content: (
|
||||
<Stack gap="md" justify="space-between">
|
||||
{/* Mode toggle: Quick grid vs Custom drag - only show for image stamps */}
|
||||
{params.parameters.stampType === 'image' && (
|
||||
<ButtonSelector
|
||||
value={quickPositionModeSelected ? 'quick' : 'custom'}
|
||||
onChange={(v: 'quick' | 'custom') => {
|
||||
const isQuick = v === 'quick';
|
||||
setQuickPositionModeSelected(isQuick);
|
||||
setCustomPositionModeSelected(!isQuick);
|
||||
}}
|
||||
options={[
|
||||
{ value: 'quick', label: t('quickPosition', 'Quick Position') },
|
||||
{ value: 'custom', label: t('customPosition', 'Custom Position') },
|
||||
]}
|
||||
disabled={endpointLoading}
|
||||
buttonClassName={styles.modeToggleButton}
|
||||
textClassName={styles.modeToggleButtonText}
|
||||
/>
|
||||
)}
|
||||
|
||||
{params.parameters.stampType === 'image' && customPositionModeSelected && (
|
||||
<div className={styles.informationContainer}>
|
||||
<Text className={styles.informationText}>{t('AddStampRequest.customPosition', 'Drag the stamp to the desired location in the preview window.')}</Text>
|
||||
</div>
|
||||
)}
|
||||
{params.parameters.stampType === 'image' && !customPositionModeSelected && (
|
||||
<div className={styles.informationContainer}>
|
||||
<Text className={styles.informationText}>{t('AddStampRequest.quickPosition', 'Select a position on the page to place the stamp.')}</Text>
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
{/* Icon pill buttons row */}
|
||||
<div className="flex justify-between gap-[0.5rem]">
|
||||
<Tooltip content={t('AddStampRequest.rotation', 'Rotation')} position="top">
|
||||
<Button
|
||||
variant={params.parameters._activePill === 'rotation' ? 'filled' : 'outline'}
|
||||
className="flex-1"
|
||||
onClick={() => params.updateParameter('_activePill', 'rotation')}
|
||||
>
|
||||
<LocalIcon icon="rotate-right-rounded" width="1.1rem" height="1.1rem" />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
<Tooltip content={t('AddStampRequest.opacity', 'Opacity')} position="top">
|
||||
<Button
|
||||
variant={params.parameters._activePill === 'opacity' ? 'filled' : 'outline'}
|
||||
className="flex-1"
|
||||
onClick={() => params.updateParameter('_activePill', 'opacity')}
|
||||
>
|
||||
<LocalIcon icon="opacity" width="1.1rem" height="1.1rem" />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
<Tooltip content={params.parameters.stampType === 'image' ? t('AddStampRequest.imageSize', 'Image Size') : t('AddStampRequest.fontSize', 'Font Size')} position="top">
|
||||
<Button
|
||||
variant={params.parameters._activePill === 'fontSize' ? 'filled' : 'outline'}
|
||||
className="flex-1"
|
||||
onClick={() => params.updateParameter('_activePill', 'fontSize')}
|
||||
>
|
||||
<LocalIcon icon="zoom-in-map-rounded" width="1.1rem" height="1.1rem" />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
{/* Single slider bound to selected pill */}
|
||||
{params.parameters._activePill === 'fontSize' && (
|
||||
<Stack gap="xs">
|
||||
<Text className={styles.labelText}>
|
||||
{params.parameters.stampType === 'image'
|
||||
? t('AddStampRequest.imageSize', 'Image Size')
|
||||
: t('AddStampRequest.fontSize', 'Font Size')
|
||||
}
|
||||
</Text>
|
||||
<Group className={styles.sliderGroup} align="center">
|
||||
<NumberInput
|
||||
value={params.parameters.fontSize}
|
||||
onChange={(v) => params.updateParameter('fontSize', typeof v === 'number' ? v : 1)}
|
||||
min={1}
|
||||
max={400}
|
||||
step={1}
|
||||
size="sm"
|
||||
className={styles.numberInput}
|
||||
disabled={endpointLoading}
|
||||
/>
|
||||
<Slider
|
||||
value={params.parameters.fontSize}
|
||||
onChange={(v) => params.updateParameter('fontSize', v as number)}
|
||||
min={1}
|
||||
max={400}
|
||||
step={1}
|
||||
className={styles.slider}
|
||||
/>
|
||||
</Group>
|
||||
</Stack>
|
||||
)}
|
||||
{params.parameters._activePill === 'rotation' && (
|
||||
<Stack gap="xs">
|
||||
<Text className={styles.labelText}>{t('AddStampRequest.rotation', 'Rotation')}</Text>
|
||||
<Group className={styles.sliderGroup} align="center">
|
||||
<NumberInput
|
||||
value={params.parameters.rotation}
|
||||
onChange={(v) => params.updateParameter('rotation', typeof v === 'number' ? v : 0)}
|
||||
min={-180}
|
||||
max={180}
|
||||
step={1}
|
||||
size="sm"
|
||||
className={styles.numberInput}
|
||||
hideControls
|
||||
disabled={endpointLoading}
|
||||
/>
|
||||
<Slider
|
||||
value={params.parameters.rotation}
|
||||
onChange={(v) => params.updateParameter('rotation', v as number)}
|
||||
min={-180}
|
||||
max={180}
|
||||
step={1}
|
||||
className={styles.sliderWide}
|
||||
/>
|
||||
</Group>
|
||||
</Stack>
|
||||
)}
|
||||
{params.parameters._activePill === 'opacity' && (
|
||||
<Stack gap="xs">
|
||||
<Text className={styles.labelText}>{t('AddStampRequest.opacity', 'Opacity')}</Text>
|
||||
<Group className={styles.sliderGroup} align="center">
|
||||
<NumberInput
|
||||
value={params.parameters.opacity}
|
||||
onChange={(v) => params.updateParameter('opacity', typeof v === 'number' ? v : 0)}
|
||||
min={0}
|
||||
max={100}
|
||||
step={1}
|
||||
size="sm"
|
||||
className={styles.numberInput}
|
||||
disabled={endpointLoading}
|
||||
/>
|
||||
<Slider
|
||||
value={params.parameters.opacity}
|
||||
onChange={(v) => params.updateParameter('opacity', v as number)}
|
||||
min={0}
|
||||
max={100}
|
||||
step={1}
|
||||
className={styles.slider}
|
||||
/>
|
||||
</Group>
|
||||
</Stack>
|
||||
)}
|
||||
|
||||
|
||||
{params.parameters.stampType !== 'image' && (
|
||||
<ColorInput
|
||||
label={t('AddStampRequest.customColor', 'Custom Text Color')}
|
||||
value={params.parameters.customColor}
|
||||
onChange={(value) => params.updateParameter('customColor', value)}
|
||||
format="hex"
|
||||
disabled={endpointLoading}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
||||
{/* Margin selection appears when using quick grid (and for text stamps) */}
|
||||
{(params.parameters.stampType === 'text' || (params.parameters.stampType === 'image' && quickPositionModeSelected)) && (
|
||||
<Select
|
||||
label={t('AddStampRequest.margin', 'Margin')}
|
||||
value={params.parameters.customMargin}
|
||||
onChange={(v) => params.updateParameter('customMargin', (v as any) || 'medium')}
|
||||
data={[
|
||||
{ value: 'small', label: t('margin.small', 'Small') },
|
||||
{ value: 'medium', label: t('margin.medium', 'Medium') },
|
||||
{ value: 'large', label: t('margin.large', 'Large') },
|
||||
{ value: 'x-large', label: t('margin.xLarge', 'Extra Large') },
|
||||
]}
|
||||
disabled={endpointLoading}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
||||
{/* Unified preview wrapped with obscured overlay if no stamp selected in step 4 */}
|
||||
<ObscuredOverlay
|
||||
obscured={
|
||||
accordion.currentStep === AddStampStep.POSITION_FORMATTING &&
|
||||
((params.parameters.stampType === 'text' && params.parameters.stampText.trim().length === 0) ||
|
||||
(params.parameters.stampType === 'image' && !params.parameters.stampImage))
|
||||
}
|
||||
overlayMessage={
|
||||
<Text size="sm" c="white" fw={600}>
|
||||
{t('AddStampRequest.noStampSelected', 'No stamp selected. Return to Step 1.')}
|
||||
</Text>
|
||||
}
|
||||
>
|
||||
<StampPreview
|
||||
parameters={params.parameters}
|
||||
onParameterChange={params.updateParameter}
|
||||
file={selectedFiles[0] || null}
|
||||
showQuickGrid={params.parameters.stampType === 'text' ? true : quickPositionModeSelected}
|
||||
/>
|
||||
</ObscuredOverlay>
|
||||
</Stack>
|
||||
),
|
||||
});
|
||||
|
||||
return steps;
|
||||
};
|
||||
|
||||
return createToolFlow({
|
||||
files: {
|
||||
selectedFiles,
|
||||
isCollapsed: hasResults,
|
||||
},
|
||||
steps: getSteps(),
|
||||
executeButton: {
|
||||
text: t('AddStampRequest.submit', 'Add Stamp'),
|
||||
isVisible: !hasResults,
|
||||
loadingText: t('loading'),
|
||||
onClick: handleExecute,
|
||||
disabled: !params.validateParameters() || !hasFiles || !endpointEnabled,
|
||||
},
|
||||
review: {
|
||||
isVisible: hasResults,
|
||||
operation: operation,
|
||||
title: t('AddStampRequest.results.title', 'Stamp Results'),
|
||||
onFileClick: (file) => onPreviewFile?.(file),
|
||||
onUndo: async () => {
|
||||
await operation.undoOperation();
|
||||
onPreviewFile?.(null);
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
AddStamp.tool = () => useAddStampOperation;
|
||||
|
||||
export default AddStamp as ToolComponent;
|
||||
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import React, { useEffect } from "react";
|
||||
import { BaseToolProps } from "../types/tool";
|
||||
import { withBasePath } from "../constants/app";
|
||||
|
||||
const SwaggerUI: React.FC<BaseToolProps> = () => {
|
||||
useEffect(() => {
|
||||
// Redirect to Swagger UI
|
||||
window.open(withBasePath("/swagger-ui/5.21.0/index.html"), "_blank");
|
||||
window.open("/swagger-ui/5.21.0/index.html", "_blank");
|
||||
}, []);
|
||||
|
||||
return (
|
||||
@@ -13,7 +12,7 @@ const SwaggerUI: React.FC<BaseToolProps> = () => {
|
||||
<p>Opening Swagger UI in a new tab...</p>
|
||||
<p>
|
||||
If it didn't open automatically,{" "}
|
||||
<a href={withBasePath("/swagger-ui/5.21.0/index.html")} target="_blank" rel="noopener noreferrer">
|
||||
<a href="/swagger-ui/5.21.0/index.html" target="_blank" rel="noopener noreferrer">
|
||||
click here
|
||||
</a>
|
||||
</p>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Define all possible tool IDs as source of truth
|
||||
export const TOOL_IDS = [
|
||||
const TOOL_IDS = [
|
||||
'certSign',
|
||||
'sign',
|
||||
'addPassword',
|
||||
|
||||
@@ -410,7 +410,7 @@ export async function generateThumbnailWithMetadata(file: File): Promise<Thumbna
|
||||
throw new Error('Could not get canvas context');
|
||||
}
|
||||
|
||||
await page.render({ canvasContext: context, viewport, canvas }).promise;
|
||||
await page.render({ canvasContext: context, viewport }).promise;
|
||||
const thumbnail = canvas.toDataURL();
|
||||
|
||||
pdfWorkerManager.destroyDocument(pdf);
|
||||
|
||||
@@ -2,20 +2,10 @@ import { ToolId } from '../types/toolId';
|
||||
|
||||
// Map URL paths to tool keys (multiple URLs can map to same tool)
|
||||
export const URL_TO_TOOL_MAP: Record<string, ToolId> = {
|
||||
// Basic tools - standard patterns
|
||||
'/split': 'split',
|
||||
'/split-pdfs': 'split',
|
||||
'/merge': 'merge',
|
||||
'/split': 'split',
|
||||
'/merge-pdfs': 'merge',
|
||||
'/compress': 'compress',
|
||||
'/compress-pdf': 'compress',
|
||||
'/rotate': 'rotate',
|
||||
'/rotate-pdf': 'rotate',
|
||||
'/repair': 'repair',
|
||||
'/flatten': 'flatten',
|
||||
'/crop': 'crop',
|
||||
|
||||
// Convert tool and all its variants
|
||||
'/convert': 'convert',
|
||||
'/convert-pdf': 'convert',
|
||||
'/file-to-pdf': 'convert',
|
||||
@@ -28,101 +18,20 @@ export const URL_TO_TOOL_MAP: Record<string, ToolId> = {
|
||||
'/pdf-to-pdfa': 'convert',
|
||||
'/pdf-to-word': 'convert',
|
||||
'/pdf-to-xml': 'convert',
|
||||
|
||||
// Security tools
|
||||
'/add-password': 'addPassword',
|
||||
'/remove-password': 'removePassword',
|
||||
'/change-permissions': 'changePermissions',
|
||||
'/cert-sign': 'certSign',
|
||||
'/manage-signatures': 'certSign',
|
||||
'/remove-certificate-sign': 'removeCertSign',
|
||||
'/remove-cert-sign': 'removeCertSign',
|
||||
'/unlock-pdf-forms': 'unlockPDFForms',
|
||||
'/validate-signature': 'validateSignature',
|
||||
'/manage-certificates': 'manageCertificates',
|
||||
|
||||
// Content manipulation
|
||||
'/sanitize': 'sanitize',
|
||||
'/sanitize-pdf': 'sanitize',
|
||||
'/ocr': 'ocr',
|
||||
'/ocr-pdf': 'ocr',
|
||||
'/watermark': 'watermark',
|
||||
'/add-watermark': 'watermark',
|
||||
'/add-image': 'addImage',
|
||||
'/add-stamp': 'addStamp',
|
||||
'/add-page-numbers': 'addPageNumbers',
|
||||
'/redact': 'redact',
|
||||
|
||||
// Page manipulation
|
||||
'/remove-pages': 'removePages',
|
||||
'/remove-blanks': 'removeBlanks',
|
||||
'/extract-pages': 'extractPages',
|
||||
'/reorganize-pages': 'reorganizePages',
|
||||
'/remove-password': 'removePassword',
|
||||
'/single-large-page': 'pdfToSinglePage',
|
||||
'/page-layout': 'pageLayout',
|
||||
'/scale-pages': 'scalePages',
|
||||
'/repair': 'repair',
|
||||
'/rotate-pdf': 'rotate',
|
||||
'/unlock-pdf-forms': 'unlockPDFForms',
|
||||
'/remove-certificate-sign': 'removeCertSign',
|
||||
'/remove-cert-sign': 'removeCertSign',
|
||||
'/cert-sign': 'certSign',
|
||||
'/manage-signatures': 'certSign',
|
||||
'/booklet-imposition': 'bookletImposition',
|
||||
|
||||
// Splitting tools
|
||||
'/auto-split-pdf': 'autoSplitPDF',
|
||||
'/auto-size-split-pdf': 'autoSizeSplitPDF',
|
||||
'/scanner-image-split': 'scannerImageSplit',
|
||||
|
||||
// Annotation and content removal
|
||||
'/remove-annotations': 'removeAnnotations',
|
||||
'/remove-image': 'removeImage',
|
||||
|
||||
// Image and visual tools
|
||||
'/extract-images': 'extractImages',
|
||||
'/adjust-contrast': 'adjustContrast',
|
||||
'/fake-scan': 'fakeScan',
|
||||
'/replace-color-pdf': 'replaceColorPdf',
|
||||
|
||||
// Metadata and info
|
||||
'/change-metadata': 'changeMetadata',
|
||||
'/get-pdf-info': 'getPdfInfo',
|
||||
'/add-attachments': 'addAttachments',
|
||||
|
||||
// Advanced tools
|
||||
'/overlay-pdfs': 'overlayPdfs',
|
||||
'/edit-table-of-contents': 'editTableOfContents',
|
||||
'/auto-rename': 'autoRename',
|
||||
'/compare': 'compare',
|
||||
'/multi-tool': 'multiTool',
|
||||
'/show-js': 'showJS',
|
||||
|
||||
// Special/utility tools
|
||||
'/read': 'read',
|
||||
'/automate': 'automate',
|
||||
'/sign': 'sign',
|
||||
|
||||
// Developer tools
|
||||
'/dev-api': 'devApi',
|
||||
'/dev-folder-scanning': 'devFolderScanning',
|
||||
'/dev-sso-guide': 'devSsoGuide',
|
||||
'/dev-airgapped': 'devAirgapped',
|
||||
|
||||
// Legacy URL mappings from sitemap
|
||||
'/pdf-organizer': 'reorganizePages',
|
||||
'/multi-page-layout': 'pageLayout',
|
||||
'/extract-page': 'extractPages',
|
||||
'/pdf-to-single-page': 'pdfToSinglePage',
|
||||
'/img-to-pdf': 'convert',
|
||||
'/pdf-to-presentation': 'convert',
|
||||
'/pdf-to-text': 'convert',
|
||||
'/pdf-to-html': 'convert',
|
||||
'/auto-redact': 'redact',
|
||||
'/stamp': 'addStamp',
|
||||
'/view-pdf': 'read',
|
||||
'/get-info-on-pdf': 'getPdfInfo',
|
||||
'/remove-image-pdf': 'removeImage',
|
||||
'/replace-and-invert-color-pdf': 'replaceColorPdf',
|
||||
'/pipeline': 'automate',
|
||||
'/extract-image-scans': 'scannerImageSplit',
|
||||
'/show-javascript': 'showJS',
|
||||
'/scanner-effect': 'fakeScan',
|
||||
'/split-by-size-or-count': 'autoSizeSplitPDF',
|
||||
'/overlay-pdf': 'overlayPdfs',
|
||||
'/split-pdf-by-sections': 'autoSplitPDF',
|
||||
'/split-pdf-by-chapters': 'autoSplitPDF',
|
||||
};
|
||||
|
||||
@@ -8,17 +8,12 @@ import { getDefaultWorkbench } from '../types/workbench';
|
||||
import { ToolRegistry, getToolWorkbench, getToolUrlPath } from '../data/toolsTaxonomy';
|
||||
import { firePixel } from './scarfTracking';
|
||||
import { URL_TO_TOOL_MAP } from './urlMapping';
|
||||
import { BASE_PATH, withBasePath } from '../constants/app';
|
||||
|
||||
/**
|
||||
* Parse the current URL to extract tool routing information
|
||||
*/
|
||||
export function parseToolRoute(registry: ToolRegistry): ToolRoute {
|
||||
const fullPath = window.location.pathname;
|
||||
// Remove base path to get app-relative path
|
||||
const path = BASE_PATH && fullPath.startsWith(BASE_PATH)
|
||||
? fullPath.slice(BASE_PATH.length) || '/'
|
||||
: fullPath;
|
||||
const path = window.location.pathname;
|
||||
const searchParams = new URLSearchParams(window.location.search);
|
||||
|
||||
// First, check URL mapping for multiple URL aliases
|
||||
@@ -88,8 +83,7 @@ export function updateToolRoute(toolId: ToolId, registry: ToolRegistry, replace:
|
||||
return;
|
||||
}
|
||||
|
||||
const toolPath = getToolUrlPath(toolId, tool);
|
||||
const newPath = withBasePath(toolPath);
|
||||
const newPath = getToolUrlPath(toolId, tool);
|
||||
const searchParams = new URLSearchParams(window.location.search);
|
||||
|
||||
// Remove tool query parameter since we're using path-based routing
|
||||
@@ -105,7 +99,7 @@ export function clearToolRoute(replace: boolean = false): void {
|
||||
const searchParams = new URLSearchParams(window.location.search);
|
||||
searchParams.delete('tool');
|
||||
|
||||
updateUrl(withBasePath('/'), searchParams, replace);
|
||||
updateUrl('/', searchParams, replace);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -123,12 +117,11 @@ export function generateShareableUrl(toolId: ToolId | null, registry: ToolRegist
|
||||
const baseUrl = window.location.origin;
|
||||
|
||||
if (!toolId || !registry[toolId]) {
|
||||
return `${baseUrl}${BASE_PATH || ''}`;
|
||||
return baseUrl;
|
||||
}
|
||||
|
||||
const tool = registry[toolId];
|
||||
|
||||
const toolPath = getToolUrlPath(toolId, tool);
|
||||
const fullPath = withBasePath(toolPath);
|
||||
return `${baseUrl}${fullPath}`;
|
||||
const path = getToolUrlPath(toolId, tool);
|
||||
return `${baseUrl}${path}`;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { defineConfig } from 'vite';
|
||||
import react from '@vitejs/plugin-react-swc';
|
||||
import react from '@vitejs/plugin-react';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
@@ -12,10 +12,5 @@ export default defineConfig({
|
||||
},
|
||||
},
|
||||
},
|
||||
optimizeDeps: {
|
||||
esbuildOptions: {
|
||||
target: 'es2020'
|
||||
}
|
||||
},
|
||||
base: process.env.RUN_SUBPATH ? `/${process.env.RUN_SUBPATH}` : './',
|
||||
base: "./",
|
||||
});
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { defineConfig } from 'vitest/config'
|
||||
import react from '@vitejs/plugin-react-swc';
|
||||
import react from '@vitejs/plugin-react'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
@@ -37,4 +37,4 @@ export default defineConfig({
|
||||
'@': '/src'
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user