- Feb 2013
-//
-// A unique way to work with a binary file in the browser
-// http://github.com/jDataView/jDataView
-// http://jDataView.github.io/
-
-var compatibility = {
- // NodeJS Buffer in v0.5.5 and newer
- 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,
- PixelData:
- "CanvasPixelArray" in globalThis &&
- "ImageData" in globalThis &&
- "document" in globalThis,
-};
-
-var createPixelData = function (byteLength, buffer) {
- var data = createPixelData.context2d.createImageData(
- (byteLength + 3) / 4,
- 1
- ).data;
- data.byteLength = byteLength;
- if (buffer !== undefined) {
- for (var i = 0; i < byteLength; i++) {
- data[i] = buffer[i];
- }
- }
- return data;
-};
-createPixelData.context2d = document.createElement("canvas").getContext("2d");
-
-var dataTypes = {
- Int8: 1,
- Int16: 2,
- Int32: 4,
- Uint8: 1,
- Uint16: 2,
- Uint32: 4,
- Float32: 4,
- Float64: 8,
-};
-
-var nodeNaming = {
- Int8: "Int8",
- Int16: "Int16",
- Int32: "Int32",
- Uint8: "UInt8",
- Uint16: "UInt16",
- Uint32: "UInt32",
- Float32: "Float",
- Float64: "Double",
-};
-
-function arrayFrom(arrayLike, forceCopy) {
- return !forceCopy && arrayLike instanceof Array
- ? arrayLike
- : Array.prototype.slice.call(arrayLike);
-}
-
-function defined(value, defaultValue) {
- return value !== undefined ? value : defaultValue;
-}
-
-export function jDataView(buffer, byteOffset, byteLength, littleEndian) {
- /* jshint validthis:true */
-
- if (buffer instanceof jDataView) {
- var result = buffer.slice(byteOffset, byteOffset + byteLength);
- result._littleEndian = defined(littleEndian, result._littleEndian);
- return result;
- }
-
- if (!(this instanceof jDataView)) {
- return new jDataView(buffer, byteOffset, byteLength, littleEndian);
- }
-
- this.buffer = buffer = jDataView.wrapBuffer(buffer);
-
- // Check parameters and existing functionnalities
- this._isArrayBuffer =
- compatibility.ArrayBuffer && buffer instanceof ArrayBuffer;
- this._isPixelData =
- compatibility.PixelData && buffer instanceof CanvasPixelArray;
- this._isDataView = compatibility.DataView && this._isArrayBuffer;
- this._isNodeBuffer = compatibility.NodeBuffer && buffer instanceof Buffer;
-
- // Handle Type Errors
- if (
- !this._isNodeBuffer &&
- !this._isArrayBuffer &&
- !this._isPixelData &&
- !(buffer instanceof Array)
- ) {
- throw new TypeError("jDataView buffer has an incompatible type");
- }
-
- // Default Values
- this._littleEndian = !!littleEndian;
-
- var bufferLength = "byteLength" in buffer ? buffer.byteLength : buffer.length;
- this.byteOffset = byteOffset = defined(byteOffset, 0);
- this.byteLength = byteLength = defined(byteLength, bufferLength - byteOffset);
-
- if (!this._isDataView) {
- this._checkBounds(byteOffset, byteLength, bufferLength);
- } else {
- this._view = new DataView(buffer, byteOffset, byteLength);
- }
-
- // Create uniform methods (action wrappers) for the following data types
-
- this._engineAction = this._isDataView
- ? this._dataViewAction
- : this._isNodeBuffer
- ? this._nodeBufferAction
- : this._isArrayBuffer
- ? this._arrayBufferAction
- : this._arrayAction;
-}
-
-function getCharCodes(string) {
- if (compatibility.NodeBuffer) {
- return new Buffer(string, "binary");
- }
-
- var Type = compatibility.ArrayBuffer ? Uint8Array : Array,
- codes = new Type(string.length);
-
- for (var i = 0, length = string.length; i < length; i++) {
- codes[i] = string.charCodeAt(i) & 0xff;
- }
- return codes;
-}
-
-// 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":
- if (compatibility.NodeBuffer) {
- buffer = new Buffer(buffer);
- buffer.fill(0);
- } else if (compatibility.ArrayBuffer) {
- buffer = new Uint8Array(buffer).buffer;
- } else if (compatibility.PixelData) {
- buffer = createPixelData(buffer);
- } else {
- buffer = new Array(buffer);
- for (var i = 0; i < buffer.length; i++) {
- buffer[i] = 0;
- }
- }
- return buffer;
-
- case "string":
- buffer = getCharCodes(buffer);
- /* falls through */
- default:
- if (
- "length" in buffer &&
- !(
- (compatibility.NodeBuffer && buffer instanceof Buffer) ||
- (compatibility.ArrayBuffer && buffer instanceof ArrayBuffer) ||
- (compatibility.PixelData && buffer instanceof CanvasPixelArray)
- )
- ) {
- if (compatibility.NodeBuffer) {
- buffer = new Buffer(buffer);
- } else if (compatibility.ArrayBuffer) {
- if (!(buffer instanceof ArrayBuffer)) {
- buffer = new Uint8Array(buffer).buffer;
- // bug in Node.js <= 0.8:
- if (!(buffer instanceof ArrayBuffer)) {
- buffer = new Uint8Array(arrayFrom(buffer, true)).buffer;
- }
- }
- } else if (compatibility.PixelData) {
- buffer = createPixelData(buffer.length, buffer);
- } else {
- buffer = arrayFrom(buffer);
- }
- }
- return buffer;
- }
-};
-
-function pow2(n) {
- return n >= 0 && n < 31 ? 1 << n : pow2[n] || (pow2[n] = Math.pow(2, n));
-}
-
-// left for backward compatibility
-jDataView.createBuffer = function () {
- return jDataView.wrapBuffer(arguments);
-};
-
-function Uint64(lo, hi) {
- this.lo = lo;
- this.hi = hi;
-}
-
-jDataView.Uint64 = Uint64;
-
-Uint64.prototype = {
- valueOf: function () {
- return this.lo + pow2(32) * this.hi;
- },
-
- toString: function () {
- return Number.prototype.toString.apply(this.valueOf(), arguments);
- },
-};
-
-Uint64.fromNumber = function (number) {
- var hi = Math.floor(number / pow2(32)),
- lo = number - hi * pow2(32);
-
- return new Uint64(lo, hi);
-};
-
-function Int64(lo, hi) {
- Uint64.apply(this, arguments);
-}
-
-jDataView.Int64 = Int64;
-
-Int64.prototype =
- "create" in Object ? Object.create(Uint64.prototype) : new Uint64();
-
-Int64.prototype.valueOf = function () {
- if (this.hi < pow2(31)) {
- return Uint64.prototype.valueOf.apply(this, arguments);
- }
- return -(pow2(32) - this.lo + pow2(32) * (pow2(32) - 1 - this.hi));
-};
-
-Int64.fromNumber = function (number) {
- var lo, hi;
- if (number >= 0) {
- var unsigned = Uint64.fromNumber(number);
- lo = unsigned.lo;
- hi = unsigned.hi;
- } else {
- hi = Math.floor(number / pow2(32));
- lo = number - hi * pow2(32);
- hi += pow2(32);
- }
- return new Int64(lo, hi);
-};
-
-jDataView.prototype = {
- _offset: 0,
- _bitOffset: 0,
-
- compatibility: compatibility,
-
- _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 byteLength !== "number") {
- throw new TypeError("Size is not a number.");
- }
- if (byteLength < 0) {
- throw new RangeError("Length is negative.");
- }
- if (
- byteOffset < 0 ||
- byteOffset + byteLength > defined(maxLength, this.byteLength)
- ) {
- throw new RangeError("Offsets are out of bounds.");
- }
- },
-
- _action: function (type, isReadAction, byteOffset, littleEndian, value) {
- return this._engineAction(
- type,
- isReadAction,
- defined(byteOffset, this._offset),
- defined(littleEndian, this._littleEndian),
- value
- );
- },
-
- _dataViewAction: function (
- type,
- isReadAction,
- byteOffset,
- littleEndian,
- 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);
- },
-
- _nodeBufferAction: function (
- type,
- isReadAction,
- byteOffset,
- littleEndian,
- value
- ) {
- // Move the internal offset forward
- this._offset = byteOffset + dataTypes[type];
- var nodeName =
- nodeNaming[type] +
- (type === "Int8" || type === "Uint8" ? "" : littleEndian ? "LE" : "BE");
- byteOffset += this.byteOffset;
- return isReadAction
- ? this.buffer["read" + nodeName](byteOffset)
- : this.buffer["write" + nodeName](value, byteOffset);
- },
-
- _arrayBufferAction: function (
- type,
- isReadAction,
- byteOffset,
- littleEndian,
- value
- ) {
- var size = dataTypes[type],
- TypedArray = globalThis[type + "Array"],
- typedArray;
-
- littleEndian = defined(littleEndian, this._littleEndian);
-
- // ArrayBuffer: we use a typed array of size 1 from original buffer if alignment is good and from slice when it's not
- if (
- size === 1 ||
- ((this.byteOffset + byteOffset) % size === 0 && littleEndian)
- ) {
- typedArray = new TypedArray(this.buffer, this.byteOffset + byteOffset, 1);
- this._offset = byteOffset + size;
- return isReadAction ? typedArray[0] : (typedArray[0] = value);
- } else {
- var bytes = new Uint8Array(
- isReadAction
- ? this.getBytes(size, byteOffset, littleEndian, true)
- : size
- );
- typedArray = new TypedArray(bytes.buffer, 0, 1);
-
- if (isReadAction) {
- return typedArray[0];
- } else {
- typedArray[0] = value;
- this._setBytes(byteOffset, bytes, littleEndian);
- }
- }
- },
-
- _arrayAction: function (type, isReadAction, byteOffset, littleEndian, value) {
- return isReadAction
- ? this["_get" + type](byteOffset, littleEndian)
- : this["_set" + type](byteOffset, value, littleEndian);
- },
-
- // Helpers
-
- _getBytes: function (length, byteOffset, littleEndian) {
- littleEndian = defined(littleEndian, this._littleEndian);
- byteOffset = defined(byteOffset, this._offset);
- length = defined(length, this.byteLength - byteOffset);
-
- this._checkBounds(byteOffset, length);
-
- byteOffset += this.byteOffset;
-
- this._offset = byteOffset - this.byteOffset + length;
-
- var result = this._isArrayBuffer
- ? new Uint8Array(this.buffer, byteOffset, length)
- : (this.buffer.slice || Array.prototype.slice).call(
- this.buffer,
- byteOffset,
- byteOffset + length
- );
-
- return littleEndian || length <= 1 ? result : arrayFrom(result).reverse();
- },
-
- // wrapper for external calls (do not return inner buffer directly to prevent it's modifying)
- getBytes: function (length, byteOffset, littleEndian, toArray) {
- var result = this._getBytes(
- length,
- byteOffset,
- defined(littleEndian, true)
- );
- return toArray ? arrayFrom(result) : result;
- },
-
- _setBytes: function (byteOffset, bytes, littleEndian) {
- var length = bytes.length;
-
- // needed for Opera
- if (length === 0) {
- return;
- }
-
- littleEndian = defined(littleEndian, this._littleEndian);
- byteOffset = defined(byteOffset, this._offset);
-
- this._checkBounds(byteOffset, length);
-
- if (!littleEndian && length > 1) {
- bytes = arrayFrom(bytes, true).reverse();
- }
-
- byteOffset += this.byteOffset;
-
- if (this._isArrayBuffer) {
- new Uint8Array(this.buffer, byteOffset, length).set(bytes);
- } else {
- if (this._isNodeBuffer) {
- new Buffer(bytes).copy(this.buffer, byteOffset);
- } else {
- for (var i = 0; i < length; i++) {
- this.buffer[byteOffset + i] = bytes[i];
- }
- }
- }
-
- this._offset = byteOffset - this.byteOffset + length;
- },
-
- setBytes: function (byteOffset, bytes, littleEndian) {
- this._setBytes(byteOffset, bytes, defined(littleEndian, true));
- },
-
- getString: function (byteLength, byteOffset, encoding) {
- if (this._isNodeBuffer) {
- byteOffset = defined(byteOffset, this._offset);
- byteLength = defined(byteLength, this.byteLength - byteOffset);
-
- this._checkBounds(byteOffset, byteLength);
-
- this._offset = byteOffset + byteLength;
- return this.buffer.toString(
- encoding || "binary",
- this.byteOffset + byteOffset,
- this.byteOffset + this._offset
- );
- }
- var bytes = this._getBytes(byteLength, byteOffset, true),
- string = "";
- byteLength = bytes.length;
- for (var i = 0; i < byteLength; i++) {
- string += String.fromCharCode(bytes[i]);
- }
- if (encoding === "utf8") {
- string = decodeURIComponent(escape(string));
- }
- return string;
- },
-
- setString: function (byteOffset, subString, encoding) {
- if (this._isNodeBuffer) {
- byteOffset = defined(byteOffset, this._offset);
- this._checkBounds(byteOffset, subString.length);
- this._offset =
- byteOffset +
- this.buffer.write(
- subString,
- this.byteOffset + byteOffset,
- encoding || "binary"
- );
- return;
- }
- if (encoding === "utf8") {
- subString = unescape(encodeURIComponent(subString));
- }
- this._setBytes(byteOffset, getCharCodes(subString), true);
- },
-
- getChar: function (byteOffset) {
- return this.getString(1, byteOffset);
- },
-
- setChar: function (byteOffset, character) {
- this.setString(byteOffset, character);
- },
-
- tell: function () {
- return this._offset;
- },
-
- seek: function (byteOffset) {
- this._checkBounds(byteOffset, 0);
- /* jshint boss: true */
- return (this._offset = byteOffset);
- },
-
- skip: function (byteLength) {
- return this.seek(this._offset + byteLength);
- },
-
- slice: function (start, end, forceCopy) {
- function normalizeOffset(offset, byteLength) {
- return offset < 0 ? offset + byteLength : offset;
- }
-
- start = normalizeOffset(start, this.byteLength);
- end = normalizeOffset(defined(end, this.byteLength), this.byteLength);
-
- return forceCopy
- ? new jDataView(
- this.getBytes(end - start, start, true, true),
- undefined,
- undefined,
- this._littleEndian
- )
- : new jDataView(
- this.buffer,
- this.byteOffset + start,
- end - start,
- this._littleEndian
- );
- },
-
- alignBy: function (byteCount) {
- this._bitOffset = 0;
- if (defined(byteCount, 1) !== 1) {
- return this.skip(byteCount - (this._offset % byteCount || byteCount));
- } else {
- return this._offset;
- }
- },
-
- // Compatibility functions
-
- _getFloat64: function (byteOffset, littleEndian) {
- var b = this._getBytes(8, byteOffset, littleEndian),
- sign = 1 - 2 * (b[7] >> 7),
- exponent = ((((b[7] << 1) & 0xff) << 3) | (b[6] >> 4)) - ((1 << 10) - 1),
- // Binary operators such as | and << operate on 32 bit values, using + and Math.pow(2) instead
- mantissa =
- (b[6] & 0x0f) * pow2(48) +
- b[5] * pow2(40) +
- b[4] * pow2(32) +
- b[3] * pow2(24) +
- b[2] * pow2(16) +
- b[1] * pow2(8) +
- b[0];
-
- if (exponent === 1024) {
- if (mantissa !== 0) {
- return NaN;
- } else {
- return sign * Infinity;
- }
- }
-
- if (exponent === -1023) {
- // Denormalized
- return sign * mantissa * pow2(-1022 - 52);
- }
-
- return sign * (1 + mantissa * pow2(-52)) * pow2(exponent);
- },
-
- _getFloat32: function (byteOffset, littleEndian) {
- var b = this._getBytes(4, byteOffset, littleEndian),
- sign = 1 - 2 * (b[3] >> 7),
- exponent = (((b[3] << 1) & 0xff) | (b[2] >> 7)) - 127,
- mantissa = ((b[2] & 0x7f) << 16) | (b[1] << 8) | b[0];
-
- if (exponent === 128) {
- if (mantissa !== 0) {
- return NaN;
- } else {
- return sign * Infinity;
- }
- }
-
- if (exponent === -127) {
- // Denormalized
- return sign * mantissa * pow2(-126 - 23);
- }
-
- return sign * (1 + mantissa * pow2(-23)) * pow2(exponent);
- },
-
- _get64: function (Type, byteOffset, littleEndian) {
- littleEndian = defined(littleEndian, this._littleEndian);
- byteOffset = defined(byteOffset, this._offset);
-
- var parts = littleEndian ? [0, 4] : [4, 0];
-
- for (var i = 0; i < 2; i++) {
- parts[i] = this.getUint32(byteOffset + parts[i], littleEndian);
- }
-
- this._offset = byteOffset + 8;
-
- return new Type(parts[0], parts[1]);
- },
-
- getInt64: function (byteOffset, littleEndian) {
- return this._get64(Int64, byteOffset, littleEndian);
- },
-
- getUint64: function (byteOffset, littleEndian) {
- return this._get64(Uint64, byteOffset, littleEndian);
- },
-
- _getInt32: function (byteOffset, littleEndian) {
- var b = this._getBytes(4, byteOffset, littleEndian);
- return (b[3] << 24) | (b[2] << 16) | (b[1] << 8) | b[0];
- },
-
- _getUint32: function (byteOffset, littleEndian) {
- return this._getInt32(byteOffset, littleEndian) >>> 0;
- },
-
- _getInt16: function (byteOffset, littleEndian) {
- return (this._getUint16(byteOffset, littleEndian) << 16) >> 16;
- },
-
- _getUint16: function (byteOffset, littleEndian) {
- var b = this._getBytes(2, byteOffset, littleEndian);
- return (b[1] << 8) | b[0];
- },
-
- _getInt8: function (byteOffset) {
- return (this._getUint8(byteOffset) << 24) >> 24;
- },
-
- _getUint8: function (byteOffset) {
- return this._getBytes(1, byteOffset)[0];
- },
-
- _getBitRangeData: function (bitLength, byteOffset) {
- var startBit = (defined(byteOffset, this._offset) << 3) + this._bitOffset,
- endBit = startBit + bitLength,
- start = startBit >>> 3,
- end = (endBit + 7) >>> 3,
- b = this._getBytes(end - start, start, true),
- wideValue = 0;
-
- /* jshint boss: true */
- if ((this._bitOffset = endBit & 7)) {
- this._bitOffset -= 8;
- }
-
- for (var i = 0, length = b.length; i < length; i++) {
- wideValue = (wideValue << 8) | b[i];
- }
-
- return {
- start: start,
- bytes: b,
- wideValue: wideValue,
- };
- },
-
- getSigned: function (bitLength, byteOffset) {
- var shift = 32 - bitLength;
- return (this.getUnsigned(bitLength, byteOffset) << shift) >> shift;
- },
-
- getUnsigned: function (bitLength, byteOffset) {
- var value =
- this._getBitRangeData(bitLength, byteOffset).wideValue >>>
- -this._bitOffset;
- return bitLength < 32 ? value & ~(-1 << bitLength) : value;
- },
-
- _setBinaryFloat: function (
- byteOffset,
- value,
- mantSize,
- expSize,
- littleEndian
- ) {
- var signBit = value < 0 ? 1 : 0,
- exponent,
- mantissa,
- eMax = ~(-1 << (expSize - 1)),
- eMin = 1 - eMax;
-
- if (value < 0) {
- value = -value;
- }
-
- if (value === 0) {
- exponent = 0;
- mantissa = 0;
- } else if (isNaN(value)) {
- exponent = 2 * eMax + 1;
- mantissa = 1;
- } else if (value === Infinity) {
- exponent = 2 * eMax + 1;
- mantissa = 0;
- } else {
- exponent = Math.floor(Math.log(value) / Math.LN2);
- if (exponent >= eMin && exponent <= eMax) {
- mantissa = Math.floor((value * pow2(-exponent) - 1) * pow2(mantSize));
- exponent += eMax;
- } else {
- mantissa = Math.floor(value / pow2(eMin - mantSize));
- exponent = 0;
- }
- }
-
- var b = [];
- while (mantSize >= 8) {
- b.push(mantissa % 256);
- mantissa = Math.floor(mantissa / 256);
- mantSize -= 8;
- }
- exponent = (exponent << mantSize) | mantissa;
- expSize += mantSize;
- while (expSize >= 8) {
- b.push(exponent & 0xff);
- exponent >>>= 8;
- expSize -= 8;
- }
- b.push((signBit << expSize) | exponent);
-
- this._setBytes(byteOffset, b, littleEndian);
- },
-
- _setFloat32: function (byteOffset, value, littleEndian) {
- this._setBinaryFloat(byteOffset, value, 23, 8, littleEndian);
- },
-
- _setFloat64: function (byteOffset, value, littleEndian) {
- this._setBinaryFloat(byteOffset, value, 52, 11, littleEndian);
- },
-
- _set64: function (Type, byteOffset, value, littleEndian) {
- if (!(value instanceof Type)) {
- value = Type.fromNumber(value);
- }
-
- littleEndian = defined(littleEndian, this._littleEndian);
- byteOffset = defined(byteOffset, this._offset);
-
- var parts = littleEndian ? { lo: 0, hi: 4 } : { lo: 4, hi: 0 };
-
- for (var partName in parts) {
- this.setUint32(
- byteOffset + parts[partName],
- value[partName],
- littleEndian
- );
- }
-
- this._offset = byteOffset + 8;
- },
-
- setInt64: function (byteOffset, value, littleEndian) {
- this._set64(Int64, byteOffset, value, littleEndian);
- },
-
- setUint64: function (byteOffset, value, littleEndian) {
- this._set64(Uint64, byteOffset, value, littleEndian);
- },
-
- _setUint32: function (byteOffset, value, littleEndian) {
- this._setBytes(
- byteOffset,
- [value & 0xff, (value >>> 8) & 0xff, (value >>> 16) & 0xff, value >>> 24],
- littleEndian
- );
- },
-
- _setUint16: function (byteOffset, value, littleEndian) {
- this._setBytes(
- byteOffset,
- [value & 0xff, (value >>> 8) & 0xff],
- littleEndian
- );
- },
-
- _setUint8: function (byteOffset, value) {
- this._setBytes(byteOffset, [value & 0xff]);
- },
-
- setUnsigned: function (byteOffset, value, bitLength) {
- var data = this._getBitRangeData(bitLength, byteOffset),
- wideValue = data.wideValue,
- b = data.bytes;
-
- wideValue &= ~(~(-1 << bitLength) << -this._bitOffset); // clearing bit range before binary "or"
- wideValue |=
- (bitLength < 32 ? value & ~(-1 << bitLength) : value) << -this._bitOffset; // setting bits
-
- for (var i = b.length - 1; i >= 0; i--) {
- b[i] = wideValue & 0xff;
- wideValue >>>= 8;
- }
-
- this._setBytes(data.start, b, true);
- },
-};
-
-var proto = jDataView.prototype;
-
-for (var type in dataTypes) {
- (function (type) {
- proto["get" + type] = function (byteOffset, littleEndian) {
- return this._action(type, true, byteOffset, littleEndian);
- };
- proto["set" + type] = function (byteOffset, value, littleEndian) {
- this._action(type, false, byteOffset, littleEndian, value);
- };
- })(type);
-}
-
-proto._setInt32 = proto._setUint32;
-proto._setInt16 = proto._setUint16;
-proto._setInt8 = proto._setUint8;
-proto.setSigned = proto.setUnsigned;
-
-for (var method in proto) {
- if (method.slice(0, 3) === "set") {
- (function (type) {
- proto["write" + type] = function () {
- Array.prototype.unshift.call(arguments, undefined);
- this["set" + type].apply(this, arguments);
- };
- })(method.slice(3));
- }
-}
-
-if (typeof module !== "undefined" && typeof module.exports === "object") {
- module.exports = jDataView;
-} else if (typeof define === "function" && define.amd) {
- define([], function () {
- return jDataView;
- });
-} else {
- var oldGlobalThis = globalThis.jDataView;
- (globalThis.jDataView = jDataView).noConflict = function () {
- globalThis.jDataView = oldGlobalThis;
- return this;
- };
-}
diff --git a/src/file-renderer/pattern.js b/src/file-renderer/pattern.js
deleted file mode 100644
index 7d73189..0000000
--- a/src/file-renderer/pattern.js
+++ /dev/null
@@ -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 += `
`;
- });
-};
-
-Pattern.prototype.drawStitchesCountTo = function (stitchesContainer, stitchesString) {
- stitchesContainer.innerHTML += `${stitchesString}: ${this.stitches.length}
`;
-};
-
-Pattern.prototype.drawSizeValuesTo = function (sizeContainer, dimensionsString) {
- sizeContainer.innerHTML += `${dimensionsString}: ${Math.round(
- this.right / 10
- )}mm x ${Math.round(this.bottom / 10)}mm
`;
-};
-
-export { Pattern, Color, stitchTypes };
diff --git a/src/format-readers/dst.js b/src/format-readers/dst.js
deleted file mode 100644
index 8da4fd9..0000000
--- a/src/format-readers/dst.js
+++ /dev/null
@@ -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();
-}
diff --git a/src/format-readers/exp.js b/src/format-readers/exp.js
deleted file mode 100644
index 58d29ae..0000000
--- a/src/format-readers/exp.js
+++ /dev/null
@@ -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();
-}
diff --git a/src/format-readers/index.js b/src/format-readers/index.js
deleted file mode 100644
index eeb157b..0000000
--- a/src/format-readers/index.js
+++ /dev/null
@@ -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 };
diff --git a/src/format-readers/jef.js b/src/format-readers/jef.js
deleted file mode 100644
index 047d006..0000000
--- a/src/format-readers/jef.js
+++ /dev/null
@@ -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;
\ No newline at end of file
diff --git a/src/format-readers/pec.js b/src/format-readers/pec.js
deleted file mode 100644
index 402e613..0000000
--- a/src/format-readers/pec.js
+++ /dev/null
@@ -1,13 +0,0 @@
-import { pecColors, pecReadStitches } from "./pes";
-
-export function pecRead(file, pattern) {
- let colorChanges, i;
- file.seek(0x38);
- colorChanges = file.getUint8();
- for (i = 0; i <= colorChanges; i++) {
- pattern.addColor(pecColors[file.getUint8() % 65]);
- }
- file.seek(0x21c);
- pecReadStitches(file, pattern);
- return true;
-}
diff --git a/src/format-readers/pes.js b/src/format-readers/pes.js
deleted file mode 100644
index 9e7b156..0000000
--- a/src/format-readers/pes.js
+++ /dev/null
@@ -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;
diff --git a/src/i18n/index.js b/src/i18n/index.js
deleted file mode 100644
index 9b358f3..0000000
--- a/src/i18n/index.js
+++ /dev/null
@@ -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)
-);
\ No newline at end of file
diff --git a/src/i18n/translations.js b/src/i18n/translations.js
deleted file mode 100644
index ff13bec..0000000
--- a/src/i18n/translations.js
+++ /dev/null
@@ -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": "✨Upload and preview your embroidery designs instantly – no software needed.
Embroidery Viewer is a free, browser-based tool that supports multiple embroidery file formats. View your designs quickly and securely, right in your browser.
",
- "home.features.title": "🚀 Features",
- "home.features.list": "📂 Supports Multiple Formats: DST, PES, JEF, EXP, VP3, and more ⚡ Quick Previews: See your embroidery files rendered as images 🧷 Multiple Files at Once: Upload several designs and view them side-by-side 🔒 No Upload to Server: Your files stay private – all processing happens locally ⬇️ Download as Image: Save each embroidery design preview as a PNG 💸 Fast & Free: No installations, no sign-ups – just open and use ",
- "home.howtouse.title": "📘 How to Use",
- "home.howtouse.list": "📁 Click the upload button or drag and drop your embroidery files into the drop area 🧵 Select one or more embroidery files ▶️ Click the “Render files” button to preview your designs 👀 Instantly view your designs right in your browser – it’s that simple ",
- "home.testimonials.title": "❤️ Loved by Hobbyists and Professionals",
- "home.testimonials.description": "Whether you're a hobbyist working on your next DIY project or a professional digitizer reviewing client files, Embroidery Viewer gives you a no-fuss, instant way to visualize your work.
",
- "home.donation.title": "💖 Help Keep It Free",
- "home.donation.description": "Embroidery Viewer is completely free for everyone to use.
If you find it useful and want to support ongoing development and hosting costs, please consider making a small donation.
",
- "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 Free Online Embroidery File Viewer .",
- "donate.title": "💖 Donate",
- "donate.subtitle": "Help support Embroidery Viewer and its development!",
- "donate.description": "⭐️ Embroidery Viewer 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": "Hi there! 👋
⭐️ Embroidery Viewer was born out of a simple need — helping someone I care about. 💖
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 she’s not a techie.
So, to make things easier for her (and others like her), I decided to build this web application.
Over the course of a few weeks, I created Embroidery Viewer — 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.
It’s not a super sophisticated tool, but it solves the problem it was meant to solve: making embroidery file previews accessible to everyone.
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.
Thanks for stopping by — and happy stitching! 🧵✨
",
- "privacy.policy.title": "🔐 Privacy Policy",
- "privacy.policy.last.update": "Last updated: May 9, 2025",
- "privacy.policy.content": "At Embroidery Viewer (embroideryviewer.xyz ), we respect your privacy and are committed to protecting any information you share while using our service.
1. Personal Information Embroidery Viewer does not 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.
2. File Uploads 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. No uploaded files are stored, saved, or shared.
Please avoid uploading any copyrighted or sensitive material unless you have permission to use it.
3. Analytics We use Umami 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.
Umami is a privacy-friendly, cookie-free analytics tool. It does not track users across sites, collect personal data, or use cookies. All data is aggregated and anonymized.
4. Cookies Embroidery Viewer does not use cookies or other tracking mechanisms in your browser.
5. Third-Party Services We do not use third-party advertising, embed external trackers, or share data with third parties.
6. Changes to This Policy We may update this Privacy Policy from time to time. All updates will be posted on this page with the updated date.
7. Contact If you have any questions about this Privacy Policy, you can reach us at leo@leomurca.xyz .
",
- "terms.of.service.title": "📝 Terms of Service",
- "terms.of.service.update": "May 9, 2025",
- "terms.of.service.content": "Welcome to Embroidery Viewer (embroideryviewer.xyz ). 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.
1. Description of Service 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.
2. Use of the Service 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.
You agree not to upload any files that are illegal, offensive, infringe on intellectual property rights, or contain malicious code.
3. File Processing 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.
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.
4. No Warranty 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.
5. Limitation of Liability 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.
6. Modifications to the Service 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.
7. Governing Law These Terms shall be governed by and interpreted in accordance with the laws of Brazil, without regard to its conflict of law principles.
8. Contact If you have any questions about these Terms of Service, feel free to contact us at leo@leomurca.xyz .
",
- "main.languageSwitch": "🇧🇷",
- "main.fileSize": "Max file size is {{fileSize}}MB .",
- "main.supportedFormats": "Accepted formats: {{supportedFormats}} .",
- "main.render": "Render files",
- "main.dropzone": "Choose files or drag and drop them here ",
- "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}} Leonardo Murça . 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": "✨Carregue e visualize seus desenhos de bordado instantaneamente – sem necessidade de software
Embroidery Viewer é 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.
",
- "home.features.title": "🚀 Funcionalidades",
- "home.features.list": "📂 Suporta vários formatos: DST, PES, JEF, EXP, VP3 e mais ⚡ Visualizações rápidas: Veja seus arquivos de bordado renderizados como imagens 🧷 Vários arquivos de uma só vez: Carregue vários designs e visualize-os lado a lado 🔒 Sem upload para o servidor: Seus arquivos permanecem privados – todo o processamento acontece localmente ⬇️ Baixar como imagem: Salve cada pré-visualização do desenho do bordado como um PNG 💸 Rápido e gratuito: Sem instalações, sem cadastros – basta abrir e usar ",
- "home.howtouse.title": "📘 Como usar",
- "home.howtouse.list": "📁 Clique no botão de upload ou arraste e solte seus arquivos de bordado na área de soltar 🧵 Selecione um ou mais arquivos de bordado ▶️ Clique no botão “Renderizar arquivos” para visualizar seus designs 👀 Visualize seus designs instantaneamente no seu navegador – é simples assim ",
- "home.testimonials.title": "❤️ Amado por Hobbyistas e Profissionais",
- "home.testimonials.description": "Seja você um amador trabalhando em seu próximo projeto \"faça você mesmo\" ou um digitalizador profissional revisando arquivos de clientes, o Embroidery Viewer oferece uma maneira fácil e instantânea de visualizar seu trabalho.
",
- "home.donation.title": "💖 Ajude a mantê-lo gratuito",
- "home.donation.description": "O Embroidery Viewer é totalmente gratuito para todos usarem.
Se você o achar útil e quiser apoiar o desenvolvimento contínuo e os custos de hospedagem, considere fazer uma pequena doação.
",
- "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 visualizador de arquivos de bordado online gratuito mais rápido.",
- "donate.title": "💖 Doe",
- "donate.subtitle": "Ajude a apoiar o Embroidery Viewer e seu desenvolvimento!",
- "donate.description": "⭐️ O Embroidery Viewer é 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": "Oi! 👋
⭐️ Embroidery Viewer nasceu de uma necessidade simples — ajudar alguém que eu amo. 💖
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.
Então, para facilitar a vida dela (e de outras pessoas como ela), decidi criar este aplicativo web.
Ao longo de algumas semanas, criei o Embroidery Viewer — 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.
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.
Se essa ferramenta também te ajudou, isso me deixa muito feliz! Pretendo continuar melhorando com base no feedback de usuários como você.
Obrigado por visitar — e bons bordados! 🧵✨
",
- "privacy.policy.title": "🔐 Política de Privacidade",
- "privacy.policy.last.update": "Última atualização: 9 de maio de 2025",
- "privacy.policy.content": "No Embroidery Viewer (embroideryviewer.xyz ), respeitamos sua privacidade e estamos comprometidos em proteger qualquer informação que você compartilhe ao usar nosso serviço.
1. Informações Pessoais O Embroidery Viewer não 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.
2. Envio de Arquivos 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. Nenhum arquivo enviado é armazenado, salvo ou compartilhado.
Evite enviar materiais sensíveis ou protegidos por direitos autorais, a menos que tenha permissão para usá-los.
3. Análises Utilizamos o Umami 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.
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.
4. Cookies O Embroidery Viewer não utiliza cookies ou outros mecanismos de rastreamento em seu navegador.
5. Serviços de Terceiros Não utilizamos publicidade de terceiros, nem incorporamos rastreadores externos, nem compartilhamos dados com terceiros.
6. Alterações nesta Política Podemos atualizar esta Política de Privacidade ocasionalmente. Todas as atualizações serão publicadas nesta página com a data de modificação.
7. Contato Se você tiver dúvidas sobre esta Política de Privacidade, entre em contato pelo e-mail leo@leomurca.xyz .
",
- "terms.of.service.title": "📝 Termos de Serviço",
- "terms.of.service.update": "Última atualização: 9 de maio de 2025",
- "terms.of.service.content": "Bem-vindo ao Embroidery Viewer (embroideryviewer.xyz ). 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.
1. Descrição do Serviço 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.
2. Uso do Serviço 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.
Você concorda em não enviar arquivos que sejam ilegais, ofensivos, infrinjam direitos de propriedade intelectual ou contenham código malicioso.
3. Processamento de Arquivos 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.
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.
4. Sem Garantia 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.
5. Limitação de Responsabilidade 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.
6. Modificações no Serviço 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.
7. Lei Aplicável 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.
8. Contato Se você tiver qualquer dúvida sobre estes Termos de Serviço, sinta-se à vontade para entrar em contato conosco pelo e-mail leo@leomurca.xyz .
",
- "main.title": "Carregar arquivos",
- "main.languageSwitch": "🇺🇸",
- "main.fileSize": "O tamanho máximo de cada arquivo é {{fileSize}}MB .",
- "main.supportedFormats": "Formatos aceitos: {{supportedFormats}} .",
- "main.render": "Renderizar arquivos",
- "main.dropzone": "Selecione arquivos ou arraste e solte-os aqui ",
- "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}} Leonardo Murça . Todos os direitos reservados.",
- "main.version": "🧵 Versão: {{version}}"
- },
- };
\ No newline at end of file
diff --git a/src/lib/MediaQuery.svelte b/src/lib/MediaQuery.svelte
deleted file mode 100644
index cfd20ec..0000000
--- a/src/lib/MediaQuery.svelte
+++ /dev/null
@@ -1,39 +0,0 @@
-
-
-
diff --git a/src/lib/components/CardList.svelte b/src/lib/components/CardList.svelte
deleted file mode 100644
index e701132..0000000
--- a/src/lib/components/CardList.svelte
+++ /dev/null
@@ -1,143 +0,0 @@
-
-
-{#if files.length !== 0}
-
- {#each Array.from(files) as file, i}
-
-
-
{file.name}
-
-
-
-
downloadCanvasAsImage(canvasRefs[i], file.name)}
- >
- {$t("main.download")}
-
-
- {canvasRefs[i] &&
- renderFileToCanvas(
- file,
- canvasRefs[i],
- errorMessageRef,
- colorRefs[i],
- stitchesRefs[i],
- sizeRefs[i],
- localizedStrings
- )}
- {/each}
-
-
-
-{/if}
-
-
diff --git a/src/lib/components/Dropzone.svelte b/src/lib/components/Dropzone.svelte
deleted file mode 100644
index 86f6d40..0000000
--- a/src/lib/components/Dropzone.svelte
+++ /dev/null
@@ -1,85 +0,0 @@
-
-
-
-
-
-
{@html $t("main.dropzone")}
-
-
{$t("main.browse")}
-
-
-
diff --git a/src/lib/components/FileList.svelte b/src/lib/components/FileList.svelte
deleted file mode 100644
index 43e7905..0000000
--- a/src/lib/components/FileList.svelte
+++ /dev/null
@@ -1,59 +0,0 @@
-
-
-{#if files.length !== 0}
-
-
{title}:
-
- {#each Array.from(files) as file}
-
- {file.name}
- {Math.round(file.size / 1000)} KB
-
- {/each}
-
-
-{/if}
-
-
diff --git a/src/lib/components/FileViewer.svelte b/src/lib/components/FileViewer.svelte
deleted file mode 100644
index 857a948..0000000
--- a/src/lib/components/FileViewer.svelte
+++ /dev/null
@@ -1,112 +0,0 @@
-
-
-
-
-{#if areAcceptedFilesRendered}
-
-{:else}
-
-
-{/if}
-
-
diff --git a/src/lib/components/Router.svelte b/src/lib/components/Router.svelte
deleted file mode 100644
index 7aa561e..0000000
--- a/src/lib/components/Router.svelte
+++ /dev/null
@@ -1,24 +0,0 @@
-
-
-
diff --git a/src/lib/index.js b/src/lib/index.js
new file mode 100644
index 0000000..856f2b6
--- /dev/null
+++ b/src/lib/index.js
@@ -0,0 +1 @@
+// place files you want to import through the `$lib` alias in this folder.
diff --git a/src/lib/pages/About.svelte b/src/lib/pages/About.svelte
deleted file mode 100644
index 8aa2d11..0000000
--- a/src/lib/pages/About.svelte
+++ /dev/null
@@ -1,29 +0,0 @@
-
-
- {$t('about.title')}
-
- {@html $t("about.content")}
-
-
-
-
\ No newline at end of file
diff --git a/src/lib/pages/Donate.svelte b/src/lib/pages/Donate.svelte
deleted file mode 100644
index 12886f6..0000000
--- a/src/lib/pages/Donate.svelte
+++ /dev/null
@@ -1,195 +0,0 @@
-
-
-
- {$t("donate.title")}
- {$t("donate.subtitle")}
-
- {@html $t("donate.description")}
-
-
-
- {$t("donate.ways")}
-
-
-
- Bitcoin
- {$t("donate.bitcoin.description")}
- onCopyBitcoin("bc1qpc4lpyr6stxrrg3u0k4clp4crlt6z4j6q845rq")}>
- {#if bitcoinCopyStatus}
- {$t(bitcoinCopyStatus)}
- {:else}
- {$t("donate.copy")}
- {/if}
-
-
-
-
-
-
- Monero
- {$t("donate.monero.description")}
- onCopyMonero("8A9iyTskiBh6f6GDUwnUJaYhAW13gNjDYaZYJBftX434D3XLrcGBko4a8kC4pLSfiuJAoSJ7e8rwP8W4StsVypftCp6FGwm")}>
- {#if moneroCopyStatus}
- {$t(moneroCopyStatus)}
- {:else}
- {$t("donate.copy")}
- {/if}
-
-
-
-
-
- PayPal
- {$t("donate.paypal.description")}
- {$t("donate.paypal.link")}
-
-
-
-
-
\ No newline at end of file
diff --git a/src/lib/pages/Home.svelte b/src/lib/pages/Home.svelte
deleted file mode 100644
index 1103bfb..0000000
--- a/src/lib/pages/Home.svelte
+++ /dev/null
@@ -1,60 +0,0 @@
-
-
-
-
-
- {$t("home.main.title")}
- {@html $t("home.main.description")}
-
-
-
- {$t("home.features.title")}
- {@html $t("home.features.list")}
-
-
-
- {$t("home.howtouse.title")}
- {@html $t("home.howtouse.list")}
-
-
-
- {$t("home.testimonials.title")}
- {@html $t("home.testimonials.description")}
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/lib/pages/NotFound.svelte b/src/lib/pages/NotFound.svelte
deleted file mode 100644
index a4c98be..0000000
--- a/src/lib/pages/NotFound.svelte
+++ /dev/null
@@ -1,2 +0,0 @@
-404 - Not Found
-Oops! That route does not exist.
\ No newline at end of file
diff --git a/src/lib/pages/PrivacyPolicy.svelte b/src/lib/pages/PrivacyPolicy.svelte
deleted file mode 100644
index 342c868..0000000
--- a/src/lib/pages/PrivacyPolicy.svelte
+++ /dev/null
@@ -1,25 +0,0 @@
-
-
- {$t('privacy.policy.title')}
- {$t('privacy.policy.last.update')}
-
- {@html $t('privacy.policy.content')}
-
-
-
\ No newline at end of file
diff --git a/src/lib/pages/TermsOfService.svelte b/src/lib/pages/TermsOfService.svelte
deleted file mode 100644
index 0c53cb2..0000000
--- a/src/lib/pages/TermsOfService.svelte
+++ /dev/null
@@ -1,26 +0,0 @@
-
-
-
- {$t('terms.of.service.title')}
- {$t('terms.of.service.update')}
-
- {@html $t('terms.of.service.content')}
-
-
-
\ No newline at end of file
diff --git a/src/lib/pages/Viewer.svelte b/src/lib/pages/Viewer.svelte
deleted file mode 100644
index 6c33d10..0000000
--- a/src/lib/pages/Viewer.svelte
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
\ No newline at end of file
diff --git a/src/lib/sections/Footer.svelte b/src/lib/sections/Footer.svelte
deleted file mode 100644
index 3645617..0000000
--- a/src/lib/sections/Footer.svelte
+++ /dev/null
@@ -1,87 +0,0 @@
-
-
-
-
-
diff --git a/src/lib/sections/Head.svelte b/src/lib/sections/Head.svelte
deleted file mode 100644
index 75d761f..0000000
--- a/src/lib/sections/Head.svelte
+++ /dev/null
@@ -1,16 +0,0 @@
-
-
- {$t("head.title")}
-
-
-
-
-
-
-
-
\ No newline at end of file
diff --git a/src/lib/sections/Header.svelte b/src/lib/sections/Header.svelte
deleted file mode 100644
index 9694688..0000000
--- a/src/lib/sections/Header.svelte
+++ /dev/null
@@ -1,195 +0,0 @@
-
-
-
-
-
\ No newline at end of file
diff --git a/src/lib/sections/Main.svelte b/src/lib/sections/Main.svelte
deleted file mode 100644
index 34ba389..0000000
--- a/src/lib/sections/Main.svelte
+++ /dev/null
@@ -1,14 +0,0 @@
-
-
-
-
-
-
diff --git a/src/main.js b/src/main.js
deleted file mode 100644
index 990889d..0000000
--- a/src/main.js
+++ /dev/null
@@ -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;
\ No newline at end of file
diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte
new file mode 100644
index 0000000..cc88df0
--- /dev/null
+++ b/src/routes/+page.svelte
@@ -0,0 +1,2 @@
+Welcome to SvelteKit
+Visit svelte.dev/docs/kit to read the documentation
diff --git a/src/utils/env.js b/src/utils/env.js
deleted file mode 100644
index 9734172..0000000
--- a/src/utils/env.js
+++ /dev/null
@@ -1,6 +0,0 @@
-// @ts-nocheck
-function appVersion() {
- return APP_VERSION;
-}
-
-export { appVersion };
diff --git a/src/utils/filterFiles.js b/src/utils/filterFiles.js
deleted file mode 100644
index 62f8f36..0000000
--- a/src/utils/filterFiles.js
+++ /dev/null
@@ -1,21 +0,0 @@
-const formattedFilenameExt = (name) =>
- `.${name.split(".").pop().toLowerCase()}`;
-
-const areRequirementsFulfilled = (requirements, file) =>
- requirements.maxSize >= file.size &&
- requirements.supportedFormats.includes(formattedFilenameExt(file.name));
-
-export function filterFiles(files, requirements) {
- let accepted = [];
- let rejected = [];
- Array.from(files).forEach((file) => {
- if (file) {
- if (areRequirementsFulfilled(requirements, file)) {
- accepted.push(file);
- } else {
- rejected.push(file);
- }
- }
- });
- return { accepted, rejected };
-}
diff --git a/src/utils/rgbToHex.js b/src/utils/rgbToHex.js
deleted file mode 100644
index a09eac5..0000000
--- a/src/utils/rgbToHex.js
+++ /dev/null
@@ -1,15 +0,0 @@
-function componentToHex(c) {
- var hex = c.toString(16);
- return hex.length == 1 ? "0" + hex : hex;
-}
-
-function rgbToHex(color) {
- return (
- "#" +
- componentToHex(color.r) +
- componentToHex(color.g) +
- componentToHex(color.b)
- );
-}
-
-export { rgbToHex };
diff --git a/src/utils/routes.js b/src/utils/routes.js
deleted file mode 100644
index 3a02d8d..0000000
--- a/src/utils/routes.js
+++ /dev/null
@@ -1,51 +0,0 @@
-import Home from '../lib/pages/Home.svelte';
-import Donate from '../lib/pages/Donate.svelte';
-import About from '../lib/pages/About.svelte';
-import PrivacyPolicy from '../lib/pages/PrivacyPolicy.svelte';
-import TermsOfService from '../lib/pages/TermsOfService.svelte';
-import Viewer from '../lib/pages/Viewer.svelte';
-import NotFound from '../lib/pages/NotFound.svelte';
-
-export const routes = {
- '/': {
- component: Home,
- nameKey: "nav.home"
- },
- '/viewer': {
- component: Viewer,
- nameKey: "nav.viewer"
- },
- '/donate': {
- component: Donate,
- nameKey: "nav.donate"
- },
- '/about': {
- component: About,
- nameKey: "nav.about"
- },
- '/privacy-policy': {
- component: PrivacyPolicy,
- nameKey: undefined
- },
- '/terms-of-service': {
- component: TermsOfService,
- nameKey: undefined
- },
-};
-
-export const footerRoutes = {
- '/about': {
- component: About,
- nameKey: "nav.about"
- },
- '/privacy-policy': {
- component: PrivacyPolicy,
- nameKey: "nav.privacy.policy"
- },
- '/terms-of-service': {
- component: TermsOfService,
- nameKey: "nav.terms.of.service"
- },
-}
-
-export const fallback = NotFound;
diff --git a/src/utils/shadeColor.js b/src/utils/shadeColor.js
deleted file mode 100644
index 7afff5a..0000000
--- a/src/utils/shadeColor.js
+++ /dev/null
@@ -1,20 +0,0 @@
-function shadeColor(color, percent) {
- const num = parseInt(color.slice(1), 16),
- amt = Math.round(2.55 * percent),
- R = (num >> 16) + amt,
- G = ((num >> 8) & 0x00ff) + amt,
- B = (num & 0x0000ff) + amt;
- return (
- "#" +
- (
- 0x1000000 +
- (R < 255 ? (R < 1 ? 0 : R) : 255) * 0x10000 +
- (G < 255 ? (G < 1 ? 0 : G) : 255) * 0x100 +
- (B < 255 ? (B < 1 ? 0 : B) : 255)
- )
- .toString(16)
- .slice(1)
- );
-}
-
-export { shadeColor };
diff --git a/src/utils/stores.js b/src/utils/stores.js
deleted file mode 100644
index 2aeebed..0000000
--- a/src/utils/stores.js
+++ /dev/null
@@ -1,3 +0,0 @@
-import { writable } from 'svelte/store';
-
-export const path = writable(window.location.pathname);
diff --git a/src/vite-env.d.ts b/src/vite-env.d.ts
deleted file mode 100644
index 4078e74..0000000
--- a/src/vite-env.d.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-///
-///
diff --git a/static/favicon.png b/static/favicon.png
new file mode 100644
index 0000000..825b9e6
Binary files /dev/null and b/static/favicon.png differ
diff --git a/svelte.config.js b/svelte.config.js
new file mode 100644
index 0000000..1cb4d5e
--- /dev/null
+++ b/svelte.config.js
@@ -0,0 +1,5 @@
+import adapter from '@sveltejs/adapter-auto';
+
+const config = { kit: { adapter: adapter() } };
+
+export default config;
diff --git a/vite.config.js b/vite.config.js
index 338cb28..bbf8c7d 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -1,10 +1,6 @@
-import { defineConfig } from "vite";
-import { svelte } from "@sveltejs/vite-plugin-svelte";
+import { sveltekit } from '@sveltejs/kit/vite';
+import { defineConfig } from 'vite';
-// https://vitejs.dev/config/
export default defineConfig({
- plugins: [svelte()],
- define: {
- APP_VERSION: JSON.stringify(process.env.npm_package_version),
- },
+ plugins: [sveltekit()]
});