{"id":16807739,"url":"https://github.com/lfscamargo/files-heavylifting-react","last_synced_at":"2025-04-11T01:12:51.730Z","repository":{"id":177033443,"uuid":"659871495","full_name":"LFSCamargo/files-heavylifting-react","owner":"LFSCamargo","description":"Web Workers Implementation, for heavy file splitting and uploading","archived":false,"fork":false,"pushed_at":"2023-06-29T00:30:23.000Z","size":37,"stargazers_count":16,"open_issues_count":0,"forks_count":1,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-04-11T01:12:47.669Z","etag":null,"topics":["react","typescript-react","webworkers","workers"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/LFSCamargo.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-06-28T18:43:09.000Z","updated_at":"2024-03-20T11:19:22.000Z","dependencies_parsed_at":null,"dependency_job_id":"9cf83e7e-1eb7-46c8-95c5-4ad6e13972ef","html_url":"https://github.com/LFSCamargo/files-heavylifting-react","commit_stats":null,"previous_names":["lfscamargo/files-heavylifting-react"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LFSCamargo%2Ffiles-heavylifting-react","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LFSCamargo%2Ffiles-heavylifting-react/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LFSCamargo%2Ffiles-heavylifting-react/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LFSCamargo%2Ffiles-heavylifting-react/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/LFSCamargo","download_url":"https://codeload.github.com/LFSCamargo/files-heavylifting-react/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248322571,"owners_count":21084337,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["react","typescript-react","webworkers","workers"],"created_at":"2024-10-13T09:54:53.117Z","updated_at":"2025-04-11T01:12:51.724Z","avatar_url":"https://github.com/LFSCamargo.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Files HeavyLifting Processing\n\nIts a simple implementation of webworkers to handle heavy lifting processing in the browser, sometimes we need to process a lot of data in the browser and we don't want to block the UI, so we can use webworkers to handle this task.\n\n# Main Thread\n\n- The main thread is the thread that runs the JavaScript code that you write.\n- The main thread is also called the UI thread because it is responsible for updating the DOM.\n\n# Worker Thread\n\n- Worker threads are threads that run JavaScript code in the background. And that we normally execute heavy lifting processing in the worker thread and send a event back to the main thread to update the UI.\n\n# Running the project\n\n```bash\npnpm install\npnpm dev\n```\n\n# Project Structure\n\n```\n- src/\n  - App.tsx (main component that will call the worker thread)\n  - types/\n    - worker.ts (types for the worker)\n    - file.ts\n  - workers/\n    - file.ts (worker)\n  - hooks/\n    - useFileWorker.ts (hook to use the worker and control the instance of the worker)\n```\n\n## Worker\n\n```ts\nimport { FileWorkerEventType, FileWorkerMessage } from \"../types\";\n\nself.addEventListener(\"message\", async (event: FileWorkerEventType) =\u003e {\n  const { chunkSize } = event.data.input;\n\n  switch (event.data.type) {\n    case \"single_file\":\n      try {\n        const { file } = event.data.input;\n\n        const chunks: Blob[] = [];\n\n        for (let i = 0; i \u003c= file.size; i += chunkSize) {\n          const chunk = file.slice(i, i + chunkSize);\n          chunks.push(chunk);\n        }\n\n        console.log(chunks);\n\n        self.postMessage({\n          type: \"done\",\n          payload: {\n            progress: 100,\n            chunks\n          }\n        } as FileWorkerMessage);\n      } catch (error) {\n        self.postMessage({\n          type: \"error\",\n          payload: {\n            error\n          }\n        } as FileWorkerMessage);\n      }\n      break;\n\n    default:\n      break;\n  }\n});\n\nexport {};\n```\n\n- The worker will receive a file from the main thread and will split the file into chunks and send back to the main thread a array of chunks.\n\n## Hooks\n\n```ts\nimport { useCallback, useMemo } from \"react\";\nimport { FileWorkerInput, FileWorkerMessage } from \"../types\";\n\nexport function useFilesWorker() {\n  const worker = useMemo(\n    () =\u003e\n      new Worker(new URL(\"../workers/file.ts\", import.meta.url), {\n        type: \"module\"\n      }),\n    []\n  );\n\n  const splitIntoChunks = useCallback(\n    (file: File, chunkSize = 1024) =\u003e {\n      return new Promise\u003cBlob[]\u003e((resolve, reject) =\u003e {\n        worker.postMessage({\n          type: \"single_file\",\n          input: {\n            file,\n            chunkSize\n          }\n        } as FileWorkerInput);\n\n        worker.addEventListener(\n          \"message\",\n          (event: MessageEvent\u003cFileWorkerMessage\u003e) =\u003e {\n            switch (event.data.type) {\n              case \"done\":\n                console.log(event.data);\n                resolve(event.data.payload.chunks);\n                break;\n\n              case \"error\":\n                console.log(event.data);\n                reject(event.data.payload.error);\n                break;\n              default:\n                break;\n            }\n          },\n          {\n            once: true\n          }\n        );\n      });\n    },\n    [worker]\n  );\n\n  return {\n    worker,\n    handlers: {\n      splitIntoChunks\n    }\n  };\n}\n```\n\n- The hook will create a instance of the worker and will return a function to split the file into chunks.\n\n## App\n\n```tsx\nimport \"./App.css\";\nimport { useState } from \"react\";\nimport reactLogo from \"./assets/react.svg\";\nimport viteLogo from \"/vite.svg\";\nimport { useFilesWorker } from \"./hooks/useFileWorker\";\n\nfunction App() {\n  const { handlers } = useFilesWorker();\n  const [isSending, setSending] = useState(false);\n\n  const splitIntoChunks = async (file: File) =\u003e {\n    try {\n      if (!file || isSending) return;\n      setSending(true);\n      const chunks = await handlers.splitIntoChunks(file, 1024);\n      console.log(\"Chunks\", chunks);\n    } catch (error) {\n      console.log(error);\n    } finally {\n      setSending(false);\n    }\n  };\n\n  return (\n    \u003c\u003e\n      \u003cdiv\u003e\n        \u003ca href=\"https://vitejs.dev\" target=\"_blank\"\u003e\n          \u003cimg src={viteLogo} className=\"logo\" alt=\"Vite logo\" /\u003e\n        \u003c/a\u003e\n        \u003ca href=\"https://react.dev\" target=\"_blank\"\u003e\n          \u003cimg src={reactLogo} className=\"logo react\" alt=\"React logo\" /\u003e\n        \u003c/a\u003e\n      \u003c/div\u003e\n      \u003ch1\u003eVite + React\u003c/h1\u003e\n      \u003cdiv className=\"card\"\u003e\n        \u003cinput\n          type=\"file\"\n          disabled={isSending}\n          onChange={(e) =\u003e splitIntoChunks(e.target.files![0] as File)}\n        /\u003e\n        \u003cp\u003e{isSending ? \"Processing File\" : \"Send Another File\"}\u003c/p\u003e\n      \u003c/div\u003e\n      \u003cp className=\"read-the-docs\"\u003e\n        Click on the Vite and React logos to learn more\n      \u003c/p\u003e\n    \u003c/\u003e\n  );\n}\n\nexport default App;\n```\n\n- The main component will call the hook and will call the function to split the file into chunks.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flfscamargo%2Ffiles-heavylifting-react","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flfscamargo%2Ffiles-heavylifting-react","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flfscamargo%2Ffiles-heavylifting-react/lists"}