customized-fabric 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/lib/ClipartObject/constants.js +12 -0
  2. package/lib/ClipartObject/index.js +145 -0
  3. package/lib/ClipartObject/interfaces.js +2 -0
  4. package/lib/ImagePlaceholderObject/constants.js +12 -0
  5. package/lib/ImagePlaceholderObject/index.js +140 -0
  6. package/lib/ImagePlaceholderObject/interfaces.js +2 -0
  7. package/lib/TextInputObject/constants.js +13 -0
  8. package/lib/TextInputObject/index.js +188 -0
  9. package/lib/TextInputObject/interfaces.js +2 -0
  10. package/lib/constants.js +12 -0
  11. package/lib/index.js +52 -0
  12. package/lib/interfaces.js +19 -0
  13. package/lib/objectId/bson_value.js +12 -0
  14. package/lib/objectId/constants.js +107 -0
  15. package/lib/objectId/error.js +79 -0
  16. package/lib/objectId/index.js +281 -0
  17. package/lib/objectId/parser/utils.js +31 -0
  18. package/lib/objectId/utils/byte_utils.js +28 -0
  19. package/lib/objectId/utils/node_byte_utils.js +98 -0
  20. package/lib/objectId/utils/web_byte_utils.js +124 -0
  21. package/lib/utils.js +90 -0
  22. package/package.json +21 -0
  23. package/src/ClipartObject/constants.ts +9 -0
  24. package/src/ClipartObject/index.ts +156 -0
  25. package/src/ClipartObject/interfaces.ts +29 -0
  26. package/src/ImagePlaceholderObject/constants.ts +9 -0
  27. package/src/ImagePlaceholderObject/index.ts +155 -0
  28. package/src/ImagePlaceholderObject/interfaces.ts +21 -0
  29. package/src/TextInputObject/constants.ts +11 -0
  30. package/src/TextInputObject/index.ts +205 -0
  31. package/src/TextInputObject/interfaces.ts +40 -0
  32. package/src/constants.ts +10 -0
  33. package/src/index.ts +62 -0
  34. package/src/interfaces.ts +3 -0
  35. package/src/objectId/bson_value.ts +18 -0
  36. package/src/objectId/constants.ts +141 -0
  37. package/src/objectId/error.ts +85 -0
  38. package/src/objectId/index.ts +354 -0
  39. package/src/objectId/parser/utils.ts +29 -0
  40. package/src/objectId/utils/byte_utils.ts +72 -0
  41. package/src/objectId/utils/node_byte_utils.ts +173 -0
  42. package/src/objectId/utils/web_byte_utils.ts +212 -0
  43. package/src/utils.ts +93 -0
  44. package/tsconfig.json +110 -0
