Merge pull request 'Migration to sveltekit' (#27) from development into main
Some checks failed
Deploy / deploy (push) Failing after 16s

Reviewed-on: #27
This commit is contained in:
Leonardo Murça 2025-06-04 21:43:03 +00:00
commit c71dbaa0b9
121 changed files with 4701 additions and 2180 deletions

17
.editorconfig Normal file
View file

@ -0,0 +1,17 @@
# EditorConfig helps developers define and maintain consistent
# coding styles between different editors and IDEs
# http://editorconfig.org
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[{package.json,*.yml,*.js}]
indent_style = space
indent_size = 2

32
.eslintrc.cjs Normal file
View file

@ -0,0 +1,32 @@
/** @type {import('eslint').Linter.Config} */
module.exports = {
root: true,
env: {
browser: true,
es2022: true,
node: true,
},
extends: [
'eslint:recommended',
'plugin:svelte/recommended',
'prettier',
],
overrides: [
{
files: ['*.svelte'],
processor: 'svelte3/svelte3',
},
],
plugins: ['svelte'],
settings: {
// Let ESLint understand Svelte
'svelte3/ignore-styles': () => true,
},
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
},
rules: {
// Customize your rules here
},
};

View file

@ -18,23 +18,19 @@ jobs:
with:
node-version: 19
- name: Install rsync
run: |
apt-get update
apt-get install -y rsync
env:
SSH_PRIVATE_KEY: ${{secrets.SSH_KEY}}
SSH_KNOWN_HOSTS: ${{secrets.SSH_KNOWN_HOSTS}}
- name: Install dependencies
run: npm install
- name: Build app
run: npm run build
- name: Install PM2
run: npm i -g pm2
- name: Add Deploy Key to SSH
run: |
mkdir ~/.ssh
echo "${{ secrets.SSH_KEY }}" >> ~/.ssh/id_ed25519_embroideryviewer
chmod 400 ~/.ssh/id_ed25519_embroideryviewer
echo -e "Host embroideryviewer\n\tUser embroideryviewer\n\tHostname 45.76.5.44\n\tIdentityFile ~/.ssh/id_ed25519_embroideryviewer\n\tStrictHostKeyChecking No" >> ~/.ssh/config
mkdir -p ~/.ssh
echo "${{ secrets.SSH_KEY }}" >> ./deploy.key
sudo chmod 600 ./deploy.key
echo "${{ secrets.SSH_KNOWN_HOSTS}}" > ~/.ssh/known_hosts
- name: Upload changes to server
run: rsync -avz --progress dist/ embroideryviewer:web/prod
- name: Deploy
run: pm2 deploy ecosystem.config.cjs production

33
.gitignore vendored
View file

@ -1,25 +1,10 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
/.vscode
node_modules
/build
/.svelte-kit
/package
.env
.env.*
!.env.example
vite.config.js.timestamp-*
vite.config.ts.timestamp-*

22
.prettierignore Normal file
View file

@ -0,0 +1,22 @@
# Ignore node_modules
node_modules/
# Build output
.build/
.svelte-kit/
dist/
# Ignore lock files
package-lock.json
pnpm-lock.yaml
yarn.lock
# Ignore environment files
.env
.env.*.local
# VSCode settings
.vscode/
# Ignore output from lint or test tools
coverage/

10
.prettierrc Normal file
View file

@ -0,0 +1,10 @@
{
"singleQuote": true,
"useTabs": false,
"tabWidth": 2,
"trailingComma": "all",
"printWidth": 80,
"semi": true,
"bracketSpacing": true,
"arrowParens": "always"
}

21
LICENSE
View file

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2022 Leonardo Murça
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -1,10 +1,38 @@
# Embroidery Viewer
# sv
A free online tool to view embroidery files.
Available at https://embroideryviewer.xyz.
Everything you need to build a Svelte project, powered by [`sv`](https://github.com/sveltejs/cli).
![Demo](/demo.gif)
## Creating a project
Current supported formats: **.pes, .dst, .pec, .jef and .exp**.
If you're seeing this, you've probably already done this step. Congrats!
Inspired by https://github.com/redteam316/html5-embroidery.git.
```bash
# create a new project in the current directory
npx sv create
# create a new project in my-app
npx sv create my-app
```
## Developing
Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server:
```bash
npm run dev
# or start the server and open the app in a new browser tab
npm run dev -- --open
```
## Building
To create a production version of your app:
```bash
npm run build
```
You can preview the production build with `npm run preview`.
> To deploy your app, you may need to install an [adapter](https://svelte.dev/docs/kit/adapters) for your target environment.

BIN
demo.gif

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.9 MiB

34
ecosystem.config.cjs Normal file
View file

@ -0,0 +1,34 @@
module.exports = {
apps: [
{
name: 'embroidery-viewer',
script: './build/index.js',
time: true,
instances: 1,
autorestart: true,
max_restarts: 50,
watch: false,
max_memory_restart: '1G',
env: {
NODE_ENV: 'production',
},
},
],
deploy: {
production: {
user: 'deployer',
host: '45.76.5.44',
key: 'deploy.key',
ref: 'origin/main',
repo: 'git@git.leomurca.xyz:leomurca/embroidery-viewer.git',
path: '/home/deployer/embroidery-viewer',
'pre-deploy': 'rm package-lock.json && npm i',
'post-deploy':
'npm run build && pm2 reload ecosystem.config.cjs --only acelera-alagoas-prod --env production && pm2 save',
env: {
PORT: 7017,
NODE_ENV: 'production',
},
},
},
};

26
eslint.config.js Normal file
View file

@ -0,0 +1,26 @@
import prettier from 'eslint-config-prettier';
import js from '@eslint/js';
import { includeIgnoreFile } from '@eslint/compat';
import svelte from 'eslint-plugin-svelte';
import globals from 'globals';
import { fileURLToPath } from 'node:url';
import svelteConfig from './svelte.config.js';
const gitignorePath = fileURLToPath(new URL('./.gitignore', import.meta.url));
export default [
includeIgnoreFile(gitignorePath),
js.configs.recommended,
...svelte.configs.recommended,
prettier,
...svelte.configs.prettier,
{
languageOptions: {
globals: { ...globals.browser, ...globals.node }
}
},
{
files: ['**/*.svelte', '**/*.svelte.js'],
languageOptions: { parserOptions: { svelteConfig } }
}
];

View file

@ -1,27 +0,0 @@
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="author" content="Leonardo Murça" />
<meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<meta name="apple-mobile-web-app-title" content="Embroidery Viewer" />
<script defer src="https://umami.leomurca.xyz/script.js" data-website-id="bd4c0533-36e6-402d-ac04-577993aaf43a"></script>
<link rel="icon" type="image/png" href="/favicon-96x96.png" sizes="96x96" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="shortcut icon" href="/favicon.ico" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />
<link rel="manifest" href="/site.webmanifest" />
<link rel="canonical" href="https://embroideryviewer.xyz/">
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>

View file

@ -1,33 +1,19 @@
{
"compilerOptions": {
"moduleResolution": "Node",
"target": "ESNext",
"module": "ESNext",
/**
* svelte-preprocess cannot figure out whether you have
* a value or a type, so tell TypeScript to enforce using
* `import type` instead of `import` for Types.
*/
"importsNotUsedAsValues": "error",
"isolatedModules": true,
"resolveJsonModule": true,
/**
* To have warnings / errors of the Svelte compiler at the
* correct position, enable source maps by default.
*/
"sourceMap": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
/**
* Typecheck JS in `.svelte` and `.js` files by default.
* Disable this if you'd like to use dynamic types.
*/
"checkJs": true
},
/**
* Use global.d.ts instead of compilerOptions.types
* to avoid limiting type declarations.
*/
"include": ["src/**/*.d.ts", "src/**/*.js", "src/**/*.svelte"]
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"moduleResolution": "bundler"
}
// Path aliases are handled by https://svelte.dev/docs/kit/configuration#alias
// except $lib which is handled by https://svelte.dev/docs/kit/configuration#files
//
// If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes
// from the referenced tsconfig.json - TypeScript does not merge them in
}

2082
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -1,17 +1,37 @@
{
"name": "embroidery-viewer",
"private": true,
"version": "2.0.3",
"version": "0.0.1",
"type": "module",
"scripts": {
"dev": "vite",
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"postbuild": "npx svelte-sitemap --domain https://embroideryviewer.xyz -o dist"
"prepare": "svelte-kit sync || echo ''",
"check": "svelte-kit sync && svelte-check --tsconfig ./jsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./jsconfig.json --watch",
"format": "prettier --write .",
"lint": "prettier --check . && eslint ."
},
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "^5.0.3",
"svelte": "^5.23.3",
"vite": "^6.2.3"
"@eslint/compat": "^1.2.5",
"@eslint/js": "^9.18.0",
"@sveltejs/adapter-auto": "^6.0.0",
"@sveltejs/kit": "^2.16.0",
"@sveltejs/vite-plugin-svelte": "^5.0.0",
"eslint": "^9.28.0",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-svelte": "^3.9.1",
"globals": "^16.0.0",
"prettier": "^3.5.3",
"prettier-plugin-svelte": "^3.3.3",
"svelte": "^5.0.0",
"svelte-check": "^4.0.0",
"typescript": "^5.0.0",
"vite": "^6.2.6"
},
"dependencies": {
"accept-language-parser": "^1.5.0",
"sveltekit-i18n": "^2.4.2"
}
}

View file

@ -1 +0,0 @@
google.com, pub-5761689301112420, DIRECT, f08c47fec0942fa0

View file

@ -1,11 +0,0 @@
<script>
import Head from "./lib/sections/Head.svelte";
import Header from "./lib/sections/Header.svelte";
import Footer from "./lib/sections/Footer.svelte";
import Main from "./lib/sections/Main.svelte";
</script>
<Head/>
<Header />
<Main />
<Footer />

View file

@ -1,74 +0,0 @@
:root {
font-family: Inter, Avenir, Helvetica, Arial, sans-serif;
font-size: 16px;
line-height: 24px;
font-weight: 400;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-text-size-adjust: 100%;
}
* {
box-sizing: border-box;
}
body {
display: flex;
justify-content: center;
flex-direction: column;
margin: 0;
width: 100%;
height: 100%;
}
#app {
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
background-color: #F2F6F5;
z-index: 10;
}
input[type="submit"] {
width: 100%;
font-size: 20px;
margin-top: 20px;
background-color: #05345f;
font-weight: 700;
color: white;
padding: 10px;
-webkit-appearance: none;
border-radius: 0;
}
input[type="submit"]:hover {
cursor: pointer;
background-color: black;
color: white;
}
body a {
text-decoration: none;
color: #06345F;
border-bottom: 3px solid #06345F;
}
body a:hover {
background-color: #06345F;
color: #ffffff;
}
:is(h1, h2, h3, h4, h5, h6) {
color: #06345F;
}
strong {
color: #06345F;
}
ul li::marker {
color: #06345F;
}

13
src/app.d.ts vendored Normal file
View file

@ -0,0 +1,13 @@
// See https://svelte.dev/docs/kit/types#app.d.ts
// for information about these interfaces
declare global {
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
// interface PageState {}
// interface Platform {}
}
}
export {};

95
src/app.html Normal file
View file

@ -0,0 +1,95 @@
<!doctype html>
<html lang="en">
<head>
<style>
:root {
font-family: Inter, Avenir, Helvetica, Arial, sans-serif;
font-size: 16px;
line-height: 24px;
font-weight: 400;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-text-size-adjust: 100%;
}
* {
box-sizing: border-box;
}
body {
display: flex;
justify-content: center;
flex-direction: column;
margin: 0;
width: 100%;
height: 100%;
}
#app {
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
background-color: #f2f6f5;
z-index: 10;
}
input[type='submit'] {
width: 100%;
font-size: 20px;
margin-top: 20px;
background-color: #05345f;
font-weight: 700;
color: white;
padding: 10px;
-webkit-appearance: none;
border-radius: 0;
}
input[type='submit']:hover {
cursor: pointer;
background-color: black;
color: white;
}
body a {
text-decoration: none;
color: #06345f;
border-bottom: 3px solid #06345f;
}
body a:hover {
background-color: #06345f;
color: #ffffff;
}
:is(h1, h2, h3, h4, h5, h6) {
color: #06345f;
}
strong {
color: #06345f;
}
ul li::marker {
color: #06345f;
}
</style>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" type="image/png" href="/favicon-96x96.png" sizes="96x96" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="shortcut icon" href="/favicon.ico" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />
<link rel="manifest" href="/site.webmanifest" />
<link rel="canonical" href="https://embroideryviewer.xyz/" />
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 124 KiB

View file

@ -1,75 +0,0 @@
import { jDataView } from "./jdataview";
import { supportedFormats } from "../format-readers";
import { Pattern } from "./pattern";
function renderFile(filename, evt, canvas, colorView, stitchesView, sizeView, localizedStrings) {
const fileExtension = filename.toLowerCase().split(".").pop();
const view = jDataView(evt.target.result, 0, evt.size);
const pattern = new Pattern();
supportedFormats[fileExtension].read(view, pattern);
pattern.moveToPositive();
pattern.drawShapeTo(canvas);
pattern.drawColorsTo(colorView);
pattern.drawStitchesCountTo(stitchesView, localizedStrings.stitches);
pattern.drawSizeValuesTo(stitchesView, localizedStrings.dimensions);
}
function renderAbortMessage(errorMessageRef) {
errorMessageRef.innerHTML = "Render aborted!";
}
function renderErrorMessage(errorName, errorMessageRef) {
let message;
switch (errorName) {
case "NotFoundError":
message =
"The file could not be found at the time the read was processed.";
break;
case "SecurityError":
message = "<p>A file security error occured. This can be due to:</p>";
message +=
"<ul><li>Accessing certain files deemed unsafe for Web applications.</li>";
message += "<li>Performing too many read calls on file resources.</li>";
message +=
"<li>The file has changed on disk since the user selected it.</li></ul>";
break;
case "NotReadableError":
message =
"The file cannot be read. This can occur if the file is open in another application.";
break;
case "EncodingError":
message = "The length of the data URL for the file is too long.";
break;
default:
message = "Something wrong happened!";
break;
}
errorMessageRef.innerHTML = message;
}
export default function renderFileToCanvas(
fileObject,
canvas,
errorMessageRef,
colorView,
stitchesView,
sizeView,
localizedStrings
) {
const reader = new FileReader();
reader.onloadend = (evt) =>
renderFile(fileObject.name, evt, canvas, colorView, stitchesView, sizeView, localizedStrings);
reader.abort = (/** @type {any} */ _) => renderAbortMessage(errorMessageRef);
reader.onerror = (evt) =>
renderErrorMessage(evt.target.error.name, errorMessageRef);
if (fileObject) {
reader.readAsArrayBuffer(fileObject);
}
return "";
}

View file

@ -1,225 +0,0 @@
import { rgbToHex } from "../utils/rgbToHex";
import { shadeColor } from "../utils/shadeColor";
function Stitch(x, y, flags, color) {
this.flags = flags;
this.x = x;
this.y = y;
this.color = color;
}
function Color(r, g, b, description) {
this.r = r;
this.g = g;
this.b = b;
this.description = description;
}
const stitchTypes = {
normal: 0,
jump: 1,
trim: 2,
stop: 4,
end: 8,
};
function Pattern() {
this.colors = [];
this.stitches = [];
this.hoop = {};
this.lastX = 0;
this.lastY = 0;
this.top = 0;
this.bottom = 0;
this.left = 0;
this.right = 0;
this.currentColorIndex = 0;
}
Pattern.prototype.addColorRgb = function (r, g, b, description) {
this.colors[this.colors.length] = new Color(r, g, b, description);
};
Pattern.prototype.addColor = function (color) {
this.colors[this.colors.length] = color;
};
Pattern.prototype.addStitchAbs = function (x, y, flags, isAutoColorIndex) {
if ((flags & stitchTypes.end) === stitchTypes.end) {
this.calculateBoundingBox();
this.fixColorCount();
}
if (
(flags & stitchTypes.stop) === stitchTypes.stop &&
this.stitches.length === 0
) {
return;
}
if ((flags & stitchTypes.stop) === stitchTypes.stop && isAutoColorIndex) {
this.currentColorIndex += 1;
}
this.stitches[this.stitches.length] = new Stitch(
x,
y,
flags,
this.currentColorIndex
);
};
Pattern.prototype.addStitchRel = function (dx, dy, flags, isAutoColorIndex) {
if (this.stitches.length !== 0) {
let nx = this.lastX + dx,
ny = this.lastY + dy;
this.lastX = nx;
this.lastY = ny;
this.addStitchAbs(nx, ny, flags, isAutoColorIndex);
} else {
this.addStitchAbs(dx, dy, flags, isAutoColorIndex);
}
};
Pattern.prototype.calculateBoundingBox = function () {
let i = 0,
stitchCount = this.stitches.length,
pt;
if (stitchCount === 0) {
this.bottom = 1;
this.right = 1;
return;
}
this.left = 99999;
this.top = 99999;
this.right = -99999;
this.bottom = -99999;
for (i = 0; i < stitchCount; i += 1) {
pt = this.stitches[i];
if (!(pt.flags & stitchTypes.trim)) {
this.left = this.left < pt.x ? this.left : pt.x;
this.top = this.top < pt.y ? this.top : pt.y;
this.right = this.right > pt.x ? this.right : pt.x;
this.bottom = this.bottom > pt.y ? this.bottom : pt.y;
}
}
};
Pattern.prototype.moveToPositive = function () {
let i = 0,
stitchCount = this.stitches.length;
for (i = 0; i < stitchCount; i += 1) {
this.stitches[i].x -= this.left;
this.stitches[i].y -= this.top;
}
this.right -= this.left;
this.left = 0;
this.bottom -= this.top;
this.top = 0;
};
Pattern.prototype.invertPatternVertical = function () {
let i = 0,
temp = -this.top,
stitchCount = this.stitches.length;
for (i = 0; i < stitchCount; i += 1) {
this.stitches[i].y = -this.stitches[i].y;
}
this.top = -this.bottom;
this.bottom = temp;
};
Pattern.prototype.addColorRandom = function () {
this.colors[this.colors.length] = new Color(
Math.round(Math.random() * 256),
Math.round(Math.random() * 256),
Math.round(Math.random() * 256),
"random"
);
};
Pattern.prototype.fixColorCount = function () {
let maxColorIndex = 0,
stitchCount = this.stitches.length,
i;
for (i = 0; i < stitchCount; i += 1) {
maxColorIndex = Math.max(maxColorIndex, this.stitches[i].color);
}
while (this.colors.length <= maxColorIndex) {
this.addColorRandom();
}
this.colors.splice(maxColorIndex + 1, this.colors.length - maxColorIndex - 1);
};
Pattern.prototype.drawShapeTo = function (canvas) {
canvas.width = this.right;
canvas.height = this.bottom;
let gradient, tx, ty;
let lastStitch = this.stitches[0];
let gWidth = 100;
if (canvas.getContext) {
const ctx = canvas.getContext("2d");
ctx.lineWidth = 3;
ctx.lineJoin = "round";
let color = this.colors[this.stitches[0].color];
for (let i = 0; i < this.stitches.length; i++) {
const currentStitch = this.stitches[i];
if (i > 0) lastStitch = this.stitches[i - 1];
tx = currentStitch.x - lastStitch.x;
ty = currentStitch.y - lastStitch.y;
gWidth = Math.sqrt(tx * tx + ty * ty);
gradient = ctx.createRadialGradient(
currentStitch.x - tx,
currentStitch.y - ty,
0,
currentStitch.x - tx,
currentStitch.y - ty,
gWidth * 1.4
);
gradient.addColorStop("0", shadeColor(rgbToHex(color), -60));
gradient.addColorStop("0.05", rgbToHex(color));
gradient.addColorStop("0.5", shadeColor(rgbToHex(color), 60));
gradient.addColorStop("0.9", rgbToHex(color));
gradient.addColorStop("1.0", shadeColor(rgbToHex(color), -60));
ctx.strokeStyle = gradient;
if (
currentStitch.flags === stitchTypes.jump ||
currentStitch.flags === stitchTypes.trim ||
currentStitch.flags === stitchTypes.stop
) {
color = this.colors[currentStitch.color];
ctx.beginPath();
ctx.strokeStyle =
"rgba(" + color.r + "," + color.g + "," + color.b + ",0)";
ctx.moveTo(currentStitch.x, currentStitch.y);
ctx.stroke();
}
ctx.beginPath();
ctx.moveTo(lastStitch.x, lastStitch.y);
ctx.lineTo(currentStitch.x, currentStitch.y);
ctx.stroke();
lastStitch = currentStitch;
}
}
};
Pattern.prototype.drawColorsTo = function (colorContainer) {
this.colors.forEach((color) => {
colorContainer.innerHTML += `<div style='background-color: rgb(${color.r}, ${color.g}, ${color.b}); height: 25px; width: 25px; border: 1px solid #000000; border-radius: 16px;'></div>`;
});
};
Pattern.prototype.drawStitchesCountTo = function (stitchesContainer, stitchesString) {
stitchesContainer.innerHTML += `<div><strong>${stitchesString}:</strong> ${this.stitches.length} </div>`;
};
Pattern.prototype.drawSizeValuesTo = function (sizeContainer, dimensionsString) {
sizeContainer.innerHTML += `<div><strong>${dimensionsString}:</strong> ${Math.round(
this.right / 10
)}mm x ${Math.round(this.bottom / 10)}mm </div>`;
};
export { Pattern, Color, stitchTypes };

View file

@ -1,107 +0,0 @@
// @ts-nocheck
import { stitchTypes } from "../file-renderer/pattern";
function decodeExp(b2) {
let returnCode = 0;
if (b2 === 0xf3) {
return stitchTypes.end;
}
if ((b2 & 0xc3) === 0xc3) {
return stitchTypes.trim | stitchTypes.stop;
}
if (b2 & 0x80) {
returnCode |= stitchTypes.trim;
}
if (b2 & 0x40) {
returnCode |= stitchTypes.stop;
}
return returnCode;
}
export function dstRead(file, pattern) {
let flags,
x,
y,
prevJump = false,
thisJump = false,
b = [],
byteCount = file.byteLength;
file.seek(512);
while (file.tell() < byteCount - 3) {
b[0] = file.getUint8();
b[1] = file.getUint8();
b[2] = file.getUint8();
x = 0;
y = 0;
if (b[0] & 0x01) {
x += 1;
}
if (b[0] & 0x02) {
x -= 1;
}
if (b[0] & 0x04) {
x += 9;
}
if (b[0] & 0x08) {
x -= 9;
}
if (b[0] & 0x80) {
y += 1;
}
if (b[0] & 0x40) {
y -= 1;
}
if (b[0] & 0x20) {
y += 9;
}
if (b[0] & 0x10) {
y -= 9;
}
if (b[1] & 0x01) {
x += 3;
}
if (b[1] & 0x02) {
x -= 3;
}
if (b[1] & 0x04) {
x += 27;
}
if (b[1] & 0x08) {
x -= 27;
}
if (b[1] & 0x80) {
y += 3;
}
if (b[1] & 0x40) {
y -= 3;
}
if (b[1] & 0x20) {
y += 27;
}
if (b[1] & 0x10) {
y -= 27;
}
if (b[2] & 0x04) {
x += 81;
}
if (b[2] & 0x08) {
x -= 81;
}
if (b[2] & 0x20) {
y += 81;
}
if (b[2] & 0x10) {
y -= 81;
}
flags = decodeExp(b[2]);
thisJump = flags & stitchTypes.jump;
if (prevJump) {
flags |= stitchTypes.jump;
}
pattern.addStitchRel(x, y, flags, true);
prevJump = thisJump;
}
pattern.addStitchRel(0, 0, stitchTypes.end, true);
pattern.invertPatternVertical();
}

View file

@ -1,50 +0,0 @@
import { stitchTypes } from "../file-renderer/pattern";
function expDecode(input) {
return input > 128 ? -(~input & 255) - 1 : input;
}
export function expRead(file, pattern) {
let b0 = 0,
b1 = 0,
dx = 0,
dy = 0,
flags = 0,
i = 0,
byteCount = file.byteLength;
while (i < byteCount) {
flags = stitchTypes.normal;
b0 = file.getInt8(i);
i += 1;
b1 = file.getInt8(i);
i += 1;
if (b0 === -128) {
if (b1 & 1) {
b0 = file.getInt8(i);
i += 1;
b1 = file.getInt8(i);
i += 1;
flags = stitchTypes.stop;
} else if (b1 === 2 || b1 === 4) {
b0 = file.getInt8(i);
i += 1;
b1 = file.getInt8(i);
i += 1;
flags = stitchTypes.trim;
} else if (b1 === -128) {
b0 = file.getInt8(i);
i += 1;
b1 = file.getInt8(i);
i += 1;
b0 = 0;
b1 = 0;
flags = stitchTypes.trim;
}
}
dx = expDecode(b0);
dy = expDecode(b1);
pattern.addStitchRel(dx, dy, flags, true);
}
pattern.addStitchRel(0, 0, stitchTypes.end);
pattern.invertPatternVertical();
}

View file

@ -1,15 +0,0 @@
import { dstRead } from "./dst";
import { expRead } from "./exp";
import { jefRead } from "./jef";
import { pecRead } from "./pec";
import { pesRead } from "./pes";
const supportedFormats = {
pes: { ext: ".pes", read: pesRead },
dst: { ext: ".dst", read: dstRead },
pec: { ext: ".pec", read: pecRead },
jef: { ext: ".jef", read: jefRead },
exp: { ext: ".exp", read: expRead },
};
export { supportedFormats };

View file

@ -1,133 +0,0 @@
import { Color, stitchTypes } from "../file-renderer/pattern";
const colors = [
new Color(0, 0, 0, "Black"),
new Color(0, 0, 0, "Black"),
new Color(255, 255, 255, "White"),
new Color(255, 255, 23, "Yellow"),
new Color(250, 160, 96, "Orange"),
new Color(92, 118, 73, "Olive Green"),
new Color(64, 192, 48, "Green"),
new Color(101, 194, 200, "Sky"),
new Color(172, 128, 190, "Purple"),
new Color(245, 188, 203, "Pink"),
new Color(255, 0, 0, "Red"),
new Color(192, 128, 0, "Brown"),
new Color(0, 0, 240, "Blue"),
new Color(228, 195, 93, "Gold"),
new Color(165, 42, 42, "Dark Brown"),
new Color(213, 176, 212, "Pale Violet"),
new Color(252, 242, 148, "Pale Yellow"),
new Color(240, 208, 192, "Pale Pink"),
new Color(255, 192, 0, "Peach"),
new Color(201, 164, 128, "Beige"),
new Color(155, 61, 75, "Wine Red"),
new Color(160, 184, 204, "Pale Sky"),
new Color(127, 194, 28, "Yellow Green"),
new Color(185, 185, 185, "Silver Grey"),
new Color(160, 160, 160, "Grey"),
new Color(152, 214, 189, "Pale Aqua"),
new Color(184, 240, 240, "Baby Blue"),
new Color(54, 139, 160, "Powder Blue"),
new Color(79, 131, 171, "Bright Blue"),
new Color(56, 106, 145, "Slate Blue"),
new Color(0, 32, 107, "Nave Blue"),
new Color(229, 197, 202, "Salmon Pink"),
new Color(249, 103, 107, "Coral"),
new Color(227, 49, 31, "Burnt Orange"),
new Color(226, 161, 136, "Cinnamon"),
new Color(181, 148, 116, "Umber"),
new Color(228, 207, 153, "Blonde"),
new Color(225, 203, 0, "Sunflower"),
new Color(225, 173, 212, "Orchid Pink"),
new Color(195, 0, 126, "Peony Purple"),
new Color(128, 0, 75, "Burgundy"),
new Color(160, 96, 176, "Royal Purple"),
new Color(192, 64, 32, "Cardinal Red"),
new Color(202, 224, 192, "Opal Green"),
new Color(137, 152, 86, "Moss Green"),
new Color(0, 170, 0, "Meadow Green"),
new Color(33, 138, 33, "Dark Green"),
new Color(93, 174, 148, "Aquamarine"),
new Color(76, 191, 143, "Emerald Green"),
new Color(0, 119, 114, "Peacock Green"),
new Color(112, 112, 112, "Dark Grey"),
new Color(242, 255, 255, "Ivory White"),
new Color(177, 88, 24, "Hazel"),
new Color(203, 138, 7, "Toast"),
new Color(247, 146, 123, "Salmon"),
new Color(152, 105, 45, "Cocoa Brown"),
new Color(162, 113, 72, "Sienna"),
new Color(123, 85, 74, "Sepia"),
new Color(79, 57, 70, "Dark Sepia"),
new Color(82, 58, 151, "Violet Blue"),
new Color(0, 0, 160, "Blue Ink"),
new Color(0, 150, 222, "Solar Blue"),
new Color(178, 221, 83, "Green Dust"),
new Color(250, 143, 187, "Crimson"),
new Color(222, 100, 158, "Floral Pink"),
new Color(181, 80, 102, "Wine"),
new Color(94, 87, 71, "Olive Drab"),
new Color(76, 136, 31, "Meadow"),
new Color(228, 220, 121, "Mustard"),
new Color(203, 138, 26, "Yellow Ochre"),
new Color(198, 170, 66, "Old Gold"),
new Color(236, 176, 44, "Honeydew"),
new Color(248, 128, 64, "Tangerine"),
new Color(255, 229, 5, "Canary Yellow"),
new Color(250, 122, 122, "Vermillion"),
new Color(107, 224, 0, "Bright Green"),
new Color(56, 108, 174, "Ocean Blue"),
new Color(227, 196, 180, "Beige Grey"),
new Color(227, 172, 129, "Bamboo"),
];
const jefDecode = (byte) => (byte >= 0x80 ? -(~byte & 0xff) - 1 : byte);
const isSpecialStitch = (byte) => byte === 0x80;
const isStopOrTrim = (byte) => (byte & 0x01) !== 0 || byte === 0x02 || byte === 0x04;
const isEndOfPattern = (byte) => byte === 0x10;
const isStop = (byte) => byte & 0x01;
const readStitchData = (file) => ({ byte1: file.getUint8(), byte2: file.getUint8() });
const addColorsToPattern = (file, pattern, colorCount) => {
for (let i = 0; i < colorCount; i++) {
pattern.addColor(colors[file.getUint32(file.tell(), true) % colors.length]);
}
};
const determineStitchType = (file, byte1, byte2) => {
if (isSpecialStitch(byte1)) {
if (isStopOrTrim(byte2)) {
return { type: isStop(byte2) ? stitchTypes.stop : stitchTypes.trim, byte1: file.getUint8(), byte2: file.getUint8() };
} else if (isEndOfPattern(byte2)) {
return { type: stitchTypes.end, byte1: 0, byte2: 0, end: true };
}
}
return { type: stitchTypes.normal, byte1, byte2 };
}
const processStitches = (file, pattern, stitchCount) => {
let stitchesProcessed = 0;
while (stitchesProcessed < stitchCount + 100) {
let { byte1, byte2 } = readStitchData(file);
let { type, byte1: decodedByte1, byte2: decodedByte2, end } = determineStitchType(file, byte1, byte2);
pattern.addStitchRel(jefDecode(decodedByte1), jefDecode(decodedByte2), type, true);
if (end) break;
stitchesProcessed++;
}
}
export function jefRead(file, pattern) {
file.seek(24);
const colorCount = file.getInt32(file.tell(), true);
const stitchCount = file.getInt32(file.tell(), true);
file.seek(file.tell() + 84);
addColorsToPattern(file, pattern, colorCount);
file.seek(file.tell() + (6 - colorCount) * 4);
processStitches(file, pattern, stitchCount);
pattern.invertPatternVertical();
}
export const jefColors = colors;

View file

@ -1,153 +0,0 @@
import { Color, stitchTypes } from "../file-renderer/pattern";
const namedColors = [
new Color(0, 0, 0, "Unknown"),
new Color(14, 31, 124, "Prussian Blue"),
new Color(10, 85, 163, "Blue"),
new Color(0, 135, 119, "Teal Green"),
new Color(75, 107, 175, "Cornflower Blue"),
new Color(237, 23, 31, "Red"),
new Color(209, 92, 0, "Reddish Brown"),
new Color(145, 54, 151, "Magenta"),
new Color(228, 154, 203, "Light Lilac"),
new Color(145, 95, 172, "Lilac"),
new Color(158, 214, 125, "Mint Green"),
new Color(232, 169, 0, "Deep Gold"),
new Color(254, 186, 53, "Orange"),
new Color(255, 255, 0, "Yellow"),
new Color(112, 188, 31, "Lime Green"),
new Color(186, 152, 0, "Brass"),
new Color(168, 168, 168, "Silver"),
new Color(125, 111, 0, "Russet Brown"),
new Color(255, 255, 179, "Cream Brown"),
new Color(79, 85, 86, "Pewter"),
new Color(0, 0, 0, "Black"),
new Color(11, 61, 145, "Ultramarine"),
new Color(119, 1, 118, "Royal Purple"),
new Color(41, 49, 51, "Dark Gray"),
new Color(42, 19, 1, "Dark Brown"),
new Color(246, 74, 138, "Deep Rose"),
new Color(178, 118, 36, "Light Brown"),
new Color(252, 187, 197, "Salmon Pink"),
new Color(254, 55, 15, "Vermillion"),
new Color(240, 240, 240, "White"),
new Color(106, 28, 138, "Violet"),
new Color(168, 221, 196, "Seacrest"),
new Color(37, 132, 187, "Sky Blue"),
new Color(254, 179, 67, "Pumpkin"),
new Color(255, 243, 107, "Cream Yellow"),
new Color(208, 166, 96, "Khaki"),
new Color(209, 84, 0, "Clay Brown"),
new Color(102, 186, 73, "Leaf Green"),
new Color(19, 74, 70, "Peacock Blue"),
new Color(135, 135, 135, "Gray"),
new Color(216, 204, 198, "Warm Gray"),
new Color(67, 86, 7, "Dark Olive"),
new Color(253, 217, 222, "Flesh Pink"),
new Color(249, 147, 188, "Pink"),
new Color(0, 56, 34, "Deep Green"),
new Color(178, 175, 212, "Lavender"),
new Color(104, 106, 176, "Wisteria Violet"),
new Color(239, 227, 185, "Beige"),
new Color(247, 56, 102, "Carmine"),
new Color(181, 75, 100, "Amber Red"),
new Color(19, 43, 26, "Olive Green"),
new Color(199, 1, 86, "Dark Fuschia"),
new Color(254, 158, 50, "Tangerine"),
new Color(168, 222, 235, "Light Blue"),
new Color(0, 103, 62, "Emerald Green"),
new Color(78, 41, 144, "Purple"),
new Color(47, 126, 32, "Moss Green"),
new Color(255, 204, 204, "Flesh Pink"),
new Color(255, 217, 17, "Harvest Gold"),
new Color(9, 91, 166, "Electric Blue"),
new Color(240, 249, 112, "Lemon Yellow"),
new Color(227, 243, 91, "Fresh Green"),
new Color(255, 153, 0, "Orange"),
new Color(255, 240, 141, "Cream Yellow"),
new Color(255, 200, 200, "Applique"),
];
function readPecStitches(file, pattern) {
let stitchNumber = 0;
const byteCount = file.byteLength;
while (file.tell() < byteCount) {
let [xOffset, yOffset] = [file.getUint8(), file.getUint8()];
let stitchType = stitchTypes.normal;
if (isEndStitch(xOffset, yOffset)) {
pattern.addStitchRel(0, 0, stitchTypes.end, true);
break;
}
if (isStopStitch(xOffset, yOffset)) {
file.getInt8(); // Skip extra byte
pattern.addStitchRel(0, 0, stitchTypes.stop, true);
stitchNumber++;
continue;
}
stitchType = determineStitchType(xOffset, yOffset);
[xOffset, yOffset] = decodeCoordinates(xOffset, yOffset, file);
pattern.addStitchRel(xOffset, yOffset, stitchType, true);
stitchNumber++;
}
}
function isEndStitch(xOffset, yOffset) {
return xOffset === 0xff && yOffset === 0x00;
}
function isStopStitch(xOffset, yOffset) {
return xOffset === 0xfe && yOffset === 0xb0;
}
function determineStitchType(xOffset, yOffset) {
if (xOffset & 0x80) {
if (xOffset & 0x20) return stitchTypes.trim;
if (xOffset & 0x10) return stitchTypes.jump;
}
if (yOffset & 0x80) {
if (yOffset & 0x20) return stitchTypes.trim;
if (yOffset & 0x10) return stitchTypes.jump;
}
return stitchTypes.normal;
}
function decodeCoordinates(xOffset, yOffset, file) {
if (xOffset & 0x80) {
xOffset = ((xOffset & 0x0f) << 8) + yOffset;
if (xOffset & 0x800) xOffset -= 0x1000;
yOffset = file.getUint8();
} else if (xOffset >= 0x40) {
xOffset -= 0x80;
}
if (yOffset & 0x80) {
yOffset = ((yOffset & 0x0f) << 8) + file.getUint8();
if (yOffset & 0x800) yOffset -= 0x1000;
} else if (yOffset > 0x3f) {
yOffset -= 0x80;
}
return [xOffset, yOffset];
}
export function pesRead(file, pattern) {
const pecStart = file.getInt32(8, true);
file.seek(pecStart + 48);
const numColors = file.getInt8() + 1;
for (let i = 0; i < numColors; i++) {
pattern.addColor(namedColors[file.getInt8()]);
}
file.seek(pecStart + 532);
readPecStitches(file, pattern);
pattern.addStitchRel(0, 0, stitchTypes.end);
}
export const pecReadStitches = readPecStitches;
export const pecColors = namedColors;

View file

@ -1,47 +0,0 @@
import { derived, writable } from "svelte/store";
import translations from "./translations";
const storedLocale = localStorage.getItem("locale");
const browserLocale = navigator.language || "en";
const [baseLang] = browserLocale.split("-");
export const DEFAULT_LOCALE =
storedLocale && translations[storedLocale] ? storedLocale :
translations[browserLocale] ? browserLocale :
translations[baseLang] ? baseLang :
"en";
export const locale = writable(DEFAULT_LOCALE);
locale.subscribe((value) => {
if (value) localStorage.setItem("locale", value);
});
export const locales = Object.entries(translations).map(([key, lang]) => [key, lang.name]);
function translate(locale, key, vars = {}) {
if (!key) throw new Error("Translation key is required.");
const fallbackLocale = "en";
const validLocale = translations[locale]
? locale
: translations[baseLang]
? baseLang
: fallbackLocale;
let text = translations[validLocale][key] || translations[fallbackLocale][key];
if (!text) {
console.error(`Missing translation for key "${key}" in locale "${validLocale}".`);
return key;
}
return Object.entries(vars).reduce(
(str, [varKey, value]) => str.replaceAll(`{{${varKey}}}`, value),
text
);
}
export const t = derived(locale, ($locale) => (key, vars = {}) =>
translate($locale, key, vars)
);

View file