@@ -0,0 +1,212 @@
1
+ import { BSONError } from "../error";
2
+
3
+ type TextDecoder = {
4
+ readonly encoding: string;
5
+ readonly fatal: boolean;
6
+ readonly ignoreBOM: boolean;
7
+ decode(input?: Uint8Array): string;
8
+ };
9
+ type TextDecoderConstructor = {
10
+ new (
11
+ label: "utf8",
12
+ options: { fatal: boolean; ignoreBOM?: boolean }
13
+ ): TextDecoder;
14
+ };
15
+
16
+ type TextEncoder = {
17
+ readonly encoding: string;
18
+ encode(input?: string): Uint8Array;
19
+ };
20
+ type TextEncoderConstructor = {
21
+ new (): TextEncoder;
22
+ };
23
+
24
+ // Web global
25
+ declare const TextDecoder: TextDecoderConstructor;
26
+ declare const TextEncoder: TextEncoderConstructor;
27
+ declare const atob: (base64: string) => string;
28
+ declare const btoa: (binary: string) => string;
29
+
30
+ type ArrayBufferViewWithTag = ArrayBufferView & {
31
+ [Symbol.toStringTag]?: string;
32
+ };
33
+
34
+ function isReactNative() {
35
+ const { navigator } = globalThis as { navigator?: { product?: string } };
36
+ return typeof navigator === "object" && navigator.product === "ReactNative";
37
+ }
38
+
39
+ /** @internal */
40
+ export function webMathRandomBytes(byteLength: number) {
41
+ if (byteLength < 0) {
42
+ throw new RangeError(
43
+ `The argument 'byteLength' is invalid. Received ${byteLength}`
44
+ );
45
+ }
46
+ return webByteUtils.fromNumberArray(
47
+ Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256))
48
+ );
49
+ }
50
+
51
+ /** @internal */
52
+ const webRandomBytes: (byteLength: number) => Uint8Array = (() => {
53
+ const { crypto } = globalThis as {
54
+ crypto?: { getRandomValues?: (space: Uint8Array) => Uint8Array };
55
+ };
56
+ if (crypto != null && typeof crypto.getRandomValues === "function") {
57
+ return (byteLength: number) => {
58
+ // @ts-expect-error: crypto.getRandomValues cannot actually be null here
59
+ // You cannot separate getRandomValues from crypto (need to have this === crypto)
60
+ return crypto.getRandomValues(webByteUtils.allocate(byteLength));
61
+ };
62
+ } else {
63
+ if (isReactNative()) {
64
+ const { console } = globalThis as {
65
+ console?: { warn?: (message: string) => void };
66
+ };
67
+ console?.warn?.(
68
+ "BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values."
69
+ );
70
+ }
71
+ return webMathRandomBytes;
72
+ }
73
+ })();
74
+
75
+ const HEX_DIGIT = /(\d|[a-f])/i;
76
+
77
+ /** @internal */
78
+ export const webByteUtils = {
79
+ toLocalBufferType(
80
+ potentialUint8array: Uint8Array | ArrayBufferViewWithTag | ArrayBuffer
81
+ ): Uint8Array {
82
+ const stringTag =
83
+ potentialUint8array?.[Symbol.toStringTag] ??
84
+ Object.prototype.toString.call(potentialUint8array);
85
+
86
+ if (stringTag === "Uint8Array") {
87
+ return potentialUint8array as Uint8Array;
88
+ }
89
+
90
+ if (ArrayBuffer.isView(potentialUint8array)) {
91
+ return new Uint8Array(
92
+ potentialUint8array.buffer.slice(
93
+ potentialUint8array.byteOffset,
94
+ potentialUint8array.byteOffset + potentialUint8array.byteLength
95
+ )
96
+ );
97
+ }
98
+
99
+ if (
100
+ stringTag === "ArrayBuffer" ||
101
+ stringTag === "SharedArrayBuffer" ||
102
+ stringTag === "[object ArrayBuffer]" ||
103
+ stringTag === "[object SharedArrayBuffer]"
104
+ ) {
105
+ return new Uint8Array(potentialUint8array);
106
+ }
107
+
108
+ throw new BSONError(
109
+ `Cannot make a Uint8Array from ${String(potentialUint8array)}`
110
+ );
111
+ },
112
+
113
+ allocate(size: number): Uint8Array {
114
+ if (typeof size !== "number") {
115
+ throw new TypeError(
116
+ `The "size" argument must be of type number. Received ${String(size)}`
117
+ );
118
+ }
119
+ return new Uint8Array(size);
120
+ },
121
+
122
+ equals(a: Uint8Array, b: Uint8Array): boolean {
123
+ if (a.byteLength !== b.byteLength) {
124
+ return false;
125
+ }
126
+ for (let i = 0; i < a.byteLength; i++) {
127
+ if (a[i] !== b[i]) {
128
+ return false;
129
+ }
130
+ }
131
+ return true;
132
+ },
133
+
134
+ fromNumberArray(array: number[]): Uint8Array {
135
+ return Uint8Array.from(array);
136
+ },
137
+
138
+ fromBase64(base64: string): Uint8Array {
139
+ return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
140
+ },
141
+
142
+ toBase64(uint8array: Uint8Array): string {
143
+ return btoa(webByteUtils.toISO88591(uint8array));
144
+ },
145
+
146
+ /** **Legacy** binary strings are an outdated method of data transfer. Do not add public API support for interpreting this format */
147
+ fromISO88591(codePoints: string): Uint8Array {
148
+ return Uint8Array.from(codePoints, (c) => c.charCodeAt(0) & 0xff);
149
+ },
150
+
151
+ /** **Legacy** binary strings are an outdated method of data transfer. Do not add public API support for interpreting this format */
152
+ toISO88591(uint8array: Uint8Array): string {
153
+ return Array.from(Uint16Array.from(uint8array), (b) =>
154
+ String.fromCharCode(b)
155
+ ).join("");
156
+ },
157
+
158
+ fromHex(hex: string): Uint8Array {
159
+ const evenLengthHex =
160
+ hex.length % 2 === 0 ? hex : hex.slice(0, hex.length - 1);
161
+ const buffer = [];
162
+
163
+ for (let i = 0; i < evenLengthHex.length; i += 2) {
164
+ const firstDigit = evenLengthHex[i];
165
+ const secondDigit = evenLengthHex[i + 1];
166
+
167
+ if (!HEX_DIGIT.test(firstDigit)) {
168
+ break;
169
+ }
170
+ if (!HEX_DIGIT.test(secondDigit)) {
171
+ break;
172
+ }
173
+
174
+ const hexDigit = Number.parseInt(`${firstDigit}${secondDigit}`, 16);
175
+ buffer.push(hexDigit);
176
+ }
177
+
178
+ return Uint8Array.from(buffer);
179
+ },
180
+
181
+ toHex(uint8array: Uint8Array): string {
182
+ return Array.from(uint8array, (byte) =>
183
+ byte.toString(16).padStart(2, "0")
184
+ ).join("");
185
+ },
186
+
187
+ fromUTF8(text: string): Uint8Array {
188
+ return new TextEncoder().encode(text);
189
+ },
190
+
191
+ toUTF8(uint8array: Uint8Array, start: number, end: number): string {
192
+ return new TextDecoder("utf8", { fatal: false }).decode(
193
+ uint8array.slice(start, end)
194
+ );
195
+ },
196
+
197
+ utf8ByteLength(input: string): number {
198
+ return webByteUtils.fromUTF8(input).byteLength;
199
+ },
200
+
201
+ encodeUTF8Into(
202
+ buffer: Uint8Array,
203
+ source: string,
204
+ byteOffset: number
205
+ ): number {
206
+ const bytes = webByteUtils.fromUTF8(source);
207
+ buffer.set(bytes, byteOffset);
208
+ return bytes.byteLength;
209
+ },
210
+
211
+ randomBytes: webRandomBytes,
212
+ };
package/src/utils.ts ADDED
@@ -0,0 +1,93 @@
1
+ import { fabric } from "fabric";
2
+ import { OBJECT_TYPES } from "./constants";
3
+ import { Clipart, TextInput } from ".";
4
+ import { ImagePlaceholder } from "./ImagePlaceholderObject";
5
+
6
+ export const loadFontFromUrl = async (name: string, url: string) => {
7
+ if (!name || !url) return;
8
+ const font = new FontFace(name, `url(${url})`);
9
+ await font.load();
10
+ document.fonts.add(font);
11
+ };
12
+
13
+ export const isFontLoaded = (name: string) => {
14
+ let isLoaded = false;
15
+ document.fonts.forEach((font) => {
16
+ if (name == font.family) {
17
+ isLoaded = true;
18
+ }
19
+ });
20
+ return isLoaded;
21
+ };
22
+
23
+ export const loadImageFromFile = (image: File) => {
24
+ return new Promise<fabric.Image>((resolve) => {
25
+ const reader = new FileReader();
26
+ reader.onload = function (event) {
27
+ const image = new Image();
28
+ image.src = event?.target?.result as string;
29
+ image.onload = function () {
30
+ resolve(new fabric.Image(image));
31
+ };
32
+ };
33
+ reader.readAsDataURL(image);
34
+ });
35
+ };
36
+
37
+ export const lockObject = (
38
+ object: fabric.Object | any,
39
+ locked: boolean,
40
+ selectable?: boolean
41
+ ) => {
42
+ object.set({
43
+ hasControls: !locked,
44
+ lockMovementX: locked,
45
+ lockMovementY: locked,
46
+ lockRotation: locked,
47
+ lockScalingX: locked,
48
+ lockScalingY: locked,
49
+ lockUniScaling: locked,
50
+ lockSkewingX: locked,
51
+ lockSkewingY: locked,
52
+ lockScalingFlip: locked,
53
+ locked: locked,
54
+ selectable: selectable ?? !locked,
55
+ });
56
+ };
57
+
58
+ export const lockAllObjects = (canvas: fabric.Canvas, locked: boolean) => {
59
+ canvas._objects.map((object) => {
60
+ lockObject(object, locked);
61
+ });
62
+ };
63
+
64
+ export const getObject = (object: any, options?: { isOriginal?: boolean }) => {
65
+ switch (object.type) {
66
+ case OBJECT_TYPES.textInput: {
67
+ const textInputObject = new TextInput({
68
+ ...object,
69
+ hideStroke: options?.isOriginal,
70
+ });
71
+ return textInputObject;
72
+ }
73
+
74
+ case OBJECT_TYPES.clipart: {
75
+ const clipartObject = new Clipart({
76
+ ...object,
77
+ hideStroke: options?.isOriginal,
78
+ });
79
+ return clipartObject;
80
+ }
81
+
82
+ case OBJECT_TYPES.imagePlaceHolder: {
83
+ const imagePlaceHolderObject = new ImagePlaceholder({
84
+ ...object,
85
+ hideStroke: options?.isOriginal,
86
+ });
87
+ return imagePlaceHolderObject;
88
+ }
89
+
90
+ default:
91
+ return;
92
+ }
93
+ };
package/tsconfig.json ADDED
@@ -0,0 +1,110 @@
1
+ {
2
+ "compilerOptions": {
3
+ /* Visit https://aka.ms/tsconfig to read more about this file */
4
+
5
+ /* Projects */
6
+ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7
+ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8
+ // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9
+ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10
+ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11
+ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12
+
13
+ /* Language and Environment */
14
+ "target": "es2020", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15
+ // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16
+ // "jsx": "preserve", /* Specify what JSX code is generated. */
17
+ // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
18
+ // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
19
+ // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
20
+ // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
21
+ // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
22
+ // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
23
+ // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
24
+ // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
25
+ // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
26
+
27
+ /* Modules */
28
+ "module": "commonjs", /* Specify what module code is generated. */
29
+ // "rootDir": "./", /* Specify the root folder within your source files. */
30
+ // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
31
+ // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
32
+ // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
33
+ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
34
+ // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
35
+ // "types": [], /* Specify type package names to be included without being referenced in a source file. */
36
+ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
37
+ // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
38
+ // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
39
+ // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
40
+ // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
41
+ // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
42
+ // "resolveJsonModule": true, /* Enable importing .json files. */
43
+ // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
44
+ // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
45
+
46
+ /* JavaScript Support */
47
+ // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
48
+ // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
49
+ // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
50
+
51
+ /* Emit */
52
+ // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
53
+ // "declarationMap": true, /* Create sourcemaps for d.ts files. */
54
+ // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
55
+ // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
56
+ // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
57
+ // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
58
+ // "outDir": "./", /* Specify an output folder for all emitted files. */
59
+ // "removeComments": true, /* Disable emitting comments. */
60
+ // "noEmit": true, /* Disable emitting files from a compilation. */
61
+ // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
62
+ // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
63
+ // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
64
+ // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
65
+ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
66
+ // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
67
+ // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
68
+ // "newLine": "crlf", /* Set the newline character for emitting files. */
69
+ // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
70
+ // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
71
+ // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
72
+ // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
73
+ // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
74
+ // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
75
+
76
+ /* Interop Constraints */
77
+ // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
78
+ // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
79
+ // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
80
+ "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
81
+ // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
82
+ "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
83
+
84
+ /* Type Checking */
85
+ "strict": true, /* Enable all strict type-checking options. */
86
+ // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
87
+ // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
88
+ // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
89
+ // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
90
+ // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
91
+ // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
92
+ // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
93
+ // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
94
+ // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
95
+ // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
96
+ // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
97
+ // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
98
+ // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
99
+ // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
100
+ // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
101
+ // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
102
+ // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
103
+ // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
104
+
105
+ /* Completeness */
106
+ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
107
+ "skipLibCheck": true, /* Skip type checking all .d.ts files. */
108
+ "outDir": "./lib"
109
+ }
110
+ }