@ -1,124 +0,0 @@
export default {
en: {
"head.title": "Free Online Embroidery File Viewer Open PES, DST, EXP & More",
"head.description": "View multiple embroidery files online for free! Open PES, DST, EXP, JEF & more without software. Upload and preview multiple files in a card list format. Try now!",
"head.keywords": "free embroidery file viewer, open PES files online, view DST files, embroidery file preview, EXP file viewer, multiple embroidery files",
"head.ogtitle": "Free Online Embroidery File Viewer Open PES, DST & More",
"head.ogdescription": "Upload and preview multiple embroidery files like PES, DST, and EXP online for free. No software needed!",
"nav.home": "🏠 Home",
"nav.viewer": "🧵 Viewer",
"nav.donate": "💖 Donate",
"nav.about": " About",
"nav.privacy.policy": "🔐 Privacy Policy",
"nav.terms.of.service": "📝 Terms of Service",
"main.title": "Upload files",
"home.main.title": "🧵 Free Online Embroidery File Viewer",
"home.main.description": "<p>✨Upload and preview your embroidery designs instantly no software needed.</p> <p><strong>Embroidery Viewer</strong> is a free, browser-based tool that supports multiple embroidery file formats. View your designs quickly and securely, right in your browser.</p>",
"home.features.title": "🚀 Features",
"home.features.list": "<ul><li>📂 <strong>Supports Multiple Formats:</strong> DST, PES, JEF, EXP, VP3, and more</li><li>⚡ <strong>Quick Previews:</strong> See your embroidery files rendered as images</li><li>🧷 <strong>Multiple Files at Once:</strong> Upload several designs and view them side-by-side</li><li>🔒 <strong>No Upload to Server:</strong> Your files stay private all processing happens locally</li><li>⬇️ <strong>Download as Image:</strong> Save each embroidery design preview as a PNG</li><li>💸 <strong>Fast & Free:</strong> No installations, no sign-ups just open and use</li></ul>",
"home.howtouse.title": "📘 How to Use",
"home.howtouse.list": "<ol><li>📁 <strong>Click</strong> the upload button <em>or</em> <strong>drag and drop</strong> your embroidery files into the drop area</li><li>🧵 Select one or more embroidery files</li><li>▶️ Click the <strong>“Render files”</strong> button to preview your designs</li><li>👀 Instantly view your designs right in your browser its that simple</li></ol>",
"home.testimonials.title": "❤️ Loved by Hobbyists and Professionals",
"home.testimonials.description": "<p>Whether you're a hobbyist working on your next DIY project or a professional digitizer reviewing client files, <strong>Embroidery Viewer</strong> gives you a no-fuss, instant way to visualize your work.</p>",
"home.donation.title": "💖 Help Keep It Free",
"home.donation.description": "<p><strong>Embroidery Viewer is completely free</strong> for everyone to use.</p><p>If you find it useful and want to support ongoing development and hosting costs, please consider making a small donation.</p>",
"home.donation.cta": "🙌 Donate Now",
"home.donation.cta.description": "every little bit helps!",
"home.cta.title": "🚀 Try It Now",
"home.cta.cta": "🧵 Open Viewer",
"home.cta.cta.description": "the fastest <strong>Free Online Embroidery File Viewer</strong>.",
"donate.title": "💖 Donate",
"donate.subtitle": "Help support Embroidery Viewer and its development!",
"donate.description": "⭐️ <strong>Embroidery Viewer</strong> is free to use. If you find this tool helpful, please consider making a donation to keep it running and fund future improvements.",
"donate.ways": "💸 Ways to Donate",
"donate.bitcoin.description": "Scan or copy the address",
"donate.copy": "Copy Address",
"donate.copied": "Copied to Clipboard!",
"donate.copy.failed": "Copy Failed!",
"donate.monero.description": "Private and secure donation option.",
"donate.paypal.description": "Want to show support in a friendly way?",
"donate.paypal.link": "Open Donation link",
"about.title": " About Embroidery Viewer",
"about.content": "<p>Hi there! 👋</p><p><strong>⭐️ Embroidery Viewer</strong> was born out of a simple need — helping someone I care about. 💖</p><p>My girlfriend loves embroidery, but she often struggled to find an easy and free way to preview her embroidery design files before stitching them. Most tools she tried were either paid, overly complex, or required technical knowledge — and shes not a techie.</p><p>So, to make things easier for her (and others like her), I decided to build this web application.</p><p>Over the course of a few weeks, I created <strong>Embroidery Viewer</strong> — a lightweight, fast, and free tool that lets you view embroidery files directly in your browser. No installation, no setup, and no tech hurdles. Just upload your file and see your design.</p><p>Its not a super sophisticated tool, but it solves the problem it was meant to solve: making embroidery file previews accessible to everyone.</p><p>If this tool has helped you too, that makes me really happy! I plan to continue improving it based on feedback from users like you.</p><p>Thanks for stopping by — and happy stitching! 🧵✨</p>",
"privacy.policy.title": "🔐 Privacy Policy",
"privacy.policy.last.update": "Last updated: May 9, 2025",
"privacy.policy.content": "<p>At <strong>Embroidery Viewer</strong> (<a href=\"https://embroideryviewer.xyz\">embroideryviewer.xyz</a>), we respect your privacy and are committed to protecting any information you share while using our service.</p><h2>1. Personal Information</h2><p>Embroidery Viewer does <strong>not</strong> collect or store any personal information. You do not need to create an account, and we do not ask for your name, email address, or any identifying details.</p><h2>2. File Uploads</h2><p>When you upload an embroidery file to the viewer, the file is processed in your browser or temporarily on our server (if required) for preview purposes only. <strong>No uploaded files are stored, saved, or shared.</strong></p><p>Please avoid uploading any copyrighted or sensitive material unless you have permission to use it.</p><h2>3. Analytics</h2><p>We use <strong>Umami</strong> to collect anonymous usage statistics about our website, such as the number of visitors, page views, device types, and referral sources. This data helps us understand how the site is being used and improve it over time.</p><p>Umami is a privacy-friendly, cookie-free analytics tool. It does <strong>not</strong> track users across sites, collect personal data, or use cookies. All data is aggregated and anonymized.</p><h2>4. Cookies</h2><p>Embroidery Viewer does <strong>not</strong> use cookies or other tracking mechanisms in your browser.</p><h2>5. Third-Party Services</h2><p>We do not use third-party advertising, embed external trackers, or share data with third parties.</p><h2>6. Changes to This Policy</h2><p>We may update this Privacy Policy from time to time. All updates will be posted on this page with the updated date.</p><h2>7. Contact</h2><p>If you have any questions about this Privacy Policy, you can reach us at <a href=\"mailto:leo@leomurca.xyz\">leo@leomurca.xyz</a>.</p>",
"terms.of.service.title": "📝 Terms of Service",
"terms.of.service.update": "May 9, 2025",
"terms.of.service.content": "<p>Welcome to <strong>Embroidery Viewer</strong> (<a href=\"https://embroideryviewer.xyz\">embroideryviewer.xyz</a>). By accessing or using this website, you agree to be bound by the following Terms of Service. If you do not agree with any part of these terms, please do not use the site.</p><h2>1. Description of Service</h2><p>Embroidery Viewer is a free, browser-based tool that allows users to preview embroidery design files online. The service is intended for personal, non-commercial use.</p><h2>2. Use of the Service</h2><p>You agree to use the service only for lawful purposes. You are solely responsible for any content (including embroidery files) you upload, and you confirm that you have the legal right to use, view, and process those files.</p><p>You agree not to upload any files that are illegal, offensive, infringe on intellectual property rights, or contain malicious code.</p><h2>3. File Processing</h2><p>Files uploaded to Embroidery Viewer are processed either directly in your browser or temporarily on our servers. Files are not stored permanently, shared, or backed up.</p><p>While we aim to keep your content secure, you acknowledge that no system is 100% secure and you use the service at your own risk.</p><h2>4. No Warranty</h2><p>This service is provided \"as is\" and \"as available\" without any warranties, express or implied. We do not guarantee that the service will be uninterrupted, secure, or error-free.</p><h2>5. Limitation of Liability</h2><p>Embroidery Viewer shall not be held liable for any damages resulting from the use or inability to use the service, including but not limited to loss of data, loss of profits, or other incidental or consequential damages.</p><h2>6. Modifications to the Service</h2><p>We reserve the right to modify, suspend, or discontinue the service at any time without notice. We may also update these Terms of Service from time to time. Continued use of the service after changes constitutes your acceptance of the new terms.</p><h2>7. Governing Law</h2><p>These Terms shall be governed by and interpreted in accordance with the laws of Brazil, without regard to its conflict of law principles.</p><h2>8. Contact</h2><p>If you have any questions about these Terms of Service, feel free to contact us at <a href=\"mailto:leo@leomurca.xyz\">leo@leomurca.xyz</a>.</p>",
"main.languageSwitch": "🇧🇷",
"main.fileSize": "Max file size is <strong>{{fileSize}}MB</strong>.",
"main.supportedFormats": "Accepted formats: <strong>{{supportedFormats}}</strong>.",
"main.render": "Render files",
"main.dropzone": "<strong>Choose files</strong><br /><span>or drag and drop them here</span>",
"main.browse": "Browse",
"main.selected": "Selected files",
"main.rejected": "Rejected files",
"main.stitches": "Stitches",
"main.dimensions": "Dimensions (x, y)",
"main.download": "Download image",
"main.copyright": "Copyright © {{year}} <a href=\"{{website}}\" target=\"_blank\" rel=\"noreferrer\">Leonardo Murça</a>. <br/> All rights reserved.",
"main.version": "🧵 Version: {{version}}"
},
pt: {
"head.title": "Visualizador de arquivos de bordado online gratuito Abra PES, DST, EXP e mais",
"head.description": "Visualize vários arquivos de bordado online gratuitamente! Abra PES, DST, EXP, JEF e mais sem software. Carregue e visualize vários arquivos em um formato de lista de cartões. Experimente agora!",
"head.keywords": "visualizador de arquivos de bordado grátis, abra arquivos PES online, visualize arquivos DST, pré-visualização de arquivos de bordado, visualizador de arquivos EXP, vários arquivos de bordado",
"head.ogtitle": "Visualizador de arquivos de bordado online gratuito Abra PES, DST e mais",
"head.ogdescription": "Carregue e visualize vários arquivos de bordado como PES, DST e EXP online gratuitamente. Não precisa de software!",
"nav.home": "🏠 Página Inicial",
"nav.viewer": "🧵 Visualizador",
"nav.donate": "💖 Doe",
"nav.about": " Sobre",
"nav.privacy.policy": "🔐 Política de Privacidade",
"nav.terms.of.service": "📝 Termos de Serviço",
"home.main.title": "🧵 Visualizador de arquivos de bordado online gratuito",
"home.main.description": "<p>✨Carregue e visualize seus desenhos de bordado instantaneamente sem necessidade de software</p> <p><strong>Embroidery Viewer</strong> é uma ferramenta gratuita para navegador que suporta diversos formatos de arquivo de bordado. Visualize seus designs de forma rápida e segura, diretamente no seu navegador.</p>",
"home.features.title": "🚀 Funcionalidades",
"home.features.list": "<ul><li>📂 <strong>Suporta vários formatos:</strong> DST, PES, JEF, EXP, VP3 e mais</li><li>⚡ <strong>Visualizações rápidas:</strong> Veja seus arquivos de bordado renderizados como imagens</li><li>🧷 <strong>Vários arquivos de uma só vez:</strong> Carregue vários designs e visualize-os lado a lado</li><li>🔒 <strong>Sem upload para o servidor:</strong> Seus arquivos permanecem privados todo o processamento acontece localmente</li><li>⬇️ <strong>Baixar como imagem:</strong> Salve cada pré-visualização do desenho do bordado como um PNG</li><li>💸 <strong>Rápido e gratuito:</strong> Sem instalações, sem cadastros basta abrir e usar</li></ul>",
"home.howtouse.title": "📘 Como usar",
"home.howtouse.list": "<ol><li>📁 <strong>Clique</strong> no botão de upload <em>ou</em> <strong>arraste e solte</strong> seus arquivos de bordado na área de soltar</li><li>🧵 Selecione um ou mais arquivos de bordado</li><li>▶️ Clique no botão <strong>“Renderizar arquivos”</strong> para visualizar seus designs</li><li>👀 Visualize seus designs instantaneamente no seu navegador é simples assim</li></ol>",
"home.testimonials.title": "❤️ Amado por Hobbyistas e Profissionais",
"home.testimonials.description": "<p>Seja você um amador trabalhando em seu próximo projeto \"faça você mesmo\" ou um digitalizador profissional revisando arquivos de clientes, o <strong>Embroidery Viewer</strong> oferece uma maneira fácil e instantânea de visualizar seu trabalho.</p>",
"home.donation.title": "💖 Ajude a mantê-lo gratuito",
"home.donation.description": "<p><strong>O Embroidery Viewer é totalmente gratuito</strong> para todos usarem.</p><p>Se você o achar útil e quiser apoiar o desenvolvimento contínuo e os custos de hospedagem, considere fazer uma pequena doação.</p>",
"home.donation.cta": "🙌 Doe agora",
"home.donation.cta.description": "cada pequena ajuda é bem-vinda!",
"home.cta.title": "🚀 Experimente agora",
"home.cta.cta": "🧵 Abrir visualizador",
"home.cta.cta.description": "o <strong>visualizador de arquivos de bordado online gratuito</strong> mais rápido.",
"donate.title": "💖 Doe",
"donate.subtitle": "Ajude a apoiar o Embroidery Viewer e seu desenvolvimento!",
"donate.description": "⭐️ O <strong>Embroidery Viewer</strong> é gratuito. Se você achar esta ferramenta útil, considere fazer uma doação para mantê-la funcionando e financiar melhorias futuras.",
"donate.ways": "💸 Formas de doar",
"donate.bitcoin.description": "Escaneie ou copie o endereço",
"donate.copy": "Copiar Endereço",
"donate.copied": "Copiado para a área de transferência!",
"donate.copy.failed": "Falha na Cópia!",
"donate.monero.description": "Opção de doação privada e segura.",
"donate.paypal.description": "Quer demonstrar apoio de uma forma amigável?",
"donate.paypal.link": "Abrir Link de Doação",
"about.title": " Sobre o Embroidery Viewer",
"about.content": "<p>Oi! 👋</p><p><strong>⭐️ Embroidery Viewer</strong> nasceu de uma necessidade simples — ajudar alguém que eu amo. 💖</p><p>Minha namorada adora bordado, mas ela sempre teve dificuldades para encontrar uma maneira fácil e gratuita de visualizar os arquivos de design de bordado antes de começar a costurar. A maioria das ferramentas que ela tentou eram pagas, muito complexas ou exigiam conhecimento técnico — e ela não é da área de tecnologia.</p><p>Então, para facilitar a vida dela (e de outras pessoas como ela), decidi criar este aplicativo web.</p><p>Ao longo de algumas semanas, criei o <strong>Embroidery Viewer</strong> — uma ferramenta leve, rápida e gratuita que permite visualizar arquivos de bordado diretamente no navegador. Sem instalação, sem configuração e sem obstáculos técnicos. Basta enviar o arquivo e ver o design.</p><p>Não é uma ferramenta super sofisticada, mas resolve o problema para o qual foi criada: tornar a visualização de arquivos de bordado acessível para todos.</p><p>Se essa ferramenta também te ajudou, isso me deixa muito feliz! Pretendo continuar melhorando com base no feedback de usuários como você.</p><p>Obrigado por visitar — e bons bordados! 🧵✨</p>",
"privacy.policy.title": "🔐 Política de Privacidade",
"privacy.policy.last.update": "Última atualização: 9 de maio de 2025",
"privacy.policy.content": "<p>No <strong>Embroidery Viewer</strong> (<a href=\"https://embroideryviewer.xyz\">embroideryviewer.xyz</a>), respeitamos sua privacidade e estamos comprometidos em proteger qualquer informação que você compartilhe ao usar nosso serviço.</p><h2>1. Informações Pessoais</h2><p>O Embroidery Viewer <strong>não</strong> coleta nem armazena informações pessoais. Você não precisa criar uma conta e não pedimos seu nome, e-mail ou qualquer dado identificável.</p><h2>2. Envio de Arquivos</h2><p>Quando você envia um arquivo de bordado para o visualizador, o arquivo é processado no seu navegador ou temporariamente em nosso servidor (se necessário) apenas para fins de visualização. <strong>Nenhum arquivo enviado é armazenado, salvo ou compartilhado.</strong></p><p>Evite enviar materiais sensíveis ou protegidos por direitos autorais, a menos que tenha permissão para usá-los.</p><h2>3. Análises</h2><p>Utilizamos o <strong>Umami</strong> para coletar estatísticas anônimas de uso do site, como número de visitantes, visualizações de página, tipos de dispositivo e fontes de acesso. Esses dados nos ajudam a entender como o site está sendo utilizado e melhorá-lo com o tempo.</p><p>O Umami é uma ferramenta de análise que respeita a privacidade, não usa cookies e não rastreia os usuários entre sites. Todos os dados são agregados e anonimizados.</p><h2>4. Cookies</h2><p>O Embroidery Viewer <strong>não</strong> utiliza cookies ou outros mecanismos de rastreamento em seu navegador.</p><h2>5. Serviços de Terceiros</h2><p>Não utilizamos publicidade de terceiros, nem incorporamos rastreadores externos, nem compartilhamos dados com terceiros.</p><h2>6. Alterações nesta Política</h2><p>Podemos atualizar esta Política de Privacidade ocasionalmente. Todas as atualizações serão publicadas nesta página com a data de modificação.</p><h2>7. Contato</h2><p>Se você tiver dúvidas sobre esta Política de Privacidade, entre em contato pelo e-mail <a href=\"mailto:leo@leomurca.xyz\">leo@leomurca.xyz</a>.</p>",
"terms.of.service.title": "📝 Termos de Serviço",
"terms.of.service.update": "Última atualização: 9 de maio de 2025",
"terms.of.service.content": "<p>Bem-vindo ao <strong>Embroidery Viewer</strong> (<a href=\"https://embroideryviewer.xyz\">embroideryviewer.xyz</a>). Ao acessar ou utilizar este site, você concorda em estar vinculado aos seguintes Termos de Serviço. Se você não concordar com qualquer parte destes termos, por favor, não utilize o site.</p><h2>1. Descrição do Serviço</h2><p>O Embroidery Viewer é uma ferramenta gratuita baseada em navegador que permite aos usuários visualizar arquivos de design de bordado online. O serviço é destinado ao uso pessoal e não comercial.</p><h2>2. Uso do Serviço</h2><p>Você concorda em usar o serviço apenas para fins legais. Você é o único responsável por qualquer conteúdo (incluindo arquivos de bordado) que enviar, e confirma que tem o direito legal de usar, visualizar e processar esses arquivos.</p><p>Você concorda em não enviar arquivos que sejam ilegais, ofensivos, infrinjam direitos de propriedade intelectual ou contenham código malicioso.</p><h2>3. Processamento de Arquivos</h2><p>Os arquivos enviados para o Embroidery Viewer são processados diretamente em seu navegador ou temporariamente em nossos servidores. Os arquivos não são armazenados permanentemente, compartilhados ou backupados.</p><p>Embora tenhamos o objetivo de manter seu conteúdo seguro, você reconhece que nenhum sistema é 100% seguro e você utiliza o serviço por sua conta e risco.</p><h2>4. Sem Garantia</h2><p>Este serviço é fornecido \"como está\" e \"como disponível\", sem quaisquer garantias, expressas ou implícitas. Não garantimos que o serviço será ininterrupto, seguro ou sem erros.</p><h2>5. Limitação de Responsabilidade</h2><p>O Embroidery Viewer não será responsabilizado por quaisquer danos resultantes do uso ou da impossibilidade de usar o serviço, incluindo, mas não se limitando a, perda de dados, perda de lucros ou outros danos incidentais ou consequenciais.</p><h2>6. Modificações no Serviço</h2><p>Reservamo-nos o direito de modificar, suspender ou descontinuar o serviço a qualquer momento, sem aviso prévio. Podemos também atualizar estes Termos de Serviço de tempos em tempos. O uso contínuo do serviço após as mudanças constitui sua aceitação dos novos termos.</p><h2>7. Lei Aplicável</h2><p>Estes Termos serão regidos e interpretados de acordo com as leis do Brasil, sem levar em consideração seus princípios de conflitos de leis.</p><h2>8. Contato</h2><p>Se você tiver qualquer dúvida sobre estes Termos de Serviço, sinta-se à vontade para entrar em contato conosco pelo e-mail <a href=\"mailto:leo@leomurca.xyz\">leo@leomurca.xyz</a>.</p>",
"main.title": "Carregar arquivos",
"main.languageSwitch": "🇺🇸",
"main.fileSize": "O tamanho máximo de cada arquivo é <strong>{{fileSize}}MB</strong>.",
"main.supportedFormats": "Formatos aceitos: <strong>{{supportedFormats}}</strong>.",
"main.render": "Renderizar arquivos",
"main.dropzone": "<strong>Selecione arquivos</strong><br /><span>ou arraste e solte-os aqui</span>",
"main.browse": "Selecionar arquivos",
"main.selected": "Arquivos selecionados",
"main.rejected": "Arquivos recusados",
"main.stitches": "Pontos",
"main.dimensions": "Dimensões (x, y)",
"main.download": "Baixar imagem",
"main.copyright": "Copyright © {{year}} <a href=\"{{website}}/pt-br\" target=\"_blank\" rel=\"noreferrer\">Leonardo Murça</a>. <br/> Todos os direitos reservados.",
"main.version": "🧵 Versão: {{version}}"
},
};

View file

Before

Width:  |  Height:  |  Size: 84 KiB

After

Width:  |  Height:  |  Size: 84 KiB

View file

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 17 KiB

View file

Before

Width:  |  Height:  |  Size: 155 KiB

After

Width:  |  Height:  |  Size: 155 KiB

View file

Before

Width:  |  Height:  |  Size: 130 KiB

After

Width:  |  Height:  |  Size: 130 KiB

View file

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

View file

@ -1,6 +1,6 @@
<script>
import { t } from "../../i18n"
import renderFileToCanvas from "../../file-renderer";
import { t } from '$lib/translations';
import renderFileToCanvas from '$lib/file-renderer';
export let files = [];
let canvasRefs = [];
@ -9,24 +9,24 @@
let sizeRefs = [];
let errorMessageRef;
let localizedStrings = {
stitches: $t("main.stitches"),
dimensions: $t("main.dimensions"),
}
stitches: $t('viewer.stitches'),
dimensions: $t('viewer.dimensions'),
};
const downloadCanvasAsImage = (canvas, filename) => {
const image = canvas
.toDataURL("image/png")
.replace("image/png", "image/octet-stream");
.toDataURL('image/png')
.replace('image/png', 'image/octet-stream');
const link = document.createElement("a");
link.download = `${filename.split(".").slice(0, -1).join(".")}.png`;
const link = document.createElement('a');
link.download = `${filename.split('.').slice(0, -1).join('.')}.png`;
link.href = image;
link.click();
};
const onKeydown = (evt) => {
if (evt.key === "Enter") {
document.getElementById("download-button").click();
if (evt.key === 'Enter') {
document.getElementById('download-button').click();
}
};
</script>
@ -43,11 +43,11 @@
<div
id="download-button"
role="button"
tabindex=0
tabindex="0"
on:keydown={onKeydown}
on:click={() => downloadCanvasAsImage(canvasRefs[i], file.name)}
>
{$t("main.download")}
{$t('viewer.download')}
</div>
</div>
{canvasRefs[i] &&
@ -58,7 +58,7 @@
colorRefs[i],
stitchesRefs[i],
sizeRefs[i],
localizedStrings
localizedStrings,
)}
{/each}
<!-- svelte-ignore a11y-missing-content -->
@ -84,7 +84,7 @@
max-height: 1000px;
margin-bottom: 15px;
padding: 10px;
/* border: 2px solid black;*/
/* border: 2px solid black;*/
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
border-radius: 16px;
}
@ -108,7 +108,7 @@
padding: 10px 0;
}
div[role="button"] {
div[role='button'] {
background-color: #05345f;
font-weight: bold;
color: white;
@ -119,7 +119,7 @@
text-align: center;
}
div[role="button"]:hover {
div[role='button']:hover {
cursor: pointer;
background-color: black;
color: white;
@ -135,7 +135,7 @@
width: 100%;
}
div[role="button"] {
div[role='button'] {
width: 100%;
padding: 15px;
}

View file

@ -1,6 +1,6 @@
<script>
import { t } from "../../i18n"
import upload from "../../assets/upload.svg"
import { t } from '$lib/translations';
import upload from '$lib/assets/upload.svg';
export let files;
export let supportedFormats;
@ -20,17 +20,17 @@
on:drop|preventDefault|stopPropagation={onDrop}
>
<img src={upload} width="40" height="40" alt="Upload icon" />
<label id="file-label" for="file-input">{@html $t("main.dropzone")}</label>
<label id="file-label" for="file-input">{@html $t('viewer.dropzone')}</label>
<input
id="file-input"
type="file"
name="files[]"
accept={supportedFormats.join(",")}
accept={supportedFormats.join(',')}
multiple
on:change={onChange}
bind:this={files}
/>
<button on:click|preventDefault={onClick}>{$t("main.browse")}</button>
<button on:click|preventDefault={onClick}>{$t('viewer.browse')}</button>
</div>
<style>
@ -58,7 +58,7 @@
button {
margin-top: 20px;
padding: 12px 24px;
background-color: #06345F;
background-color: #06345f;
color: white;
border: none;
border-radius: 10px;

View file

@ -8,18 +8,22 @@
<div id="selected-files-container">
<h2>{title}:</h2>
<div id="files-list">
{#each Array.from(files) as file}
<div id={isError ? "selected-file-card-error" : "selected-file-card"}>
<span>{file.name}</span>
<span>{Math.round(file.size / 1000)} KB</span>
</div>
{/each}
{#each Array.from(files) as file}
<div id={isError ? 'selected-file-card-error' : 'selected-file-card'}>
<span>{file.name}</span>
<span>{Math.round(file.size / 1000)} KB</span>
</div>
{/each}
</div>
</div>
{/if}
<style>
#files-list{
#selected-files-container {
text-align: center;
}
#files-list {
display: flex;
flex-direction: column;
align-items: center;
@ -28,7 +32,7 @@
#selected-file-card {
display: flex;
justify-content: space-between;
color: #06345F;
color: #06345f;
font-weight: bolder;
width: 500px;
padding-left: 15px;
@ -38,7 +42,7 @@
#selected-file-card-error {
display: flex;
justify-content: space-between;
color: #06345F;
color: #06345f;
font-weight: bolder;
width: 500px;
padding-left: 15px;

View file

@ -1,112 +0,0 @@
<script>
import CardList from "./CardList.svelte";
import Dropzone from "./Dropzone.svelte";
import FileList from "./FileList.svelte";
import { filterFiles } from "../../utils/filterFiles";
import { supportedFormats } from "../../format-readers";
import { t } from "../../i18n"
let acceptedFiles;
let rejectedFiles;
let areAcceptedFilesRendered = false;
const fileRequirements = {
supportedFormats: Object.values(supportedFormats).map((f) => f.ext),
maxSize: 1000000,
};
const onSubmit = () => {
areAcceptedFilesRendered = true;
};
const onDrop = (evt) => {
onChange(evt);
};
const onChange = (evt) => {
acceptedFiles = null;
areAcceptedFilesRendered = false;
const changedFiles = evt.dataTransfer
? evt.dataTransfer.files
: evt.target.files;
const results = filterFiles(changedFiles, fileRequirements);
acceptedFiles = results.accepted;
rejectedFiles = results.rejected;
};
const onClick = () => {
document.getElementById("file-input").click();
};
const onKeydown = (evt) => {
if (evt.key === "Enter") {
document.getElementById("file-input").click();
}
};
</script>
<form
id="form"
enctype="multipart/form-data"
on:submit|preventDefault|stopPropagation={onSubmit}
>
<div class="title-container">
<h2>{$t("main.title")}</h2>
</div>
<p>
{@html $t("main.fileSize", { fileSize: fileRequirements.maxSize / 1000000 })}
{@html $t("main.supportedFormats", { supportedFormats: fileRequirements.supportedFormats.join(", ") })}
</p>
<Dropzone
files={acceptedFiles}
supportedFormats={fileRequirements.supportedFormats}
{onKeydown}
{onClick}
{onDrop}
{onChange}
/>
<input id="submit" type="submit" value={$t("main.render")} />
<p class="disclaimer"><em>Do not upload copyrighted material you do not own or have rights to.</em></p>
</form>
{#if areAcceptedFilesRendered}
<CardList files={acceptedFiles} />
{:else}
<FileList title={$t("main.selected")} files={acceptedFiles} />
<FileList title={$t("main.rejected")} files={rejectedFiles} isError />
{/if}
<style>
form {
width: fit-content;
margin: 0 auto;
}
.title-container {
display: flex;
justify-content: space-between;
align-items: center;
}
#submit {
border: none;
border-radius: 10px;
padding: 15px
}
.disclaimer {
font-size: 13px;
text-align: center;
}
@media only screen and (max-device-width: 768px) {
#form {
width: 100%;
}
}
</style>

View file

@ -1,23 +1,32 @@
<script>
import { t } from "../../i18n";
import { appVersion } from "../../utils/env";
import { footerRoutes } from "../../utils/routes"
import { t } from '$lib/translations';
import { appVersion } from '$lib/utils/env';
</script>
<footer>
<div class="footer-content">
<div class="footer-info">
<p>{@html $t("main.copyright", {
year: new Date().getFullYear(),
website: "https://leomurca.xyz"
})}</p>
<p>{@html $t("main.version", { version: appVersion() })}</p>
<p>
{@html $t(
'footer.copyright',
/** @type {any} */ ({
year: new Date().getFullYear(),
website: 'https://leomurca.xyz',
}),
)}
</p>
<p>
{@html $t(
'footer.version',
/** @type {any} */ ({ version: appVersion() }),
)}
</p>
</div>
<nav class="footer-nav">
{#each Object.entries(footerRoutes) as [route, config]}
<a href={route} >{$t(config.nameKey)}</a>
{/each}
<a href="/about">{$t('footer.about')}</a>
<a href="/privacy-policy">{$t('footer.privacy.policy')}</a>
<a href="/terms-of-service">{$t('footer.terms.of.service')}</a>
</nav>
</div>
</footer>

View file

@ -1,29 +1,20 @@
<script>
import MediaQuery from "../MediaQuery.svelte";
import logo from "../../assets/logo.webp";
import { t, locale, locales } from "../../i18n"
import { path } from '../../utils/stores.js';
import { routes } from '../../utils/routes.js';
import { t, locale, locales, SUPPORTED_LOCALES } from '$lib/translations';
import logo from '$lib/assets/logo.webp';
import MediaQuery from './MediaQuery.svelte';
const configsFor = (matches) => {
const configsFor = (/** @type {boolean} */ matches) => {
return matches
? { src: logo, width: 150, height: 70} // mobile
? { src: logo, width: 150, height: 70 } // mobile
: { src: logo, width: 150, height: 100 }; // desktop
};
const onSwitchToOppositeLang = () => {
const oppositeLang = locales.find(item => item[0] !== $locale);
locale.set(oppositeLang[0]);
}
const onNavigateTo = (e, route) => {
e.preventDefault()
history.pushState({}, '', route);
path.set(route);
if (isMenuOpen) {
isMenuOpen = false
}
}
$locale =
$locale === SUPPORTED_LOCALES.EN_US
? SUPPORTED_LOCALES.PT_BR
: SUPPORTED_LOCALES.EN_US;
};
let isMenuOpen = false;
</script>
@ -32,39 +23,59 @@
<div class="logo">
<MediaQuery query="(max-width: 768px)" let:matches>
{@const configs = configsFor(matches)}
<a href="#" on:click={(e) => onNavigateTo(e, "/")}>
<img src={configs.src} alt="Embroidery viewer logo" width={configs.width} height={configs.height}/>
</a>
<a href="/">
<img
src={configs.src}
alt="Embroidery viewer logo"
width={configs.width}
height={configs.height}
/>
</a>
</MediaQuery>
</div>
<div class="nav-container">
<MediaQuery query="(max-width: 768px)" let:matches >
<slot let-matches>
{#if matches}
<button class="hamburger" on:click={() => (isMenuOpen = !isMenuOpen)}>
{#if isMenuOpen}x{:else}{/if}
</button>
{/if}
</slot>
</MediaQuery>
<nav class:is-open={isMenuOpen}>
<ul>
{#each Object.entries(routes).filter(r => r[1].nameKey !== undefined) as [route, config]}
<li><a href="#" on:click={(e) => onNavigateTo(e, route)} >{$t(config.nameKey)}</a></li>
{/each}
</ul>
</nav>
<div class="nav-container">
<MediaQuery query="(max-width: 768px)" let:matches>
<slot let-matches>
{#if matches}
<button class="hamburger" on:click={() => (isMenuOpen = !isMenuOpen)}>
{#if isMenuOpen}x{:else}{/if}
</button>
{/if}
</slot>
</MediaQuery>
<nav class:is-open={isMenuOpen}>
<ul>
<li>
<a href="/">{$t('header.homeNav')}</a>
</li>
<li>
<a href="/viewer">{$t('header.viewerNav')}</a>
</li>
<li>
<a href="/about">{$t('header.aboutNav')}</a>
</li>
<li>
<a href="/donate">{$t('header.donateNav')}</a>
</li>
</ul>
</nav>
<a class="common-switch {$locale === 'en' ? 'portuguese-switch' : 'english-switch' }" href="#" on:click|preventDefault={onSwitchToOppositeLang}>
<div style="display: flex; width: fit-content;">
<span style="font-size: 20px;">{$t("main.languageSwitch")}</span>
</div>
</a>
</div>
<a
class="common-switch {$locale === SUPPORTED_LOCALES.EN_US
? 'portuguese-switch'
: 'english-switch'}"
href="#"
on:click|preventDefault={onSwitchToOppositeLang}
>
<div style="display: flex; width: fit-content;">
<span style="font-size: 20px;">{$t('header.languageSwitch')}</span>
</div>
</a>
</div>
</header>
<style>
<style>
header {
display: flex;
align-items: center;
@ -123,33 +134,33 @@
}
.portuguese-switch {
color: #0C8F27;
border-bottom: 3px solid #0C8F27 !important;
fill: #0C8F27 !important;
color: #0c8f27;
border-bottom: 3px solid #0c8f27 !important;
fill: #0c8f27 !important;
}
.portuguese-switch:hover {
background: #0C8F27;
background: #0c8f27;
color: #ffffff;
fill: #ffffff !important;
}
.english-switch{
color: #BE0A2F;
border-bottom: 3px solid #BE0A2F;
.english-switch {
color: #be0a2f;
border-bottom: 3px solid #be0a2f;
width: fit-content;
fill: #BE0A2F !important;
}
fill: #be0a2f !important;
}
.english-switch:hover {
background: #BE0A2F;
background: #be0a2f;
color: #ffffff;
fill: #ffffff !important;
}
@media (max-width: 768px) {
header {
padding: 10px 20px ;
padding: 10px 20px;
}
.hamburger {
display: block;
@ -192,4 +203,4 @@
border-bottom: none;
}
}
</style>
</style>

View file

@ -1,9 +1,15 @@
<script>
import { onMount } from "svelte";
import { onMount } from 'svelte';
export let query;
/**
* @type {MediaQueryList}
*/
let mql;
/**
* @type {((this: MediaQueryList, ev: MediaQueryListEvent) => any) | null}
*/
let mqlListener;
let wasMounted = false;
let matches = false;
@ -22,6 +28,9 @@
}
}
/**
* @param {string} query
*/
function addNewListener(query) {
mql = window.matchMedia(query);
mqlListener = (v) => (matches = v.matches);

View file

@ -1,24 +0,0 @@
<script>
import { onMount } from 'svelte';
import { routes, fallback } from '../../utils/routes.js';
import { path } from '../../utils/stores.js';
const navigate = (to) => {
history.pushState({}, '', to);
path.set(to);
}
window.addEventListener('popstate', () => {
path.set(window.location.pathname);
});
let component;
const unsubscribe = path.subscribe(current => {
component = routes[current] !== undefined ? routes[current].component : fallback;
});
onMount(() => () => unsubscribe());
</script>
<svelte:component this={component} />

View file

@ -0,0 +1,61 @@
<script>
import { t } from '$lib/translations';
/** @type {string} Title of the page */
export let title;
/** @type {string} Description of the page */
export let description;
/** @type {string} SEO keywords */
export let keywords;
/** @type {string} Canonical URL of the page */
export let url;
/** @type {string} Main image URL for sharing */
export let image;
/** @type {string} Open Graph type (e.g., 'website', 'article') */
export let ogType = 'website';
/** @type {string} Open Graph title (defaults to title) */
export let ogTitle = title;
/** @type {string} Open Graph description (defaults to description) */
export let ogDescription = description;
/** @type {string} Open Graph image (defaults to image) */
export let ogImage = image;
/** @type {string} Twitter card type (e.g., 'summary_large_image') */
export let twitterCard = 'summary_large_image';
/** @type {string} Twitter title (defaults to title) */
export let twitterTitle = title;
/** @type {string} Twitter description (defaults to description) */
export let twitterDescription = description;
/** @type {string} Twitter image (defaults to image) */
export let twitterImage = image;
</script>
<svelte:head>
<title>{$t(title)}</title>
<meta name="description" content={$t(description)} />
<meta name="keywords" content={$t(keywords)} />
<!-- Open Graph -->
<meta property="og:type" content={ogType} />
<meta property="og:title" content={$t(ogTitle)} />
<meta property="og:description" content={$t(ogDescription)} />
<meta property="og:image" content={ogImage} />
<meta property="og:url" content={url} />
<!-- Twitter -->
<meta name="twitter:card" content={twitterCard} />
<meta name="twitter:title" content={twitterTitle} />
<meta name="twitter:description" content={$t(twitterDescription)} />
<meta name="twitter:image" content={twitterImage} />
</svelte:head>

View file

@ -0,0 +1,141 @@
import { supportedFormats } from '$lib/format-readers';
import { jDataView } from './jdataview';
import { Pattern } from './pattern';
/**
* Render the embroidery pattern file to the provided canvas and update views.
* @param {string} filename - The name of the file.
* @param {ProgressEvent<FileReader>} evt - The file load event.
* @param {HTMLCanvasElement} canvas - Canvas to render the pattern.
* @param {HTMLElement} colorView - Element to display colors.
* @param {HTMLElement} stitchesView - Element to display stitch count.
* @param {HTMLElement} sizeView - Element to display size.
* @param {{stitches: string, dimensions: string}} localizedStrings - Localized labels.
*/
function renderFile(
filename,
evt,
canvas,
colorView,
stitchesView,
sizeView,
localizedStrings,
) {
const fileExtension = filename.toLowerCase().split('.').pop();
const arrayBuffer = evt.target?.result;
if (!(fileExtension && arrayBuffer)) {
throw new Error('Invalid file extension or file data');
}
const view = new jDataView(arrayBuffer, 0, evt.total || 0);
const pattern = new Pattern();
const formatReader = supportedFormats[fileExtension];
if (!formatReader || typeof formatReader.read !== 'function') {
throw new Error(`Unsupported file format: ${fileExtension}`);
}
// @ts-ignore
formatReader.read(view, pattern);
pattern.moveToPositive();
pattern.drawShapeTo(canvas);
pattern.drawColorsTo(colorView);
pattern.drawStitchesCountTo(stitchesView, localizedStrings.stitches);
pattern.drawSizeValuesTo(sizeView, localizedStrings.dimensions);
}
/**
* Display a generic abort message.
* @param {HTMLElement} errorMessageRef - Element to display the message.
*/
function renderAbortMessage(errorMessageRef) {
errorMessageRef.textContent = 'Render aborted!';
}
/**
* Display a detailed error message based on error type.
* @param {string} errorName - The name of the error.
* @param {HTMLElement} errorMessageRef - Element to display the message.
*/
function renderErrorMessage(errorName, errorMessageRef) {
/** @type {string} */
let message;
switch (errorName) {
case 'NotFoundError':
message =
'The file could not be found at the time the read was processed.';
break;
case 'SecurityError':
message =
'<p>A file security error occurred. This can be due to:</p>' +
'<ul>' +
'<li>Accessing certain files deemed unsafe for Web applications.</li>' +
'<li>Performing too many read calls on file resources.</li>' +
'<li>The file has changed on disk since the user selected it.</li>' +
'</ul>';
break;
case 'NotReadableError':
message =
'The file cannot be read. This can occur if the file is open in another application.';
break;
case 'EncodingError':
message = 'The length of the data URL for the file is too long.';
break;
default:
message = 'Something went wrong!';
break;
}
errorMessageRef.innerHTML = message;
}
/**
* Read a file and render its pattern to canvas with error handling.
* @param {File} fileObject - The file to read.
* @param {HTMLCanvasElement} canvas - The canvas to render on.
* @param {HTMLElement} errorMessageRef - Element to show error messages.
* @param {HTMLElement} colorView - Element to display colors.
* @param {HTMLElement} stitchesView - Element to display stitch count.
* @param {HTMLElement} sizeView - Element to display size.
* @param {{stitches: string, dimensions: string}} localizedStrings - Localized strings.
* @returns {string} Empty string after starting file read.
*/
export default function renderFileToCanvas(
fileObject,
canvas,
errorMessageRef,
colorView,
stitchesView,
sizeView,
localizedStrings,
) {
const reader = new FileReader();
reader.onloadend = (evt) =>
renderFile(
fileObject.name,
evt,
canvas,
colorView,
stitchesView,
sizeView,
localizedStrings,
);
reader.onabort = () => renderAbortMessage(errorMessageRef);
reader.onerror = (evt) =>
renderErrorMessage(
// @ts-ignore
evt.target.error?.name || 'UnknownError',
errorMessageRef,
);
if (fileObject) {
reader.readAsArrayBuffer(fileObject);
}
return '';
}

View file

@ -1,5 +1,7 @@
/* eslint-disable no-unused-vars */
/* eslint-disable no-undef */
// @ts-nocheck
//
import { browser } from '$app/environment';
// jDataView by Vjeux <vjeuxx@gmail.com> - Jan 2010
// Continued by RReverser <me@rreverser.com> - Feb 2013
//
@ -9,22 +11,22 @@
var compatibility = {
// NodeJS Buffer in v0.5.5 and newer
NodeBuffer: "Buffer" in globalThis && "readInt16LE" in Buffer.prototype,
NodeBuffer: 'Buffer' in globalThis && 'readInt16LE' in Buffer.prototype,
DataView:
"DataView" in globalThis &&
("getFloat64" in DataView.prototype || // Chrome
"getFloat64" in new DataView(new ArrayBuffer(1))), // Node
ArrayBuffer: "ArrayBuffer" in globalThis,
'DataView' in globalThis &&
('getFloat64' in DataView.prototype || // Chrome
'getFloat64' in new DataView(new ArrayBuffer(1))), // Node
ArrayBuffer: 'ArrayBuffer' in globalThis,
PixelData:
"CanvasPixelArray" in globalThis &&
"ImageData" in globalThis &&
"document" in globalThis,
'CanvasPixelArray' in globalThis &&
'ImageData' in globalThis &&
'document' in globalThis,
};
var createPixelData = function (byteLength, buffer) {
var data = createPixelData.context2d.createImageData(
(byteLength + 3) / 4,
1
1,
).data;
data.byteLength = byteLength;
if (buffer !== undefined) {
@ -34,7 +36,8 @@ var createPixelData = function (byteLength, buffer) {
}
return data;
};
createPixelData.context2d = document.createElement("canvas").getContext("2d");
createPixelData.context2d =
browser ?? document.createElement('canvas').getContext('2d');
var dataTypes = {
Int8: 1,
@ -48,14 +51,14 @@ var dataTypes = {
};
var nodeNaming = {
Int8: "Int8",
Int16: "Int16",
Int32: "Int32",
Uint8: "UInt8",
Uint16: "UInt16",
Uint32: "UInt32",
Float32: "Float",
Float64: "Double",
Int8: 'Int8',
Int16: 'Int16',
Int32: 'Int32',
Uint8: 'UInt8',
Uint16: 'UInt16',
Uint32: 'UInt32',
Float32: 'Float',
Float64: 'Double',
};
function arrayFrom(arrayLike, forceCopy) {
@ -98,13 +101,13 @@ export function jDataView(buffer, byteOffset, byteLength, littleEndian) {
!this._isPixelData &&
!(buffer instanceof Array)
) {
throw new TypeError("jDataView buffer has an incompatible type");
throw new TypeError('jDataView buffer has an incompatible type');
}
// Default Values
this._littleEndian = !!littleEndian;
var bufferLength = "byteLength" in buffer ? buffer.byteLength : buffer.length;
var bufferLength = 'byteLength' in buffer ? buffer.byteLength : buffer.length;
this.byteOffset = byteOffset = defined(byteOffset, 0);
this.byteLength = byteLength = defined(byteLength, bufferLength - byteOffset);
@ -119,15 +122,15 @@ export function jDataView(buffer, byteOffset, byteLength, littleEndian) {
this._engineAction = this._isDataView
? this._dataViewAction
: this._isNodeBuffer
? this._nodeBufferAction
: this._isArrayBuffer
? this._arrayBufferAction
: this._arrayAction;
? this._nodeBufferAction
: this._isArrayBuffer
? this._arrayBufferAction
: this._arrayAction;
}
function getCharCodes(string) {
if (compatibility.NodeBuffer) {
return new Buffer(string, "binary");
return new Buffer(string, 'binary');
}
var Type = compatibility.ArrayBuffer ? Uint8Array : Array,
@ -142,7 +145,7 @@ function getCharCodes(string) {
// mostly internal function for wrapping any supported input (String or Array-like) to best suitable buffer format
jDataView.wrapBuffer = function (buffer) {
switch (typeof buffer) {
case "number":
case 'number':
if (compatibility.NodeBuffer) {
buffer = new Buffer(buffer);
buffer.fill(0);
@ -158,12 +161,12 @@ jDataView.wrapBuffer = function (buffer) {
}
return buffer;
case "string":
case 'string':
buffer = getCharCodes(buffer);
/* falls through */
default:
if (
"length" in buffer &&
'length' in buffer &&
!(
(compatibility.NodeBuffer && buffer instanceof Buffer) ||
(compatibility.ArrayBuffer && buffer instanceof ArrayBuffer) ||
@ -230,7 +233,7 @@ function Int64(lo, hi) {
jDataView.Int64 = Int64;
Int64.prototype =
"create" in Object ? Object.create(Uint64.prototype) : new Uint64();
'create' in Object ? Object.create(Uint64.prototype) : new Uint64();
Int64.prototype.valueOf = function () {
if (this.hi < pow2(31)) {
@ -261,20 +264,20 @@ jDataView.prototype = {
_checkBounds: function (byteOffset, byteLength, maxLength) {
// Do additional checks to simulate DataView
if (typeof byteOffset !== "number") {
throw new TypeError("Offset is not a number.");
if (typeof byteOffset !== 'number') {
throw new TypeError('Offset is not a number.');
}
if (typeof byteLength !== "number") {
throw new TypeError("Size is not a number.");
if (typeof byteLength !== 'number') {
throw new TypeError('Size is not a number.');
}
if (byteLength < 0) {
throw new RangeError("Length is negative.");
throw new RangeError('Length is negative.');
}
if (
byteOffset < 0 ||
byteOffset + byteLength > defined(maxLength, this.byteLength)
) {
throw new RangeError("Offsets are out of bounds.");
throw new RangeError('Offsets are out of bounds.');
}
},
@ -284,7 +287,7 @@ jDataView.prototype = {
isReadAction,
defined(byteOffset, this._offset),
defined(littleEndian, this._littleEndian),
value
value,
);
},
@ -293,13 +296,13 @@ jDataView.prototype = {
isReadAction,
byteOffset,
littleEndian,
value
value,
) {
// Move the internal offset forward
this._offset = byteOffset + dataTypes[type];
return isReadAction
? this._view["get" + type](byteOffset, littleEndian)
: this._view["set" + type](byteOffset, value, littleEndian);
? this._view['get' + type](byteOffset, littleEndian)
: this._view['set' + type](byteOffset, value, littleEndian);
},
_nodeBufferAction: function (
@ -307,17 +310,17 @@ jDataView.prototype = {
isReadAction,
byteOffset,
littleEndian,
value
value,
) {
// Move the internal offset forward
this._offset = byteOffset + dataTypes[type];
var nodeName =
nodeNaming[type] +
(type === "Int8" || type === "Uint8" ? "" : littleEndian ? "LE" : "BE");
(type === 'Int8' || type === 'Uint8' ? '' : littleEndian ? 'LE' : 'BE');
byteOffset += this.byteOffset;
return isReadAction
? this.buffer["read" + nodeName](byteOffset)
: this.buffer["write" + nodeName](value, byteOffset);
? this.buffer['read' + nodeName](byteOffset)
: this.buffer['write' + nodeName](value, byteOffset);
},
_arrayBufferAction: function (
@ -325,10 +328,10 @@ jDataView.prototype = {
isReadAction,
byteOffset,
littleEndian,
value
value,
) {
var size = dataTypes[type],
TypedArray = globalThis[type + "Array"],
TypedArray = globalThis[type + 'Array'],
typedArray;
littleEndian = defined(littleEndian, this._littleEndian);
@ -345,7 +348,7 @@ jDataView.prototype = {
var bytes = new Uint8Array(
isReadAction
? this.getBytes(size, byteOffset, littleEndian, true)
: size
: size,
);
typedArray = new TypedArray(bytes.buffer, 0, 1);
@ -360,8 +363,8 @@ jDataView.prototype = {
_arrayAction: function (type, isReadAction, byteOffset, littleEndian, value) {
return isReadAction
? this["_get" + type](byteOffset, littleEndian)
: this["_set" + type](byteOffset, value, littleEndian);
? this['_get' + type](byteOffset, littleEndian)
: this['_set' + type](byteOffset, value, littleEndian);
},
// Helpers
@ -382,7 +385,7 @@ jDataView.prototype = {
: (this.buffer.slice || Array.prototype.slice).call(
this.buffer,
byteOffset,
byteOffset + length
byteOffset + length,
);
return littleEndian || length <= 1 ? result : arrayFrom(result).reverse();
@ -393,7 +396,7 @@ jDataView.prototype = {
var result = this._getBytes(
length,
byteOffset,
defined(littleEndian, true)
defined(littleEndian, true),
);
return toArray ? arrayFrom(result) : result;
},
@ -445,18 +448,18 @@ jDataView.prototype = {
this._offset = byteOffset + byteLength;
return this.buffer.toString(
encoding || "binary",
encoding || 'binary',
this.byteOffset + byteOffset,
this.byteOffset + this._offset
this.byteOffset + this._offset,
);
}
var bytes = this._getBytes(byteLength, byteOffset, true),
string = "";
string = '';
byteLength = bytes.length;
for (var i = 0; i < byteLength; i++) {
string += String.fromCharCode(bytes[i]);
}
if (encoding === "utf8") {
if (encoding === 'utf8') {
string = decodeURIComponent(escape(string));
}
return string;
@ -471,11 +474,11 @@ jDataView.prototype = {
this.buffer.write(
subString,
this.byteOffset + byteOffset,
encoding || "binary"
encoding || 'binary',
);
return;
}
if (encoding === "utf8") {
if (encoding === 'utf8') {
subString = unescape(encodeURIComponent(subString));
}
this._setBytes(byteOffset, getCharCodes(subString), true);
@ -516,13 +519,13 @@ jDataView.prototype = {
this.getBytes(end - start, start, true, true),
undefined,
undefined,
this._littleEndian
this._littleEndian,
)
: new jDataView(
this.buffer,
this.byteOffset + start,
end - start,
this._littleEndian
this._littleEndian,
);
},
@ -679,7 +682,7 @@ jDataView.prototype = {
value,
mantSize,
expSize,
littleEndian
littleEndian,
) {
var signBit = value < 0 ? 1 : 0,
exponent,
@ -751,7 +754,7 @@ jDataView.prototype = {
this.setUint32(
byteOffset + parts[partName],
value[partName],
littleEndian
littleEndian,
);
}
@ -770,7 +773,7 @@ jDataView.prototype = {
this._setBytes(
byteOffset,
[value & 0xff, (value >>> 8) & 0xff, (value >>> 16) & 0xff, value >>> 24],
littleEndian
littleEndian,
);
},
@ -778,7 +781,7 @@ jDataView.prototype = {
this._setBytes(
byteOffset,
[value & 0xff, (value >>> 8) & 0xff],
littleEndian
littleEndian,
);
},
@ -808,10 +811,10 @@ var proto = jDataView.prototype;
for (var type in dataTypes) {
(function (type) {
proto["get" + type] = function (byteOffset, littleEndian) {
proto['get' + type] = function (byteOffset, littleEndian) {
return this._action(type, true, byteOffset, littleEndian);
};
proto["set" + type] = function (byteOffset, value, littleEndian) {
proto['set' + type] = function (byteOffset, value, littleEndian) {
this._action(type, false, byteOffset, littleEndian, value);
};
})(type);
@ -823,19 +826,19 @@ proto._setInt8 = proto._setUint8;
proto.setSigned = proto.setUnsigned;
for (var method in proto) {
if (method.slice(0, 3) === "set") {
if (method.slice(0, 3) === 'set') {
(function (type) {
proto["write" + type] = function () {
proto['write' + type] = function () {
Array.prototype.unshift.call(arguments, undefined);
this["set" + type].apply(this, arguments);
this['set' + type].apply(this, arguments);
};
})(method.slice(3));
}
}
if (typeof module !== "undefined" && typeof module.exports === "object") {
if (typeof module !== 'undefined' && typeof module.exports === 'object') {
module.exports = jDataView;
} else if (typeof define === "function" && define.amd) {
} else if (typeof define === 'function' && define.amd) {
define([], function () {
return jDataView;
});

View file

@ -0,0 +1,331 @@
import { rgbToHex } from '$lib/utils/rgbToHex';
import { shadeColor } from '$lib/utils/shadeColor';
/**
* Represents a single stitch in the pattern.
* @param {number} x - The absolute x position of the stitch.
* @param {number} y - The absolute y position of the stitch.
* @param {number} flags - Stitch flags (e.g. jump, trim).
* @param {number} color - Index of the stitch color.
* @constructor
*/
function Stitch(x, y, flags, color) {
this.x = x;
this.y = y;
this.flags = flags;
this.color = color;
}
/**
* Represents a color with RGB components and an optional description.
* @param {number} r - Red component (0-255).
* @param {number} g - Green component (0-255).
* @param {number} b - Blue component (0-255).
* @param {string} description - Color description.
* @constructor
*/
function Color(r, g, b, description) {
this.r = r;
this.g = g;
this.b = b;
this.description = description;
}
/**
* Stitch type bit flags.
* @readonly
* @enum {number}
*/
const stitchTypes = {
normal: 0,
jump: 1,
trim: 2,
stop: 4,
end: 8,
};
/**
* Represents an embroidery pattern containing stitches and colors.
* @constructor
*/
function Pattern() {
/** @type {Color[]} */
this.colors = [];
/** @type {Stitch[]} */
this.stitches = [];
/** Hoop info (not typed, depends on implementation) */
this.hoop = {};
/** Last stitch position for relative moves */
this.lastX = 0;
this.lastY = 0;
/** Bounding box */
this.top = 0;
this.bottom = 0;
this.left = 0;
this.right = 0;
/** Current color index used for new stitches */
this.currentColorIndex = 0;
}
/**
* Adds a color by RGB values.
* @param {number} r
* @param {number} g
* @param {number} b
* @param {string} description
*/
Pattern.prototype.addColorRgb = function (r, g, b, description) {
this.colors.push(new Color(r, g, b, description));
};
/**
* Adds an existing Color instance.
* @param {Color} color
*/
Pattern.prototype.addColor = function (color) {
this.colors.push(color);
};
/**
* Adds a stitch at absolute coordinates.
* @param {number} x - Absolute X coordinate.
* @param {number} y - Absolute Y coordinate.
* @param {number} flags - Stitch flags.
* @param {boolean} isAutoColorIndex - Whether to automatically increment color on stop.
*/
Pattern.prototype.addStitchAbs = function (x, y, flags, isAutoColorIndex) {
if ((flags & stitchTypes.end) === stitchTypes.end) {
this.calculateBoundingBox();
this.fixColorCount();
}
if (
(flags & stitchTypes.stop) === stitchTypes.stop &&
this.stitches.length === 0
) {
return;
}
if ((flags & stitchTypes.stop) === stitchTypes.stop && isAutoColorIndex) {
this.currentColorIndex += 1;
}
this.stitches.push(new Stitch(x, y, flags, this.currentColorIndex));
};
/**
* Adds a stitch relative to the last stitch.
* @param {number} dx - Delta X from last stitch.
* @param {number} dy - Delta Y from last stitch.
* @param {number} flags - Stitch flags.
* @param {boolean} [isAutoColorIndex=false] - Whether to automatically increment color on stop. Optional.
*/
Pattern.prototype.addStitchRel = function (dx, dy, flags, isAutoColorIndex) {
if (typeof isAutoColorIndex === 'undefined') {
isAutoColorIndex = false;
}
if (this.stitches.length !== 0) {
const nx = this.lastX + dx;
const ny = this.lastY + dy;
this.lastX = nx;
this.lastY = ny;
this.addStitchAbs(nx, ny, flags, isAutoColorIndex);
} else {
this.addStitchAbs(dx, dy, flags, isAutoColorIndex);
}
};
/**
* Calculates the bounding box of all stitches, excluding trims.
*/
Pattern.prototype.calculateBoundingBox = function () {
const stitchCount = this.stitches.length;
if (stitchCount === 0) {
this.bottom = 1;
this.right = 1;
return;
}
this.left = Infinity;
this.top = Infinity;
this.right = -Infinity;
this.bottom = -Infinity;
for (let i = 0; i < stitchCount; i++) {
const pt = this.stitches[i];
if (!(pt.flags & stitchTypes.trim)) {
if (pt.x < this.left) this.left = pt.x;
if (pt.y < this.top) this.top = pt.y;
if (pt.x > this.right) this.right = pt.x;
if (pt.y > this.bottom) this.bottom = pt.y;
}
}
};
/**
* Moves all stitches so the pattern is positioned at positive coordinates.
*/
Pattern.prototype.moveToPositive = function () {
const stitchCount = this.stitches.length;
for (let i = 0; i < stitchCount; i++) {
this.stitches[i].x -= this.left;
this.stitches[i].y -= this.top;
}
this.right -= this.left;
this.left = 0;
this.bottom -= this.top;
this.top = 0;
};
/**
* Flips the pattern vertically.
*/
Pattern.prototype.invertPatternVertical = function () {
const stitchCount = this.stitches.length;
const tempTop = -this.top;
for (let i = 0; i < stitchCount; i++) {
this.stitches[i].y = -this.stitches[i].y;
}
this.top = -this.bottom;
this.bottom = tempTop;
};
/**
* Adds a random color to the pattern.
*/
Pattern.prototype.addColorRandom = function () {
this.colors.push(
new Color(
Math.round(Math.random() * 256),
Math.round(Math.random() * 256),
Math.round(Math.random() * 256),
'random',
),
);
};
/**
* Fixes the color count so colors match used indices in stitches.
*/
Pattern.prototype.fixColorCount = function () {
let maxColorIndex = 0;
const stitchCount = this.stitches.length;
for (let i = 0; i < stitchCount; i++) {
if (this.stitches[i].color > maxColorIndex) {
maxColorIndex = this.stitches[i].color;
}
}
while (this.colors.length <= maxColorIndex) {
this.addColorRandom();
}
// Remove extra colors beyond max used index
this.colors.splice(maxColorIndex + 1);
};
/**
* Draws the stitch pattern to a canvas element.
* @param {HTMLCanvasElement} canvas
*/
Pattern.prototype.drawShapeTo = function (canvas) {
canvas.width = this.right;
canvas.height = this.bottom;
let gradient, tx, ty;
let lastStitch = this.stitches[0];
let gWidth = 100;
if (canvas.getContext) {
const ctx = canvas.getContext('2d');
if (!ctx) {
// If context is null, just return or handle accordingly
return;
}
ctx.lineWidth = 3;
ctx.lineJoin = 'round';
let color = this.colors[this.stitches[0].color];
for (let i = 0; i < this.stitches.length; i++) {
const currentStitch = this.stitches[i];
if (i > 0) lastStitch = this.stitches[i - 1];
tx = currentStitch.x - lastStitch.x;
ty = currentStitch.y - lastStitch.y;
gWidth = Math.sqrt(tx * tx + ty * ty);
gradient = ctx.createRadialGradient(
currentStitch.x - tx,
currentStitch.y - ty,
0,
currentStitch.x - tx,
currentStitch.y - ty,
gWidth * 1.4,
);
gradient.addColorStop(0, shadeColor(rgbToHex(color), -60));
gradient.addColorStop(0.05, rgbToHex(color));
gradient.addColorStop(0.5, shadeColor(rgbToHex(color), 60));
gradient.addColorStop(0.9, rgbToHex(color));
gradient.addColorStop(1.0, shadeColor(rgbToHex(color), -60));
ctx.strokeStyle = gradient;
if (
currentStitch.flags === stitchTypes.jump ||
currentStitch.flags === stitchTypes.trim ||
currentStitch.flags === stitchTypes.stop
) {
color = this.colors[currentStitch.color];
ctx.beginPath();
ctx.strokeStyle =
'rgba(' + color.r + ',' + color.g + ',' + color.b + ',0)';
ctx.moveTo(currentStitch.x, currentStitch.y);
ctx.stroke();
}
ctx.beginPath();
ctx.moveTo(lastStitch.x, lastStitch.y);
ctx.lineTo(currentStitch.x, currentStitch.y);
ctx.stroke();
lastStitch = currentStitch;
}
}
};
/**
* Draws color swatches into a container element.
* @param {HTMLElement} colorContainer
*/
Pattern.prototype.drawColorsTo = function (colorContainer) {
this.colors.forEach((color) => {
colorContainer.innerHTML += `<div style='background-color: rgb(${color.r}, ${color.g}, ${color.b}); height: 25px; width: 25px; border: 1px solid #000000; border-radius: 16px;'></div>`;
});
};
/**
* Displays the stitch count in a container element.
* @param {HTMLElement} stitchesContainer
* @param {string} stitchesString - Label for stitches count.
*/
Pattern.prototype.drawStitchesCountTo = function (
stitchesContainer,
stitchesString,
) {
stitchesContainer.innerHTML += `<div><strong>${stitchesString}:</strong> ${this.stitches.length}</div>`;
};
/**
* Displays pattern dimensions in a container element.
* @param {HTMLElement} sizeContainer
* @param {string} dimensionsString - Label for dimensions.
*/
Pattern.prototype.drawSizeValuesTo = function (
sizeContainer,
dimensionsString,
) {
sizeContainer.innerHTML += `<div><strong>${dimensionsString}:</strong> ${Math.round(this.right / 10)}mm x ${Math.round(this.bottom / 10)}mm</div>`;
};
export { Pattern, Color, stitchTypes };

View file

@ -0,0 +1,89 @@
import { stitchTypes } from '$lib/file-renderer/pattern';
/**
* Decodes stitch flags from the 3rd byte of a DST stitch command.
*
* @param {number} b2 The third byte of the stitch command.
* @returns {number} Bitmask representing stitch types.
*/
function decodeExp(b2) {
if (b2 === 0xf3) {
return stitchTypes.end;
}
if ((b2 & 0xc3) === 0xc3) {
return stitchTypes.trim | stitchTypes.stop;
}
let returnCode = 0;
if (b2 & 0x80) {
returnCode |= stitchTypes.trim;
}
if (b2 & 0x40) {
returnCode |= stitchTypes.stop;
}
return returnCode;
}
/**
* Reads a DST embroidery file and populates the pattern object.
*
*
* @param {EmbroideryFileView} file
* @param {EmbroideryPattern} pattern
*/
export function dstRead(file, pattern) {
let prevJump = false;
const byteCount = file.byteLength;
file.seek(512); // Skip DST header
while (file.tell() < byteCount - 3) {
/** @type {number[]} */
const b = [file.getUint8(), file.getUint8(), file.getUint8()];
let x = 0;
let y = 0;
// Decode X movements
if (b[0] & 0x01) x += 1;
if (b[0] & 0x02) x -= 1;
if (b[0] & 0x04) x += 9;
if (b[0] & 0x08) x -= 9;
if (b[1] & 0x01) x += 3;
if (b[1] & 0x02) x -= 3;
if (b[1] & 0x04) x += 27;
if (b[1] & 0x08) x -= 27;
if (b[2] & 0x04) x += 81;
if (b[2] & 0x08) x -= 81;
// Decode Y movements
if (b[0] & 0x80) y += 1;
if (b[0] & 0x40) y -= 1;
if (b[0] & 0x20) y += 9;
if (b[0] & 0x10) y -= 9;
if (b[1] & 0x80) y += 3;
if (b[1] & 0x40) y -= 3;
if (b[1] & 0x20) y += 27;
if (b[1] & 0x10) y -= 27;
if (b[2] & 0x20) y += 81;
if (b[2] & 0x10) y -= 81;
let flags = decodeExp(b[2]);
const thisJump = (flags & stitchTypes.jump) !== 0;
if (prevJump) {
flags |= stitchTypes.jump;
}
pattern.addStitchRel(x, y, flags, true);
prevJump = thisJump;
}
pattern.addStitchRel(0, 0, stitchTypes.end, true);
pattern.invertPatternVertical();
}

View file

@ -0,0 +1,56 @@
import { stitchTypes } from '$lib/file-renderer/pattern';
/**
* Decodes a single byte with EXP format rules.
* Values above 128 are negative numbers encoded with bitwise operations.
*
* @param {number} input - A signed 8-bit integer (-128 to 127).
* @returns {number} - Decoded signed integer.
*/
function expDecode(input) {
return input > 128 ? -(~input & 0xff) - 1 : input;
}
/**
* Reads an EXP format file and adds stitches to the given pattern.
*
* @param {EmbroideryFileView} file - A DataView representing the binary EXP file content.
* @param {EmbroideryPattern} pattern - The pattern object with addStitchRel and invertPatternVertical methods.
* @returns {void}
*/
export function expRead(file, pattern) {
let index = 0;
const byteCount = file.byteLength;
while (index < byteCount) {
let flags = stitchTypes.normal;
let b0 = file.getInt8(index++);
let b1 = file.getInt8(index++);
if (b0 === -128) {
if (b1 & 1) {
b0 = file.getInt8(index++);
b1 = file.getInt8(index++);
flags = stitchTypes.stop;
} else if (b1 === 2 || b1 === 4) {
b0 = file.getInt8(index++);
b1 = file.getInt8(index++);
flags = stitchTypes.trim;
} else if (b1 === -128) {
b0 = file.getInt8(index++);
b1 = file.getInt8(index++);
b0 = 0;
b1 = 0;
flags = stitchTypes.trim;
}
}
const dx = expDecode(b0);
const dy = expDecode(b1);
pattern.addStitchRel(dx, dy, flags, true);
}
pattern.addStitchRel(0, 0, stitchTypes.end);
pattern.invertPatternVertical();
}

View file

@ -0,0 +1,19 @@
import { dstRead } from './dst';
import { expRead } from './exp';
import { jefRead } from './jef';
import { pecRead } from './pec';
import { pesRead } from './pes';
/**
* Supported embroidery file formats.
* @type {SupportedFormats}
*/
const supportedFormats = {
pes: { ext: '.pes', read: pesRead },
dst: { ext: '.dst', read: dstRead },
pec: { ext: '.pec', read: pecRead },
jef: { ext: '.jef', read: jefRead },
exp: { ext: '.exp', read: expRead },
};
export { supportedFormats };

View file

@ -0,0 +1,212 @@
import { Color, stitchTypes } from '$lib/file-renderer/pattern';
/** @type {Color[]} */
const colors = [
new Color(0, 0, 0, 'Black'),
new Color(0, 0, 0, 'Black'),
new Color(255, 255, 255, 'White'),
new Color(255, 255, 23, 'Yellow'),
new Color(250, 160, 96, 'Orange'),
new Color(92, 118, 73, 'Olive Green'),
new Color(64, 192, 48, 'Green'),
new Color(101, 194, 200, 'Sky'),
new Color(172, 128, 190, 'Purple'),
new Color(245, 188, 203, 'Pink'),
new Color(255, 0, 0, 'Red'),
new Color(192, 128, 0, 'Brown'),
new Color(0, 0, 240, 'Blue'),
new Color(228, 195, 93, 'Gold'),
new Color(165, 42, 42, 'Dark Brown'),
new Color(213, 176, 212, 'Pale Violet'),
new Color(252, 242, 148, 'Pale Yellow'),
new Color(240, 208, 192, 'Pale Pink'),
new Color(255, 192, 0, 'Peach'),
new Color(201, 164, 128, 'Beige'),
new Color(155, 61, 75, 'Wine Red'),
new Color(160, 184, 204, 'Pale Sky'),
new Color(127, 194, 28, 'Yellow Green'),
new Color(185, 185, 185, 'Silver Grey'),
new Color(160, 160, 160, 'Grey'),
new Color(152, 214, 189, 'Pale Aqua'),
new Color(184, 240, 240, 'Baby Blue'),
new Color(54, 139, 160, 'Powder Blue'),
new Color(79, 131, 171, 'Bright Blue'),
new Color(56, 106, 145, 'Slate Blue'),
new Color(0, 32, 107, 'Nave Blue'),
new Color(229, 197, 202, 'Salmon Pink'),
new Color(249, 103, 107, 'Coral'),
new Color(227, 49, 31, 'Burnt Orange'),
new Color(226, 161, 136, 'Cinnamon'),
new Color(181, 148, 116, 'Umber'),
new Color(228, 207, 153, 'Blonde'),
new Color(225, 203, 0, 'Sunflower'),
new Color(225, 173, 212, 'Orchid Pink'),
new Color(195, 0, 126, 'Peony Purple'),
new Color(128, 0, 75, 'Burgundy'),
new Color(160, 96, 176, 'Royal Purple'),
new Color(192, 64, 32, 'Cardinal Red'),
new Color(202, 224, 192, 'Opal Green'),
new Color(137, 152, 86, 'Moss Green'),
new Color(0, 170, 0, 'Meadow Green'),
new Color(33, 138, 33, 'Dark Green'),
new Color(93, 174, 148, 'Aquamarine'),
new Color(76, 191, 143, 'Emerald Green'),
new Color(0, 119, 114, 'Peacock Green'),
new Color(112, 112, 112, 'Dark Grey'),
new Color(242, 255, 255, 'Ivory White'),
new Color(177, 88, 24, 'Hazel'),
new Color(203, 138, 7, 'Toast'),
new Color(247, 146, 123, 'Salmon'),
new Color(152, 105, 45, 'Cocoa Brown'),
new Color(162, 113, 72, 'Sienna'),
new Color(123, 85, 74, 'Sepia'),
new Color(79, 57, 70, 'Dark Sepia'),
new Color(82, 58, 151, 'Violet Blue'),
new Color(0, 0, 160, 'Blue Ink'),
new Color(0, 150, 222, 'Solar Blue'),
new Color(178, 221, 83, 'Green Dust'),
new Color(250, 143, 187, 'Crimson'),
new Color(222, 100, 158, 'Floral Pink'),
new Color(181, 80, 102, 'Wine'),
new Color(94, 87, 71, 'Olive Drab'),
new Color(76, 136, 31, 'Meadow'),
new Color(228, 220, 121, 'Mustard'),
new Color(203, 138, 26, 'Yellow Ochre'),
new Color(198, 170, 66, 'Old Gold'),
new Color(236, 176, 44, 'Honeydew'),
new Color(248, 128, 64, 'Tangerine'),
new Color(255, 229, 5, 'Canary Yellow'),
new Color(250, 122, 122, 'Vermillion'),
new Color(107, 224, 0, 'Bright Green'),
new Color(56, 108, 174, 'Ocean Blue'),
new Color(227, 196, 180, 'Beige Grey'),
new Color(227, 172, 129, 'Bamboo'),
];
/**
* Decode a single byte for JEF stitch data (signed int8-like with special encoding).
* @param {number} byte
* @returns {number}
*/
const jefDecode = (byte) => (byte >= 0x80 ? -(~byte & 0xff) - 1 : byte);
/**
* Check if a byte represents a special stitch (0x80).
* @param {number} byte
* @returns {boolean}
*/
const isSpecialStitch = (byte) => byte === 0x80;
/**
* Check if a byte represents a stop or trim command.
* @param {number} byte
* @returns {boolean}
*/
const isStopOrTrim = (byte) =>
(byte & 0x01) !== 0 || byte === 0x02 || byte === 0x04;
/**
* Check if a byte indicates end of pattern.
* @param {number} byte
* @returns {boolean}
*/
const isEndOfPattern = (byte) => byte === 0x10;
/**
* Check if a byte indicates a stop command.
* @param {number} byte
* @returns {boolean}
*/
const isStop = (byte) => (byte & 0x01) !== 0;
/**
* Read two stitch data bytes from the file.
* @param {EmbroideryFileView} file
* @returns {{ byte1: number, byte2: number }}
*/
const readStitchData = (file) => ({
byte1: file.getUint8(),
byte2: file.getUint8(),
});
/**
* Add colors from file data to the pattern.
* @param {EmbroideryFileView} file
* @param {EmbroideryPattern} pattern
* @param {number} colorCount
*/
const addColorsToPattern = (file, pattern, colorCount) => {
for (let i = 0; i < colorCount; i++) {
const colorIndex = file.getUint32(file.tell(), true) % colors.length;
pattern.addColor(colors[colorIndex]);
}
};
/**
* Determine the stitch type and potentially read additional bytes.
* @param {EmbroideryFileView} file
* @param {number} byte1
* @param {number} byte2
* @returns {{ type: number, byte1: number, byte2: number, end?: boolean }}
*/
const determineStitchType = (file, byte1, byte2) => {
if (isSpecialStitch(byte1)) {
if (isStopOrTrim(byte2)) {
return {
type: isStop(byte2) ? stitchTypes.stop : stitchTypes.trim,
byte1: file.getUint8(),
byte2: file.getUint8(),
};
} else if (isEndOfPattern(byte2)) {
return { type: stitchTypes.end, byte1: 0, byte2: 0, end: true };
}
}
return { type: stitchTypes.normal, byte1, byte2 };
};
/**
* Process stitches in the file and add them to the pattern.
* @param {EmbroideryFileView} file
* @param {EmbroideryPattern} pattern
* @param {number} stitchCount
*/
const processStitches = (file, pattern, stitchCount) => {
let stitchesProcessed = 0;
while (stitchesProcessed < stitchCount + 100) {
const { byte1, byte2 } = readStitchData(file);
const {
type,
byte1: decodedByte1,
byte2: decodedByte2,
end,
} = determineStitchType(file, byte1, byte2);
pattern.addStitchRel(
jefDecode(decodedByte1),
jefDecode(decodedByte2),
type,
true,
);
if (end) break;
stitchesProcessed++;
}
};
/**
* Reads a JEF file and adds stitches and colors to the pattern.
* @param {EmbroideryFileView} file
* @param {EmbroideryPattern} pattern
*/
export function jefRead(file, pattern) {
file.seek(24);
const colorCount = file.getInt32(file.tell(), true);
const stitchCount = file.getInt32(file.tell(), true);
file.seek(file.tell() + 84);
addColorsToPattern(file, pattern, colorCount);
file.seek(file.tell() + (6 - colorCount) * 4);
processStitches(file, pattern, stitchCount);
pattern.invertPatternVertical();
}
export const jefColors = colors;

View file

@ -1,5 +1,10 @@
import { pecColors, pecReadStitches } from "./pes";
import { pecColors, pecReadStitches } from './pes';
/**
*
* @param {EmbroideryFileView} file
* @param {EmbroideryPattern} pattern
*/
export function pecRead(file, pattern) {
let colorChanges, i;
file.seek(0x38);

View file

@ -0,0 +1,192 @@
import { Color, stitchTypes } from '$lib/file-renderer/pattern';
/**
* Array of predefined embroidery colors used in PEC files.
* @type {Color[]}
*/
export const pecColors = [
new Color(0, 0, 0, 'Unknown'),
new Color(14, 31, 124, 'Prussian Blue'),
new Color(10, 85, 163, 'Blue'),
new Color(0, 135, 119, 'Teal Green'),
new Color(75, 107, 175, 'Cornflower Blue'),
new Color(237, 23, 31, 'Red'),
new Color(209, 92, 0, 'Reddish Brown'),
new Color(145, 54, 151, 'Magenta'),
new Color(228, 154, 203, 'Light Lilac'),
new Color(145, 95, 172, 'Lilac'),
new Color(158, 214, 125, 'Mint Green'),
new Color(232, 169, 0, 'Deep Gold'),
new Color(254, 186, 53, 'Orange'),
new Color(255, 255, 0, 'Yellow'),
new Color(112, 188, 31, 'Lime Green'),
new Color(186, 152, 0, 'Brass'),
new Color(168, 168, 168, 'Silver'),
new Color(125, 111, 0, 'Russet Brown'),
new Color(255, 255, 179, 'Cream Brown'),
new Color(79, 85, 86, 'Pewter'),
new Color(0, 0, 0, 'Black'),
new Color(11, 61, 145, 'Ultramarine'),
new Color(119, 1, 118, 'Royal Purple'),
new Color(41, 49, 51, 'Dark Gray'),
new Color(42, 19, 1, 'Dark Brown'),
new Color(246, 74, 138, 'Deep Rose'),
new Color(178, 118, 36, 'Light Brown'),
new Color(252, 187, 197, 'Salmon Pink'),
new Color(254, 55, 15, 'Vermillion'),
new Color(240, 240, 240, 'White'),
new Color(106, 28, 138, 'Violet'),
new Color(168, 221, 196, 'Seacrest'),
new Color(37, 132, 187, 'Sky Blue'),
new Color(254, 179, 67, 'Pumpkin'),
new Color(255, 243, 107, 'Cream Yellow'),
new Color(208, 166, 96, 'Khaki'),
new Color(209, 84, 0, 'Clay Brown'),
new Color(102, 186, 73, 'Leaf Green'),
new Color(19, 74, 70, 'Peacock Blue'),
new Color(135, 135, 135, 'Gray'),
new Color(216, 204, 198, 'Warm Gray'),
new Color(67, 86, 7, 'Dark Olive'),
new Color(253, 217, 222, 'Flesh Pink'),
new Color(249, 147, 188, 'Pink'),
new Color(0, 56, 34, 'Deep Green'),
new Color(178, 175, 212, 'Lavender'),
new Color(104, 106, 176, 'Wisteria Violet'),
new Color(239, 227, 185, 'Beige'),
new Color(247, 56, 102, 'Carmine'),
new Color(181, 75, 100, 'Amber Red'),
new Color(19, 43, 26, 'Olive Green'),
new Color(199, 1, 86, 'Dark Fuschia'),
new Color(254, 158, 50, 'Tangerine'),
new Color(168, 222, 235, 'Light Blue'),
new Color(0, 103, 62, 'Emerald Green'),
new Color(78, 41, 144, 'Purple'),
new Color(47, 126, 32, 'Moss Green'),
new Color(255, 204, 204, 'Flesh Pink'),
new Color(255, 217, 17, 'Harvest Gold'),
new Color(9, 91, 166, 'Electric Blue'),
new Color(240, 249, 112, 'Lemon Yellow'),
new Color(227, 243, 91, 'Fresh Green'),
new Color(255, 153, 0, 'Orange'),
new Color(255, 240, 141, 'Cream Yellow'),
new Color(255, 200, 200, 'Applique'),
];
/**
* Reads stitch data from a PEC embroidery file and adds it to the pattern.
* @param {EmbroideryFileView} file
* @param {EmbroideryPattern} pattern - The pattern to populate.
*/
function readPecStitches(file, pattern) {
let stitchNumber = 0;
const byteCount = file.byteLength;
while (file.tell() < byteCount) {
let [xOffset, yOffset] = [file.getUint8(), file.getUint8()];
let stitchType = stitchTypes.normal;
if (isEndStitch(xOffset, yOffset)) {
pattern.addStitchRel(0, 0, stitchTypes.end, true);
break;
}
if (isStopStitch(xOffset, yOffset)) {
file.getInt8(); // Skip extra byte
pattern.addStitchRel(0, 0, stitchTypes.stop, true);
stitchNumber++;
continue;
}
stitchType = determineStitchType(xOffset, yOffset);
[xOffset, yOffset] = decodeCoordinates(xOffset, yOffset, file);
pattern.addStitchRel(xOffset, yOffset, stitchType, true);
// eslint-disable-next-line no-unused-vars
stitchNumber++;
}
}
/**
* Determines whether the stitch is an "end" stitch.
* @param {number} xOffset
* @param {number} yOffset
* @returns {boolean}
*/
function isEndStitch(xOffset, yOffset) {
return xOffset === 0xff && yOffset === 0x00;
}
/**
* Determines whether the stitch is a "stop" stitch.
* @param {number} xOffset
* @param {number} yOffset
* @returns {boolean}
*/
function isStopStitch(xOffset, yOffset) {
return xOffset === 0xfe && yOffset === 0xb0;
}
/**
* Infers the stitch type from byte flags.
* @param {number} xOffset
* @param {number} yOffset
* @returns {number}
*/
function determineStitchType(xOffset, yOffset) {
if (xOffset & 0x80) {
if (xOffset & 0x20) return stitchTypes.trim;
if (xOffset & 0x10) return stitchTypes.jump;
}
if (yOffset & 0x80) {
if (yOffset & 0x20) return stitchTypes.trim;
if (yOffset & 0x10) return stitchTypes.jump;
}
return stitchTypes.normal;
}
/**
* Decodes 12-bit signed coordinates from PEC format.
* @param {number} xOffset
* @param {number} yOffset
* @param {DataView & { tell: () => number, seek: (pos: number) => void, getUint8: () => number, getInt8: () => number }} file
* @returns {[number, number]} - Decoded [x, y] coordinates.
*/
function decodeCoordinates(xOffset, yOffset, file) {
if (xOffset & 0x80) {
xOffset = ((xOffset & 0x0f) << 8) + yOffset;
if (xOffset & 0x800) xOffset -= 0x1000;
yOffset = file.getUint8();
} else if (xOffset >= 0x40) {
xOffset -= 0x80;
}
if (yOffset & 0x80) {
yOffset = ((yOffset & 0x0f) << 8) + file.getUint8();
if (yOffset & 0x800) yOffset -= 0x1000;
} else if (yOffset > 0x3f) {
yOffset -= 0x80;
}
return [xOffset, yOffset];
}
/**
* Parses a PES file and adds stitch and color data to the pattern.
* @param {DataView & { tell: () => number, seek: (pos: number) => void, getUint8: () => number, getInt8: () => number }} file
* @param {EmbroideryPattern} pattern - The pattern to populate.
*/
export function pesRead(file, pattern) {
const pecStart = file.getInt32(8, true);
file.seek(pecStart + 48);
const numColors = file.getInt8() + 1;
for (let i = 0; i < numColors; i++) {
pattern.addColor(pecColors[file.getInt8()]);
}
file.seek(pecStart + 532);
readPecStitches(file, pattern);
pattern.addStitchRel(0, 0, stitchTypes.end);
}
export const pecReadStitches = readPecStitches;

View file

@ -0,0 +1,31 @@
/**
* A custom DataView with embroidery reader-specific helper methods.
* @typedef {DataView & {
* tell: () => number;
* seek: (pos: number) => void;
* getUint8: () => number;
* getInt8: () => number;
* getInt32: (pos: number, littleEndian: boolean) => number;
* }} EmbroideryFileView
*/
/**
* A Pattern extended with optional embroidery reader methods.
* @typedef {import('$lib/file-renderer/pattern').Pattern & {
* addColor?: (color: import('$lib/file-renderer/pattern').Color) => void;
* addStitchRel: (dx: number, dy: number, stitchType: string, autoAdvance?: boolean) => void;
* invertPatternVertical?: () => void;
* }} EmbroideryPattern
*/
/**
* Represents a reader for a specific embroidery file format.
* @typedef {Object} FormatReader
* @property {string} ext - File extension (e.g., '.pes', '.dst').
* @property {(view: EmbroideryFileView, pattern: EmbroideryPattern) => void} read - Function to parse the embroidery format and populate the pattern.
*/
/**
* A map of supported embroidery file formats keyed by format name (e.g., "pes", "dst").
* @typedef {Object.<string, FormatReader>} SupportedFormats
*/

View file

@ -1,29 +0,0 @@
<script>
import { t } from "../../i18n"
</script>
<section aria-labelledby="about-heading">
<h1 id="about-heading">{$t('about.title')}</h1>
{@html $t("about.content")}
</section>
<style>
section {
width: 70%;
margin: 0 auto;
}
h1 {
padding: 0;
margin-bottom: 7px;
}
@media (max-width: 768px) {
section {
width: 100%;
}
}
</style>

View file

@ -1,195 +0,0 @@
<script>
import { t } from "../../i18n"
import bitcoin from "../../assets/bitcoin.svg"
import monero from "../../assets/monero.svg"
import paypal from "../../assets/paypal.svg"
let bitcoinCopyStatus = '';
let moneroCopyStatus= '';
const onCopyMonero = async (text) => {
try {
const textarea = document.createElement('textarea');
textarea.value = text;
textarea.setAttribute('readonly', '');
textarea.style.position = 'absolute';
textarea.style.left = '-9999px';
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
document.body.removeChild(textarea);
moneroCopyStatus = 'donate.copied';
} catch (err) {
console.error('Copy failed:', err);
moneroCopyStatus = 'donate.copy.failed';
}
setTimeout(() => moneroCopyStatus = '', 2000);
};
const onCopyBitcoin = async (text) => {
try {
const textarea = document.createElement('textarea');
textarea.value = text;
textarea.setAttribute('readonly', '');
textarea.style.position = 'absolute';
textarea.style.left = '-9999px';
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
document.body.removeChild(textarea);
bitcoinCopyStatus = 'donate.copied';
} catch (err) {
console.error('Copy failed:', err);
bitcoinCopyStatus = 'donate.copy.failed';
}
setTimeout(() => bitcoinCopyStatus = '', 2000);
};
</script>
<section aria-labelledby="donate-title">
<h1 id="donate-title">{$t("donate.title")}</h1>
<p class="donate-subtitle">{$t("donate.subtitle")}</p>
<p>
{@html $t("donate.description")}
</p>
</section>
<section id="ways" aria-labelledby="ways-title">
<h2>{$t("donate.ways")}</h2>
<div class="donation-options">
<article class="donation-method" aria-labelledby="btc-label">
<img src={bitcoin} width="200" height="200" alt="Bitcoin QR code" />
<h3 id="btc-label">Bitcoin</h3>
<p>{$t("donate.bitcoin.description")}</p>
<button id="copy-btc" aria-label="Copy Bitcoin address" on:click={() => onCopyBitcoin("bc1qpc4lpyr6stxrrg3u0k4clp4crlt6z4j6q845rq")}>
{#if bitcoinCopyStatus}
{$t(bitcoinCopyStatus)}
{:else}
{$t("donate.copy")}
{/if}
</button>
</article>
<article class="donation-method" aria-labelledby="xmr-label">
<img src={monero} alt="Monero QR code" width="200" height="200" />
<h3 id="xmr-label">Monero</h3>
<p>{$t("donate.monero.description")}</p>
<button id="copy-monero" aria-label="Copy Monero address" on:click={() => onCopyMonero("8A9iyTskiBh6f6GDUwnUJaYhAW13gNjDYaZYJBftX434D3XLrcGBko4a8kC4pLSfiuJAoSJ7e8rwP8W4StsVypftCp6FGwm")}>
{#if moneroCopyStatus}
{$t(moneroCopyStatus)}
{:else}
{$t("donate.copy")}
{/if}
</button>
</article>
<article class="donation-method" aria-labelledby="bmc-label">
<img src={paypal} alt="PayPal" width="200" height="200" />
<h3 id="bmc-label">PayPal</h3>
<p>{$t("donate.paypal.description")}</p>
<a id="paypal-donation-link" aria-label="Paypal donation link" target="_blank" href="https://www.paypal.com/donate/?business=leo@leomurca.xyz&currency_code=USD">{$t("donate.paypal.link")}</a>
</article>
</div>
</section>
<style>
h1 {
padding: 0;
margin-bottom: 7px;
}
.donate-subtitle {
font-weight: bold;
color: #06345F;
margin: 0;
}
.donation-options {
display: flex;
justify-content: space-between;
}
.donation-method {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 33.33%;
}
.donation-method p {
margin-top: 0;
}
button {
font-size: 14px;
background-color: #05345f;
font-weight: bold;
color: white;
padding: 10px;
border: none;
border-radius: 10px;
width: 200px;
height: 45px;
}
button:hover {
cursor: pointer;
background-color: black;
color: white;
}
#paypal-donation-link {
font-size: 14px;
background-color: #05345f;
font-weight: bold;
color: white;
padding: 10px;
border: none;
border-radius: 10px;
width: 200px;
height: 45px;
text-align: center;
display: flex;
align-items: center;
justify-content: center;
}
#paypal-donation-link:hover {
cursor: pointer;
background-color: black;
color: white;
}
@media (max-width: 768px) {
button {
font-size: 1em;
width: 100%;
height: 55px;
}
#paypal-donation-link {
font-size: 1em;
width: 100%;
height: 55px;
margin: 0;
padding: 0;
}
.donation-options{
display: flex;
flex-direction: column;
gap: 50px;
justify-content: space-between;
}
.donation-method {
width: 100%;
}
}
</style>

View file

@ -1,60 +0,0 @@
<script>
import { t } from "../../i18n"
import { path } from '../../utils/stores.js';
const onNavigateTo = (e, route) => {
e.preventDefault()
history.pushState({}, '', route);
path.set(route);
}
</script>
<div class="home-container">
<section aria-labelledby="main-title">
<h1 id="main-title">{$t("home.main.title")}</h1>
{@html $t("home.main.description")}
</section>
<section aria-labelledby="features-title">
<h2 id="features-title">{$t("home.features.title")}</h2>
{@html $t("home.features.list")}
</section>
<section aria-labelledby="how-to-use-title">
<h2 id="how-to-use-title">{$t("home.howtouse.title")}</h2>
{@html $t("home.howtouse.list")}
</section>
<section aria-labelledby="testimonials-title">
<h2 id="testimonials-title">{$t("home.testimonials.title")}</h2>
{@html $t("home.testimonials.description")}
</section>
<section aria-labelledby="donation-title">
<h2 id="donation-title">{$t("home.donation.title")}</h2>
{@html $t("home.donation.description")}
<p><a href="#" on:click={(e) => onNavigateTo(e, "/donate")} class="button">{$t("home.donation.cta")}</a> {$t("home.donation.cta.description")}</p>
</section>
<!--TODO: add video preview-->
<section aria-labelledby="cta-title">
<h2 id="cta-title">{$t("home.cta.title")}</h2>
<p><a href="#" on:click={(e) => onNavigateTo(e, "/viewer")} class="button">{$t("home.cta.cta")}</a> {@html $t("home.cta.cta.description")}</p>
</section>
</div>
<style>
.home-container {
margin: 0 auto;
width: 70%;
}
@media (max-width: 768px) {
.home-container {
width: 100%;
}
}
</style>

View file

@ -1,2 +0,0 @@
<h1>404 - Not Found</h1>
<p>Oops! That route does not exist.</p>

View file

@ -1,25 +0,0 @@
<script>
import { t } from "../../i18n"
</script>
<section aria-labelledby="privacy-policy-heading">
<h1 id="privacy-policy-heading">{$t('privacy.policy.title')}</h1>
<p><em>{$t('privacy.policy.last.update')}</em></p>
{@html $t('privacy.policy.content')}
</section>
<style>
section {
width: 70%;
margin: 0 auto;
}
h2 {
font-size: 17px;
}
@media (max-width: 768px) {
section {
width: 100%;
}
}
</style>

View file

@ -1,26 +0,0 @@
<script>
import { t } from "../../i18n"
</script>
<section aria-labelledby="tos-heading">
<h1 id="tos-heading">{$t('terms.of.service.title')}</h1>
<p><em>{$t('terms.of.service.update')}</em></p>
{@html $t('terms.of.service.content')}
</section>
<style>
section {
width: 70%;
margin: 0 auto;
}
h2 {
font-size: 17px;
}
@media (max-width: 768px) {
section {
width: 100%;
}
}
</style>

View file

@ -1,4 +0,0 @@
<script>
import FileViewer from "../components/FileViewer.svelte"
</script>
<FileViewer/>

View file

@ -1,16 +0,0 @@
<script>
import { t, locale } from "../../i18n";
import thumbnail from "../../assets/thumbnail.webp";
$: document.documentElement.lang = $locale;
</script>
<svelte:head>
<title>{$t("head.title")}</title>
<meta name="description" content="{$t('head.description')}" />
<meta name="keywords" content="{$t('head.keywords')}">
<meta property="og:title" content="{$t('head.ogtitle')}">
<meta property="og:description" content="{$t('head.ogdescription')}">
<meta property="og:url" content="https://embroideryviewer.xyz/">
<meta property="og:type" content="website">
<meta property="og:image" content="{thumbnail}">
</svelte:head>

View file

@ -1,14 +0,0 @@
<script>
import Router from "../components/Router.svelte";
</script>
<main>
<Router />
</main>
<style>
main {
flex: 1; /* This pushes footer to bottom */
padding: 20px;
min-height: 90vh;
}
</style>

View file

@ -0,0 +1,9 @@
{
"title": " About Embroidery Viewer",
"content": "<p>Hi there! 👋</p><p><strong>⭐️ Embroidery Viewer</strong> was born out of a simple need — helping someone I care about. 💖</p><p>My girlfriend loves embroidery, but she often struggled to find an easy and free way to preview her embroidery design files before stitching them. Most tools she tried were either paid, overly complex, or required technical knowledge — and shes not a techie.</p><p>So, to make things easier for her (and others like her), I decided to build this web application.</p><p>Over the course of a few weeks, I created <strong>Embroidery Viewer</strong> — a lightweight, fast, and free tool that lets you view embroidery files directly in your browser. No installation, no setup, and no tech hurdles. Just upload your file and see your design.</p><p>Its not a super sophisticated tool, but it solves the problem it was meant to solve: making embroidery file previews accessible to everyone.</p><p>If this tool has helped you too, that makes me really happy! I plan to continue improving it based on feedback from users like you.</p><p>Thanks for stopping by — and happy stitching! 🧵✨</p>",
"seo.title": " About Embroidery Viewer The Story Behind the Tool",
"seo.description": "Learn the story behind Embroidery Viewer — a free, online tool created to make embroidery file previews simple, fast, and accessible to everyone.",
"seo.keywords": "about embroidery viewer, embroidery viewer story, free embroidery viewer, why embroidery viewer was created, who created embroidery viewer, online embroidery viewer, free embroidery tool, embroidery viewer about",
"seo.url": "https://embroideryviewer.xyz/about",
"seo.image": "https://embroideryviewer.xyz/og/about.png"
}

View file

@ -0,0 +1,18 @@
{
"title": "💖 Donate",
"subtitle": "Help support Embroidery Viewer and its development!",
"description": "⭐️ <strong>Embroidery Viewer</strong> is free to use. If you find this tool helpful, please consider making a donation to keep it running and fund future improvements.",
"ways": "💸 Ways to Donate",
"bitcoin.description": "Scan or copy the address",
"copy": "Copy Address",
"copied": "Copied to Clipboard!",
"copy.failed": "Copy Failed!",
"monero.description": "Private and secure donation option.",
"paypal.description": "Want to show support in a friendly way?",
"paypal.link": "Open Donation link",
"seo.title": "💖 Donate Support Embroidery Viewer",
"seo.description": "Help keep Embroidery Viewer free and improving by making a donation. Choose from Bitcoin, Monero, PayPal, or other secure options to support ongoing development and hosting.",
"keywords": "donate embroidery viewer, support embroidery viewer, embroidery viewer donations, help embroidery viewer, fund embroidery viewer, bitcoin donation embroidery, monero donation embroidery, paypal donation embroidery",
"url": "https://embroideryviewer.xyz/donate",
"image": "https://embroideryviewer.xyz/og/donate.png"
}

View file

@ -0,0 +1,7 @@
{
"about": " About",
"privacy.policy": "🔐 Privacy Policy",
"terms.of.service": "📝 Terms of Service",
"copyright": "Copyright © {{year}} <a href=\"{{website}}\" target=\"_blank\" rel=\"noreferrer\">Leonardo Murça</a>. <br/> All rights reserved.",
"version": "🧵 Version: {{version}}"
}

View file

@ -0,0 +1,7 @@
{
"languageSwitch": "🇧🇷",
"homeNav": "🏠 Home",
"aboutNav": " About",
"viewerNav": "🧵 Viewer",
"donateNav": "💖 Donate"
}

View file

@ -0,0 +1,22 @@
{
"main.title": "🧵 Free Online Embroidery File Viewer",
"main.description": "<p>✨Upload and preview your embroidery designs instantly no software needed.</p> <p><strong>Embroidery Viewer</strong> is a free, browser-based tool that supports multiple embroidery file formats. View your designs quickly and securely, right in your browser.</p>",
"features.title": "🚀 Features",
"features.list": "<ul><li>📂 <strong>Supports Multiple Formats:</strong> DST, PES, JEF, EXP, VP3, and more</li><li>⚡ <strong>Quick Previews:</strong> See your embroidery files rendered as images</li><li>🧷 <strong>Multiple Files at Once:</strong> Upload several designs and view them side-by-side</li><li>🔒 <strong>No Upload to Server:</strong> Your files stay private all processing happens locally</li><li>⬇️ <strong>Download as Image:</strong> Save each embroidery design preview as a PNG</li><li>💸 <strong>Fast & Free:</strong> No installations, no sign-ups just open and use</li></ul>",
"howtouse.title": "📘 How to Use",
"howtouse.list": "<ol><li>📁 <strong>Click</strong> the upload button <em>or</em> <strong>drag and drop</strong> your embroidery files into the drop area</li><li>🧵 Select one or more embroidery files</li><li>▶️ Click the <strong>“Render files”</strong> button to preview your designs</li><li>👀 Instantly view your designs right in your browser its that simple</li></ol>",
"testimonials.title": "❤️ Loved by Hobbyists and Professionals",
"testimonials.description": "<p>Whether you're a hobbyist working on your next DIY project or a professional digitizer reviewing client files, <strong>Embroidery Viewer</strong> gives you a no-fuss, instant way to visualize your work.</p>",
"donation.title": "💖 Help Keep It Free",
"donation.description": "<p><strong>Embroidery Viewer is completely free</strong> for everyone to use.</p><p>If you find it useful and want to support ongoing development and hosting costs, please consider making a small donation.</p>",
"donation.cta": "🙌 Donate Now",
"donation.cta.description": "every little bit helps!",
"cta.title": "🚀 Try It Now",
"cta.cta": "🧵 Open Viewer",
"cta.cta.description": "the fastest <strong>Free Online Embroidery File Viewer</strong>.",
"seo.title": "🏠 Free Online Embroidery File Viewer - Fast, Private & No Signup",
"seo.description": "Upload and preview embroidery files instantly with Embroidery Viewer. Supports DST, PES, JEF, EXP, VP3 and more. No installs, no uploads 100% browser-based and free.",
"seo.keywords": "embroidery viewer, online embroidery viewer, embroidery file preview, DST viewer, PES viewer, free embroidery tool, JEF viewer, EXP embroidery, VP3 embroidery viewer, embroidery preview tool, browser embroidery renderer, convert embroidery to PNG",
"seo.url": "https://embroideryviewer.xyz",
"seo.image": "https://embroideryviewer.xyz/og/"
}

View file

@ -0,0 +1,10 @@
{
"title": "🔐 Privacy Policy",
"last.update": "Last updated: May 9, 2025",
"content": "<p>At <strong>Embroidery Viewer</strong> (<a href=\"https://embroideryviewer.xyz\">embroideryviewer.xyz</a>), we respect your privacy and are committed to protecting any information you share while using our service.</p><h2>1. Personal Information</h2><p>Embroidery Viewer does <strong>not</strong> collect or store any personal information. You do not need to create an account, and we do not ask for your name, email address, or any identifying details.</p><h2>2. File Uploads</h2><p>When you upload an embroidery file to the viewer, the file is processed in your browser or temporarily on our server (if required) for preview purposes only. <strong>No uploaded files are stored, saved, or shared.</strong></p><p>Please avoid uploading any copyrighted or sensitive material unless you have permission to use it.</p><h2>3. Analytics</h2><p>We use <strong>Umami</strong> to collect anonymous usage statistics about our website, such as the number of visitors, page views, device types, and referral sources. This data helps us understand how the site is being used and improve it over time.</p><p>Umami is a privacy-friendly, cookie-free analytics tool. It does <strong>not</strong> track users across sites, collect personal data, or use cookies. All data is aggregated and anonymized.</p><h2>4. Cookies</h2><p>Embroidery Viewer does <strong>not</strong> use cookies or other tracking mechanisms in your browser.</p><h2>5. Third-Party Services</h2><p>We do not use third-party advertising, embed external trackers, or share data with third parties.</p><h2>6. Changes to This Policy</h2><p>We may update this Privacy Policy from time to time. All updates will be posted on this page with the updated date.</p><h2>7. Contact</h2><p>If you have any questions about this Privacy Policy, you can reach us at <a href=\"mailto:leo@leomurca.xyz\">leo@leomurca.xyz</a>.</p>",
"seo.title": "🔐 Privacy Policy - Embroidery Viewer",
"seo.description": "Learn how Embroidery Viewer respects your privacy. No personal data collected, files processed locally or temporarily, anonymous analytics only, no cookies or trackers used.",
"seo.keywords": "privacy policy, data protection, embroidery viewer privacy, file uploads privacy, anonymous analytics, no cookies, user privacy, privacy-friendly analytics, data security, embroideryviewer.xyz",
"seo.url": "https://embroideryviewer.xyz/privacy-policy",
"seo.image": "https://embroideryviewer.xyz/og/privacy-policy.png"
}

View file

@ -0,0 +1,10 @@
{
"title": "📝 Terms of Service",
"update": "May 9, 2025",
"content": "<p>Welcome to <strong>Embroidery Viewer</strong> (<a href=\"https://embroideryviewer.xyz\">embroideryviewer.xyz</a>). By accessing or using this website, you agree to be bound by the following Terms of Service. If you do not agree with any part of these terms, please do not use the site.</p><h2>1. Description of Service</h2><p>Embroidery Viewer is a free, browser-based tool that allows users to preview embroidery design files online. The service is intended for personal, non-commercial use.</p><h2>2. Use of the Service</h2><p>You agree to use the service only for lawful purposes. You are solely responsible for any content (including embroidery files) you upload, and you confirm that you have the legal right to use, view, and process those files.</p><p>You agree not to upload any files that are illegal, offensive, infringe on intellectual property rights, or contain malicious code.</p><h2>3. File Processing</h2><p>Files uploaded to Embroidery Viewer are processed either directly in your browser or temporarily on our servers. Files are not stored permanently, shared, or backed up.</p><p>While we aim to keep your content secure, you acknowledge that no system is 100% secure and you use the service at your own risk.</p><h2>4. No Warranty</h2><p>This service is provided \"as is\" and \"as available\" without any warranties, express or implied. We do not guarantee that the service will be uninterrupted, secure, or error-free.</p><h2>5. Limitation of Liability</h2><p>Embroidery Viewer shall not be held liable for any damages resulting from the use or inability to use the service, including but not limited to loss of data, loss of profits, or other incidental or consequential damages.</p><h2>6. Modifications to the Service</h2><p>We reserve the right to modify, suspend, or discontinue the service at any time without notice. We may also update these Terms of Service from time to time. Continued use of the service after changes constitutes your acceptance of the new terms.</p><h2>7. Governing Law</h2><p>These Terms shall be governed by and interpreted in accordance with the laws of Brazil, without regard to its conflict of law principles.</p><h2>8. Contact</h2><p>If you have any questions about these Terms of Service, feel free to contact us at <a href=\"mailto:leo@leomurca.xyz\">leo@leomurca.xyz</a>.</p>",
"seo.title": "📝 Terms of Service - Embroidery Viewer",
"seo.description": "Read the Terms of Service for Embroidery Viewer. Personal use, upload rules, file processing, warranty disclaimers, liability limitations, and governing law.",
"seo.keywords": "terms of service, terms of use, personal use, file upload, file processing, warranty disclaimer, liability limitation, Brazilian law, embroideryviewer.xyz",
"seo.url": "https://embroideryviewer.xyz/terms-of-service",
"seo.image": "https://embroideryviewer.xyz/og/terms-of-service.png"
}

View file

@ -0,0 +1,19 @@
{
"title": "Upload files",
"fileSize": "Max file size is <strong>{{fileSize}}MB</strong>.",
"supportedFormats": "Accepted formats: <strong>{{supportedFormats}}</strong>.",
"render": "Render files",
"dropzone": "<strong>Choose files</strong><br /><span>or drag and drop them here</span>",
"browse": "Browse",
"selected": "Selected files",
"rejected": "Rejected files",
"stitches": "Stitches",
"dimensions": "Dimensions (x, y)",
"download": "Download image",
"warning.copyright": "Do not upload copyrighted material you do not own or have rights to.",
"seo.title": "🧵 Free Online Embroidery File Viewer Fast, Private & No Signup",
"seo.description": "Upload and preview your embroidery files instantly with Embroidery Viewer. Supports DST, PES, JEF, EXP, VP3, and more. No installs, no uploads 100% browser-based and free.",
"seo.keywords": "embroidery viewer, online embroidery viewer, embroidery file preview, DST viewer, PES viewer, free embroidery tool, JEF viewer, EXP embroidery, VP3 embroidery viewer, embroidery preview tool, browser embroidery renderer, convert embroidery to PNG",
"seo.url": "https://embroideryviewer.xyz/viewer",
"seo.image": "https://embroideryviewer.xyz/og/viewer.png"
}

View file

@ -0,0 +1,133 @@
import i18n from 'sveltekit-i18n';
/**
* A frozen object mapping locale identifiers to their respective locale codes.
*
* These values represent the supported languages in the application.
* Used for validating user preferences and loading the correct translations.
*
* @readonly
* @enum {string}
*/
export const SUPPORTED_LOCALES = Object.freeze({
EN_US: 'en-US',
PT_BR: 'pt-BR',
});
/** @type {import('sveltekit-i18n').Config} */
const config = {
initLocale: navigator.language,
fallbackLocale: SUPPORTED_LOCALES.EN_US,
loaders: [
{
locale: SUPPORTED_LOCALES.EN_US,
key: 'header',
loader: async () => (await import('./en-US/header.json')).default,
},
{
locale: SUPPORTED_LOCALES.EN_US,
key: 'footer',
loader: async () => (await import('./en-US/footer.json')).default,
},
{
locale: SUPPORTED_LOCALES.EN_US,
key: 'home',
routes: ['/'],
loader: async () => (await import('./en-US/home.json')).default,
},
{
locale: SUPPORTED_LOCALES.EN_US,
key: 'about',
routes: ['/about'],
loader: async () => (await import('./en-US/about.json')).default,
},
{
locale: SUPPORTED_LOCALES.EN_US,
key: 'donate',
routes: ['/donate'],
loader: async () => (await import('./en-US/donate.json')).default,
},
{
locale: SUPPORTED_LOCALES.EN_US,
key: 'privacy.policy',
routes: ['/privacy-policy'],
loader: async () => (await import('./en-US/privacy-policy.json')).default,
},
{
locale: SUPPORTED_LOCALES.EN_US,
key: 'terms.of.service',
routes: ['/terms-of-service'],
loader: async () =>
(await import('./en-US/terms-of-service.json')).default,
},
{
locale: SUPPORTED_LOCALES.EN_US,
key: 'viewer',
routes: ['/viewer'],
loader: async () => (await import('./en-US/viewer.json')).default,
},
{
locale: SUPPORTED_LOCALES.PT_BR,
key: 'header',
loader: async () => (await import('./pt-BR/header.json')).default,
},
{
locale: SUPPORTED_LOCALES.PT_BR,
key: 'footer',
loader: async () => (await import('./pt-BR/footer.json')).default,
},
{
locale: SUPPORTED_LOCALES.PT_BR,
key: 'home',
routes: ['/'],
loader: async () => (await import('./pt-BR/home.json')).default,
},
{
locale: SUPPORTED_LOCALES.PT_BR,
key: 'about',
routes: ['/about'],
loader: async () => (await import('./pt-BR/about.json')).default,
},
{
locale: SUPPORTED_LOCALES.PT_BR,
key: 'donate',
routes: ['/donate'],
loader: async () => (await import('./pt-BR/donate.json')).default,
},
{
locale: SUPPORTED_LOCALES.PT_BR,
key: 'privacy.policy',
routes: ['/privacy-policy'],
loader: async () => (await import('./pt-BR/privacy-policy.json')).default,
},
{
locale: SUPPORTED_LOCALES.PT_BR,
key: 'terms.of.service',
routes: ['/terms-of-service'],
loader: async () =>
(await import('./pt-BR/terms-of-service.json')).default,
},
{
locale: SUPPORTED_LOCALES.PT_BR,
key: 'viewer',
routes: ['/viewer'],
loader: async () => (await import('./pt-BR/viewer.json')).default,
},
],
};
export const {
t,
locale,
locales,
loading,
loadTranslations,
setRoute,
setLocale,
} = new i18n(config);
locale.subscribe(($locale) => {
if (typeof document !== 'undefined') {
document.cookie = `locale=${$locale}; path=/; SameSite=Strict;`;
}
});

View file

@ -0,0 +1,9 @@
{
"title": " Sobre o Embroidery Viewer",
"content": "<p>Oi! 👋</p><p><strong>⭐️ Embroidery Viewer</strong> nasceu de uma necessidade simples — ajudar alguém que eu amo. 💖</p><p>Minha namorada adora bordado, mas ela sempre teve dificuldades para encontrar uma maneira fácil e gratuita de visualizar os arquivos de design de bordado antes de começar a costurar. A maioria das ferramentas que ela tentou eram pagas, muito complexas ou exigiam conhecimento técnico — e ela não é da área de tecnologia.</p><p>Então, para facilitar a vida dela (e de outras pessoas como ela), decidi criar este aplicativo web.</p><p>Ao longo de algumas semanas, criei o <strong>Embroidery Viewer</strong> — uma ferramenta leve, rápida e gratuita que permite visualizar arquivos de bordado diretamente no navegador. Sem instalação, sem configuração e sem obstáculos técnicos. Basta enviar o arquivo e ver o design.</p><p>Não é uma ferramenta super sofisticada, mas resolve o problema para o qual foi criada: tornar a visualização de arquivos de bordado acessível para todos.</p><p>Se essa ferramenta também te ajudou, isso me deixa muito feliz! Pretendo continuar melhorando com base no feedback de usuários como você.</p><p>Obrigado por visitar — e bons bordados! 🧵✨</p>",
"seo.title": "Sobre o Embroidery Viewer - Por que esta ferramenta foi criada",
"seo.description": "Conheça a história por trás do Embroidery Viewer — uma ferramenta gratuita e online criada para tornar a visualização de arquivos de bordado simples, rápida e acessível a todos.",
"seo.keywords": "sobre embroidery viewer, história do embroidery viewer, visualizador de bordado gratuito, motivo da criação do embroidery viewer, quem criou o embroidery viewer, visualizador online de bordado, ferramenta gratuita para bordado, embroidery viewer sobre",
"seo.url": "https://embroideryviewer.xyz/about",
"seo.image": "https://embroideryviewer.xyz/og/about.png"
}

View file

@ -0,0 +1,18 @@
{
"title": "💖 Doe",
"subtitle": "Ajude a apoiar o Embroidery Viewer e seu desenvolvimento!",
"description": "⭐️ O <strong>Embroidery Viewer</strong> é gratuito. Se você achar esta ferramenta útil, considere fazer uma doação para mantê-la funcionando e financiar melhorias futuras.",
"ways": "💸 Formas de doar",
"bitcoin.description": "Escaneie ou copie o endereço",
"copy": "Copiar Endereço",
"copied": "Copiado para a área de transferência!",
"copy.failed": "Falha na Cópia!",
"monero.description": "Opção de doação privada e segura.",
"paypal.description": "Quer demonstrar apoio de uma forma amigável?",
"paypal.link": "Abrir Link de Doação",
"seo.title": "💖 Doe Apoie o Embroidery Viewer",
"seo.description": "Ajude a manter o Embroidery Viewer gratuito e em constante melhoria fazendo uma doação. Escolha entre Bitcoin, Monero, PayPal ou outras opções seguras para apoiar o desenvolvimento e hospedagem.",
"seo.keywords": "doar embroidery viewer, apoie embroidery viewer, doações embroidery viewer, ajudar embroidery viewer, financiar embroidery viewer, doação bitcoin embroidery, doação monero embroidery, doação paypal embroidery",
"url": "https://embroideryviewer.xyz/doar",
"image": "https://embroideryviewer.xyz/og/doar.png"
}

View file

@ -0,0 +1,7 @@
{
"about": " Sobre",
"privacy.policy": "🔐 Política de Privacidade",
"terms.of.service": "📝 Termos de Serviço",
"copyright": "Copyright © {{year}} <a href=\"{{website}}/pt-br\" target=\"_blank\" rel=\"noreferrer\">Leonardo Murça</a>. <br/> Todos os direitos reservados.",
"version": "🧵 Versão: {{version}}"
}

View file

@ -0,0 +1,7 @@
{
"languageSwitch": "🇺🇸",
"homeNav": "🏠 Página Inicial",
"aboutNav": " Sobre",
"viewerNav": "🧵 Visualizador",
"donateNav": "💖 Doe"
}

View file

@ -0,0 +1,22 @@
{
"main.title": "🧵 Visualizador de arquivos de bordado online gratuito",
"main.description": "<p>✨Carregue e visualize seus desenhos de bordado instantaneamente sem necessidade de software</p> <p><strong>Embroidery Viewer</strong> é uma ferramenta gratuita para navegador que suporta diversos formatos de arquivo de bordado. Visualize seus designs de forma rápida e segura, diretamente no seu navegador.</p>",
"features.title": "🚀 Funcionalidades",
"features.list": "<ul><li>📂 <strong>Suporta vários formatos:</strong> DST, PES, JEF, EXP, VP3 e mais</li><li>⚡ <strong>Visualizações rápidas:</strong> Veja seus arquivos de bordado renderizados como imagens</li><li>🧷 <strong>Vários arquivos de uma só vez:</strong> Carregue vários designs e visualize-os lado a lado</li><li>🔒 <strong>Sem upload para o servidor:</strong> Seus arquivos permanecem privados todo o processamento acontece localmente</li><li>⬇️ <strong>Baixar como imagem:</strong> Salve cada pré-visualização do desenho do bordado como um PNG</li><li>💸 <strong>Rápido e gratuito:</strong> Sem instalações, sem cadastros basta abrir e usar</li></ul>",
"howtouse.title": "📘 Como usar",
"howtouse.list": "<ol><li>📁 <strong>Clique</strong> no botão de upload <em>ou</em> <strong>arraste e solte</strong> seus arquivos de bordado na área de soltar</li><li>🧵 Selecione um ou mais arquivos de bordado</li><li>▶️ Clique no botão <strong>“Renderizar arquivos”</strong> para visualizar seus designs</li><li>👀 Visualize seus designs instantaneamente no seu navegador é simples assim</li></ol>",
"testimonials.title": "❤️ Amado por Hobbyistas e Profissionais",
"testimonials.description": "<p>Seja você um amador trabalhando em seu próximo projeto \"faça você mesmo\" ou um digitalizador profissional revisando arquivos de clientes, o <strong>Embroidery Viewer</strong> oferece uma maneira fácil e instantânea de visualizar seu trabalho.</p>",
"donation.title": "💖 Ajude a mantê-lo gratuito",
"donation.description": "<p><strong>O Embroidery Viewer é totalmente gratuito</strong> para todos usarem.</p><p>Se você o achar útil e quiser apoiar o desenvolvimento contínuo e os custos de hospedagem, considere fazer uma pequena doação.</p>",
"donation.cta": "🙌 Doe agora",
"donation.cta.description": "cada pequena ajuda é bem-vinda!",
"cta.title": "🚀 Experimente agora",
"cta.cta": "🧵 Abrir visualizador",
"cta.cta.description": "o <strong>visualizador de arquivos de bordado online gratuito</strong> mais rápido.",
"seo.title": "🏠 Visualizador de Bordado Online Grátis - Rápido, Privado e Sem Cadastro",
"seo.description": "Envie e visualize arquivos de bordado instantaneamente com o Embroidery Viewer. Compatível com DST, PES, JEF, EXP, VP3 e mais. Sem instalações, sem uploads 100% no navegador e gratuito.",
"seo.keywords": "visualizador de bordado, visualizador online de bordado, visualizar arquivos de bordado, visualizar DST, visualizar PES, ferramenta gratuita de bordado, visualizador JEF, bordado EXP, visualizador VP3, pré-visualização de bordado, renderizador de bordado no navegador, converter bordado em PNG",
"seo.url": "https://embroideryviewer.xyz",
"seo.image": "https://embroideryviewer.xyz/og/"
}

View file

@ -0,0 +1,10 @@
{
"title": "🔐 Política de Privacidade",
"last.update": "Última atualização: 9 de maio de 2025",
"content": "<p>No <strong>Embroidery Viewer</strong> (<a href=\"https://embroideryviewer.xyz\">embroideryviewer.xyz</a>), respeitamos sua privacidade e estamos comprometidos em proteger qualquer informação que você compartilhe ao usar nosso serviço.</p><h2>1. Informações Pessoais</h2><p>O Embroidery Viewer <strong>não</strong> coleta nem armazena informações pessoais. Você não precisa criar uma conta e não pedimos seu nome, e-mail ou qualquer dado identificável.</p><h2>2. Envio de Arquivos</h2><p>Quando você envia um arquivo de bordado para o visualizador, o arquivo é processado no seu navegador ou temporariamente em nosso servidor (se necessário) apenas para fins de visualização. <strong>Nenhum arquivo enviado é armazenado, salvo ou compartilhado.</strong></p><p>Evite enviar materiais sensíveis ou protegidos por direitos autorais, a menos que tenha permissão para usá-los.</p><h2>3. Análises</h2><p>Utilizamos o <strong>Umami</strong> para coletar estatísticas anônimas de uso do site, como número de visitantes, visualizações de página, tipos de dispositivo e fontes de acesso. Esses dados nos ajudam a entender como o site está sendo utilizado e melhorá-lo com o tempo.</p><p>O Umami é uma ferramenta de análise que respeita a privacidade, não usa cookies e não rastreia os usuários entre sites. Todos os dados são agregados e anonimizados.</p><h2>4. Cookies</h2><p>O Embroidery Viewer <strong>não</strong> utiliza cookies ou outros mecanismos de rastreamento em seu navegador.</p><h2>5. Serviços de Terceiros</h2><p>Não utilizamos publicidade de terceiros, nem incorporamos rastreadores externos, nem compartilhamos dados com terceiros.</p><h2>6. Alterações nesta Política</h2><p>Podemos atualizar esta Política de Privacidade ocasionalmente. Todas as atualizações serão publicadas nesta página com a data de modificação.</p><h2>7. Contato</h2><p>Se você tiver dúvidas sobre esta Política de Privacidade, entre em contato pelo e-mail <a href=\"mailto:leo@leomurca.xyz\">leo@leomurca.xyz</a>.</p>",
"seo.title": "🔐 Política de Privacidade - Embroidery Viewer",
"seo.description": "Saiba como o Embroidery Viewer respeita sua privacidade. Nenhum dado pessoal é coletado, arquivos processados localmente ou temporariamente, análises anônimas, sem cookies ou rastreadores.",
"seo.keywords": "política de privacidade, proteção de dados, privacidade embroidery viewer, upload de arquivos, análises anônimas, sem cookies, privacidade do usuário, análises que respeitam a privacidade, segurança de dados, embroideryviewer.xyz",
"seo.url": "https://embroideryviewer.xyz/privacy-policy",
"seo.image": "https://embroideryviewer.xyz/og/privacy-policy.png"
}

View file

@ -0,0 +1,10 @@
{
"title": "📝 Termos de Serviço",
"update": "Última atualização: 9 de maio de 2025",
"content": "<p>Bem-vindo ao <strong>Embroidery Viewer</strong> (<a href=\"https://embroideryviewer.xyz\">embroideryviewer.xyz</a>). Ao acessar ou utilizar este site, você concorda em estar vinculado aos seguintes Termos de Serviço. Se você não concordar com qualquer parte destes termos, por favor, não utilize o site.</p><h2>1. Descrição do Serviço</h2><p>O Embroidery Viewer é uma ferramenta gratuita baseada em navegador que permite aos usuários visualizar arquivos de design de bordado online. O serviço é destinado ao uso pessoal e não comercial.</p><h2>2. Uso do Serviço</h2><p>Você concorda em usar o serviço apenas para fins legais. Você é o único responsável por qualquer conteúdo (incluindo arquivos de bordado) que enviar, e confirma que tem o direito legal de usar, visualizar e processar esses arquivos.</p><p>Você concorda em não enviar arquivos que sejam ilegais, ofensivos, infrinjam direitos de propriedade intelectual ou contenham código malicioso.</p><h2>3. Processamento de Arquivos</h2><p>Os arquivos enviados para o Embroidery Viewer são processados diretamente em seu navegador ou temporariamente em nossos servidores. Os arquivos não são armazenados permanentemente, compartilhados ou backupados.</p><p>Embora tenhamos o objetivo de manter seu conteúdo seguro, você reconhece que nenhum sistema é 100% seguro e você utiliza o serviço por sua conta e risco.</p><h2>4. Sem Garantia</h2><p>Este serviço é fornecido \"como está\" e \"como disponível\", sem quaisquer garantias, expressas ou implícitas. Não garantimos que o serviço será ininterrupto, seguro ou sem erros.</p><h2>5. Limitação de Responsabilidade</h2><p>O Embroidery Viewer não será responsabilizado por quaisquer danos resultantes do uso ou da impossibilidade de usar o serviço, incluindo, mas não se limitando a, perda de dados, perda de lucros ou outros danos incidentais ou consequenciais.</p><h2>6. Modificações no Serviço</h2><p>Reservamo-nos o direito de modificar, suspender ou descontinuar o serviço a qualquer momento, sem aviso prévio. Podemos também atualizar estes Termos de Serviço de tempos em tempos. O uso contínuo do serviço após as mudanças constitui sua aceitação dos novos termos.</p><h2>7. Lei Aplicável</h2><p>Estes Termos serão regidos e interpretados de acordo com as leis do Brasil, sem levar em consideração seus princípios de conflitos de leis.</p><h2>8. Contato</h2><p>Se você tiver qualquer dúvida sobre estes Termos de Serviço, sinta-se à vontade para entrar em contato conosco pelo e-mail <a href=\"mailto:leo@leomurca.xyz\">leo@leomurca.xyz</a>.</p>",
"seo.title": "📝 Termos de Serviço - Embroidery Viewer",
"seo.description": "Leia os Termos de Serviço do Embroidery Viewer. Uso pessoal, regras de upload, processamento de arquivos, isenção de garantias, limitações de responsabilidade e legislação aplicável.",
"seo.keywords": "termos de serviço, condições de uso, uso pessoal, upload de arquivos, processamento de arquivos, isenção de garantias, limitações de responsabilidade, legislação brasileira, embroideryviewer.xyz",
"seo.url": "https://embroideryviewer.xyz/termos-de-servico",
"seo.image": "https://embroideryviewer.xyz/og/termos-de-servico.png"
}

View file

@ -0,0 +1,19 @@
{
"title": "Carregar arquivos",
"languageSwitch": "🇺🇸",
"fileSize": "O tamanho máximo de cada arquivo é <strong>{{fileSize}}MB</strong>.",
"supportedFormats": "Formatos aceitos: <strong>{{supportedFormats}}</strong>.",
"render": "Renderizar arquivos",
"dropzone": "<strong>Selecione arquivos</strong><br /><span>ou arraste e solte-os aqui</span>",
"browse": "Selecionar arquivos",
"selected": "Arquivos selecionados",
"rejected": "Arquivos recusados",
"stitches": "Pontos",
"download": "Baixar imagem",
"warning.copyright": "Não carregue material protegido por direitos autorais que você não possui ou sobre os quais não tenha direitos.",
"seo.title": "🧵 Visualizador Online Gratuito de Arquivos de Bordado Rápido, Privado e Sem Cadastro",
"seo.description": "Faça upload e visualize seus arquivos de bordado instantaneamente com o Embroidery Viewer. Suporta DST, PES, JEF, EXP, VP3 e muito mais. Sem instalações, sem upload para servidor 100% baseado no navegador e gratuito.",
"seo.keywords": "visualizador de bordado, visualizador online de bordado, pré-visualização de arquivos de bordado, visualizador DST, visualizador PES, ferramenta gratuita de bordado, visualizador JEF, bordado EXP, visualizador VP3, ferramenta de pré-visualização de bordado, renderizador de bordado no navegador, converter bordado para PNG",
"seo.url": "https://embroideryviewer.xyz/viewer",
"seo.image": "https://embroideryviewer.xyz/og/viewer.png"
}

View file

@ -1,5 +1,6 @@
// @ts-nocheck
function appVersion() {
/* eslint-disable no-undef */
return APP_VERSION;
}

View file

@ -0,0 +1,47 @@
/**
* Returns the lowercase file extension (including dot) of a filename.
* @param {string} name - The name of the file.
* @returns {string} The file extension, e.g., ".png"
*/
const formattedFilenameExt = (name) => {
const parts = typeof name === 'string' ? name.split('.') : [];
const ext = parts.length > 1 ? parts.pop() : '';
return ext ? `.${ext.toLowerCase()}` : '';
};
/**
* Checks whether a file meets the size and format requirements.
* @param {{ maxSize: number, supportedFormats: string[] }} requirements
* @param {File} file
* @returns {boolean}
*/
const areRequirementsFulfilled = (requirements, file) => {
return (
file.size <= requirements.maxSize &&
requirements.supportedFormats.includes(formattedFilenameExt(file.name))
);
};
/**
* Filters a list of files into accepted and rejected based on requirements.
* @param {FileList | File[]} files - The list of files to filter.
* @param {{ maxSize: number, supportedFormats: string[] }} requirements
* @returns {{ accepted: File[], rejected: File[] }}
*/
export function filterFiles(files, requirements) {
/** @type {File[]} */
const accepted = [];
/** @type {File[]} */
const rejected = [];
for (const file of Array.from(files)) {
if (file && areRequirementsFulfilled(requirements, file)) {
accepted.push(file);
} else {
rejected.push(file);
}
}
return { accepted, rejected };
}

25
src/lib/utils/rgbToHex.js Normal file
View file

@ -0,0 +1,25 @@
/**
* Converts a single color component to a 2-digit hexadecimal string.
* @param {number} c - A number between 0 and 255.
* @returns {string} The 2-digit hex representation.
*/
const componentToHex = (c) => {
const hex = c.toString(16);
return hex.length === 1 ? '0' + hex : hex;
};
/**
* Converts an RGB object to a hexadecimal color string.
* @param {{ r: number, g: number, b: number }} color - An object with r, g, and b properties (0255).
* @returns {string} The hex color string (e.g., "#ffcc00").
*/
const rgbToHex = (color) => {
return (
'#' +
componentToHex(color.r) +
componentToHex(color.g) +
componentToHex(color.b)
);
};
export { rgbToHex };

View file

@ -0,0 +1,27 @@
/**
* Shades a hex color by a given percentage.
* Positive values lighten the color, negative values darken it.
*
* @param {string} color - A 7-character hex color string (e.g. "#ffcc00").
* @param {number} percent - A percentage from -100 to 100 to adjust brightness.
* @returns {string} - The adjusted hex color string.
*/
function shadeColor(color, percent) {
const num = parseInt(color.slice(1), 16);
const amt = Math.round(2.55 * percent);
let r = (num >> 16) + amt;
let g = ((num >> 8) & 0xff) + amt;
let b = (num & 0xff) + amt;
// Clamp each component between 0 and 255
r = Math.min(255, Math.max(0, r));
g = Math.min(255, Math.max(0, g));
b = Math.min(255, Math.max(0, b));
const shaded = (1 << 24) + (r << 16) + (g << 8) + b;
return `#${shaded.toString(16).slice(1)}`;
}
export { shadeColor };

View file

@ -1,9 +0,0 @@
import { mount } from 'svelte';
import App from './App.svelte';
import "./app.css";
const app = mount(App, {
target: document.getElementById('app'),
});
export default app;

17
src/routes/+layout.js Normal file
View file

@ -0,0 +1,17 @@
import { setLocale, setRoute } from '$lib/translations';
/**
* @typedef {Object} LayoutData
* @property {string} route
* @property {string} language
*/
/** @type {import('@sveltejs/kit').Load<LayoutData>} */
export const load = async ({ data }) => {
const { route, language } = data ?? {};
if (route) await setRoute(route);
if (language) await setLocale(language);
return data ?? {};
};

View file

@ -0,0 +1,54 @@
import { parse } from 'accept-language-parser';
import { loadTranslations, setLocale, setRoute } from '$lib/translations';
import { SUPPORTED_LOCALES } from '$lib/translations';
/**
* A set of all supported locale codes, used to validate and match against
* user preferences from cookies or Accept-Language headers. We're using a
* Set for better performance in lookup.
*
* Example values: "en-US", "pt-BR"
* @type {Set<string>}
*/
const SUPPORTED_LOCALE_SET = new Set(Object.values(SUPPORTED_LOCALES));
/**
* Returns a valid locale from cookies, or null if not valid/found.
* @param {{ get: (cookies: string) => any; }} cookies
*/
function localeFromCookies(cookies) {
const locale = cookies.get('locale');
return locale && SUPPORTED_LOCALE_SET.has(locale) ? locale : null;
}
/**
* Parses the Accept-Language header and returns the best matching locale.
* @param {string | null | undefined} header
*/
function localeFromHeader(header) {
if (!header) return null;
const parsedLanguages = parse(header);
for (const { code, region } of parsedLanguages) {
const locale = region ? `${code}-${region}` : code;
if (SUPPORTED_LOCALE_SET.has(locale)) {
return locale;
}
}
return null;
}
/** @type {import('@sveltejs/kit').ServerLoad}*/
export async function load({ url, request, cookies }) {
const cookieLocale = localeFromCookies(cookies);
const headerLocale = localeFromHeader(request.headers.get('accept-language'));
const language = cookieLocale || headerLocale || SUPPORTED_LOCALES.EN_US;
const route = url.pathname;
await loadTranslations(language, route);
setLocale(language);
setRoute(route);
return { language, route };
}

18
src/routes/+layout.svelte Normal file
View file

@ -0,0 +1,18 @@
<script>
import Header from '$lib/components/Header.svelte';
import Footer from '$lib/components/Footer.svelte';
</script>
<Header />
<main>
<slot />
</main>
<Footer />
<style>
main {
flex: 1; /* This pushes footer to bottom */
padding: 20px;
min-height: 90vh;
}
</style>

12
src/routes/+page.js Normal file
View file

@ -0,0 +1,12 @@
/** @type {import('./$types').PageLoad} */
export function load() {
return {
metadata: {
title: 'home.seo.title',
description: 'home.seo.description',
keywords: 'home.seo.keywords',
url: 'home.seo.url',
image: 'home.seo.image',
},
};
}

64
src/routes/+page.svelte Normal file
View file

@ -0,0 +1,64 @@
<script>
import Seo from '$lib/components/Seo.svelte';
import { t } from '$lib/translations';
/** @type {import('./$types').PageProps} */
let { data } = $props();
const metadata = data.metadata;
</script>
<Seo {...metadata} />
<div class="home-container">
<section aria-labelledby="main-title">
<h1 id="main-title">{$t('home.main.title')}</h1>
{@html $t('home.main.description')}
</section>
<section aria-labelledby="features-title">
<h2 id="features-title">{$t('home.features.title')}</h2>
{@html $t('home.features.list')}
</section>
<section aria-labelledby="how-to-use-title">
<h2 id="how-to-use-title">{$t('home.howtouse.title')}</h2>
{@html $t('home.howtouse.list')}
</section>
<section aria-labelledby="testimonials-title">
<h2 id="testimonials-title">{$t('home.testimonials.title')}</h2>
{@html $t('home.testimonials.description')}
</section>
<section aria-labelledby="donation-title">
<h2 id="donation-title">{$t('home.donation.title')}</h2>
{@html $t('home.donation.description')}
<p>
<a href="/donate" class="button">{$t('home.donation.cta')}</a>
{$t('home.donation.cta.description')}
</p>
</section>
<!--TODO: add video preview-->
<section aria-labelledby="cta-title">
<h2 id="cta-title">{$t('home.cta.title')}</h2>
<p>
<a href="/viewer" class="button">{$t('home.cta.cta')}</a>
{@html $t('home.cta.cta.description')}
</p>
</section>
</div>
<style>
.home-container {
margin: 0 auto;
width: 70%;
}
@media (max-width: 768px) {
.home-container {
width: 100%;
}
}
</style>

12
src/routes/about/+page.js Normal file
View file

@ -0,0 +1,12 @@
/** @type {import('./$types').PageLoad} */
export function load() {
return {
metadata: {
title: 'about.seo.title',
description: 'about.seo.description',
keywords: 'about.seo.keywords',
url: 'about.seo.url',
image: 'about.seo.image',
},
};
}

View file

@ -0,0 +1,36 @@
<script>
import { t } from '$lib/translations';
import Seo from '$lib/components/Seo.svelte';
/** @type {import('./$types').PageProps} */
let { data } = $props();
const metadata = data.metadata;
</script>
<Seo {...metadata} />
<section aria-labelledby="about-heading">
<h1 id="about-heading">{$t('about.title')}</h1>
{@html $t('about.content')}
</section>
<style>
section {
width: 70%;
margin: 0 auto;
}
h1 {
padding: 0;
margin-bottom: 7px;
}
@media (max-width: 768px) {
section {
width: 100%;
}
}
</style>

View file

@ -0,0 +1,12 @@
/** @type {import('./$types').PageLoad} */
export function load() {
return {
metadata: {
title: 'donate.seo.title',
description: 'donate.seo.description',
keywords: 'donate.seo.keywords',
url: 'donate.seo.url',
image: 'donate.seo.image',
},
};
}

View file

@ -0,0 +1,186 @@
<script>
import { t } from '$lib/translations';
import bitcoin from '$lib/assets/bitcoin.svg';
import monero from '$lib/assets/monero.svg';
import paypal from '$lib/assets/paypal.svg';
import Seo from '$lib/components/Seo.svelte';
/** @type {import('./$types').PageProps} */
let { data } = $props();
const metadata = data.metadata;
const BTC_ADDRESS = 'bc1qpc4lpyr6stxrrg3u0k4clp4crlt6z4j6q845rq';
const XMR_ADDRESS =
'8A9iyTskiBh6f6GDUwnUJaYhAW13gNjDYaZYJBftX434D3XLrcGBko4a8kC4pLSfiuJAoSJ7e8rwP8W4StsVypftCp6FGwm';
let copyStatus = {
btc: '',
xmr: '',
};
/**
* @param {string} text
* @param {'btc' | 'xmr'} key
*/
async function copyToClipboard(text, key) {
try {
await navigator.clipboard.writeText(text);
copyStatus[key] = 'donate.copied';
} catch (err) {
console.error('Copy failed:', err);
copyStatus[key] = 'donate.copy.failed';
}
setTimeout(() => (copyStatus[key] = ''), 2000);
}
</script>
<Seo {...metadata} />
<section aria-labelledby="donate-title" class="donate-container">
<header>
<h1 id="donate-title">{$t('donate.title')}</h1>
<p class="donate-subtitle">{$t('donate.subtitle')}</p>
<p>{@html $t('donate.description')}</p>
</header>
<h2 id="ways-title">{$t('donate.ways')}</h2>
<div class="donation-options" aria-labelledby="ways-title">
<article class="donation-method" aria-labelledby="btc-label">
<img src={bitcoin} alt="Bitcoin QR code" width="200" height="200" />
<h3 id="btc-label">Bitcoin</h3>
<p>{$t('donate.bitcoin.description')}</p>
<button
aria-label="Copy Bitcoin address"
on:click={() => copyToClipboard(BTC_ADDRESS, 'btc')}
>
{#if copyStatus.btc}
{$t(copyStatus.btc)}
{:else}
{$t('donate.copy')}
{/if}
</button>
</article>
<article class="donation-method" aria-labelledby="xmr-label">
<img src={monero} alt="Monero QR code" width="200" height="200" />
<h3 id="xmr-label">Monero</h3>
<p>{$t('donate.monero.description')}</p>
<button
aria-label="Copy Monero address"
on:click={() => copyToClipboard(XMR_ADDRESS, 'xmr')}
>
{#if copyStatus.xmr}
{$t(copyStatus.xmr)}
{:else}
{$t('donate.copy')}
{/if}
</button>
</article>
<article class="donation-method" aria-labelledby="paypal-label">
<img src={paypal} alt="PayPal" width="200" height="200" />
<h3 id="paypal-label">PayPal</h3>
<p>{$t('donate.paypal.description')}</p>
<a
class="donation-link"
href="https://www.paypal.com/donate/?business=leo@leomurca.xyz&currency_code=USD"
target="_blank"
rel="noopener noreferrer"
aria-label="PayPal donation link"
>
{$t('donate.paypal.link')}
</a>
</article>
</div>
</section>
<style>
.donate-container {
width: 70%;
margin: 0 auto;
}
h1 {
margin-bottom: 7px;
}
.donate-subtitle {
font-weight: bold;
color: #06345f;
margin: 0;
}
.donation-options {
display: flex;
gap: 2rem;
margin-top: 2rem;
}
.donation-method {
display: flex;
flex-direction: column;
align-items: center;
width: 30rem;
}
.donation-method p {
margin-top: 0.5rem;
text-align: center;
display: block;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
button,
.donation-link {
font-size: 14px;
background-color: #05345f;
font-weight: bold;
color: white;
padding: 10px;
border: none;
border-radius: 10px;
width: 200px;
height: 45px;
text-align: center;
display: flex;
align-items: center;
justify-content: center;
margin-top: 1rem;
transition: background-color 0.2s ease;
}
button:hover,
.donation-link:hover {
cursor: pointer;
background-color: black;
color: white;
}
@media (max-width: 768px) {
.donate-container {
width: 100%;
}
.donation-options {
flex-direction: column;
align-items: center;
}
.donation-method {
width: 100%;
}
button,
.donation-link {
width: 100%;
height: 55px;
font-size: 1em;
}
}
</style>

View file

@ -0,0 +1,12 @@
/** @type {import('./$types').PageLoad} */
export function load() {
return {
metadata: {
title: 'privacy.policy.seo.title',
description: 'privacy.policy.seo.description',
keywords: 'privacy.policy.seo.keywords',
url: 'privacy.policy.seo.url',
image: 'privacy.policy.seo.image',
},
};
}

View file

@ -0,0 +1,34 @@
<script>
import { t } from '$lib/translations';
import Seo from '$lib/components/Seo.svelte';
/** @type {import('./$types').PageProps} */
let { data } = $props();
const metadata = data.metadata;
</script>
<Seo {...metadata} />
<section aria-labelledby="privacy-policy-heading">
<h1 id="privacy-policy-heading">{$t('privacy.policy.title')}</h1>
<p><em>{$t('privacy.policy.last.update')}</em></p>
{@html $t('privacy.policy.content')}
</section>
<style>
section {
width: 70%;
margin: 0 auto;
}
h2 {
font-size: 17px;
}
@media (max-width: 768px) {
section {
width: 100%;
}
}
</style>

View file

@ -0,0 +1,41 @@
export async function GET() {
const baseUrl = 'https://embroideryviewer.xyz';
const pages = [
'',
'about',
'donate',
'terms-of-service',
'privacy-policy',
'viewer',
];
const urls = pages
.map(
(page) => `
<url>
<loc>${baseUrl}/${page}</loc>
<changefreq>weekly</changefreq>
<priority>0.8</priority>
</url>`,
)
.join('');
const xml = `<?xml version="1.0" encoding="UTF-8" ?>
<urlset
xmlns="https://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:xhtml="https://www.w3.org/1999/xhtml"
xmlns:mobile="https://www.google.com/schemas/sitemap-mobile/1.0"
xmlns:news="https://www.google.com/schemas/sitemap-news/0.9"
xmlns:image="https://www.google.com/schemas/sitemap-image/1.1"
xmlns:video="https://www.google.com/schemas/sitemap-video/1.1"
>
${urls}
</urlset>`.trim();
return new Response(xml, {
headers: {
'Content-Type': 'application/xml',
},
});
}

View file

@ -0,0 +1,12 @@
/** @type {import('./$types').PageLoad} */
export function load() {
return {
metadata: {
title: 'terms.of.service.seo.title',
description: 'terms.of.service.seo.description',
keywords: 'terms.of.service.seo.keywords',
url: 'terms.of.service.seo.url',
image: 'terms.of.service.seo.image',
},
};
}

Some files were not shown because too many files have changed in this diff Show more