Explorar o código

add: worker 添加队列

liutian hai 3 meses
pai
achega
c4fe3c1532

+ 71 - 0
packages/core/src/worker/PriorityQueue.ts

@@ -0,0 +1,71 @@
+const findIndex = (array: any[], value: any, comparator: Function) => {
+  let start = 0
+  let end = array.length
+  while (start < end) {
+    const middle = (start + end) >>> 1
+    if (comparator(array[middle], value) <= 0) {
+      start = middle + 1
+    } else {
+      end = middle
+    }
+  }
+  return start
+}
+
+class PriorityQueue {
+  options: {
+    initialValues: any[]
+  }
+  comparator: (a: any, b: any) => number
+  data: any[]
+  constructor(options: {
+    comparator: (a: any, b: any) => number
+    initialValues: any[]
+  }) {
+    this.options = options
+    this.comparator = options.comparator
+    this.data = (options.initialValues && options.initialValues.slice()) || []
+    this.data.sort(this.comparator).reverse()
+  }
+
+  queue(value: any) {
+    const index = findIndex(this.data, value, this.comparator)
+    this.data.splice(index, 0, value)
+  }
+
+  dequeue() {
+    return this.data.pop()
+  }
+
+  peek() {
+    return this.data[this.data.length - 1]
+  }
+
+  find(value: any) {
+    const index = findIndex(this.data, value, this.comparator) - 1
+    return index >= 0 && this.comparator(this.data[index], value) === 0 ? index : -1
+  }
+
+  remove(value: any) {
+    const index = this.find(value)
+    if (index >= 0) {
+      this.data.splice(index, 1)
+      return true
+    }
+    return false
+  }
+
+  removeAllMatching(test: Function, callback: Function) {
+    let count = 0
+    for (let i = this.data.length - 1; i >= 0; i--) {
+      if (test(this.data[i])) {
+        const value = this.data.splice(i, 1)[0]
+        if (callback) {
+          callback(value)
+        }
+        count++
+      }
+    }
+    return count
+  }
+}

+ 17 - 6
packages/core/src/worker/index.ts

@@ -1,15 +1,24 @@
+// @ts-ignore
 importScripts("./ComPDFkit.js")
 
 import MessageHandler from "./messageHandler"
 
+async function sleep(delay: number) {
+  await new Promise((resolve) => setTimeout(resolve, delay))
+}
+
 class ComPDFKitWorker {
-  static setup(gloabal) {
-    const messageHandler = new MessageHandler(gloabal)
+  static messageHandler: MessageHandler
+  static setup(self: typeof globalThis) {
+    const messageHandler = new MessageHandler('worker', self)
     this.messageHandler = messageHandler
+
+    
   }
 }
 
-async function setUp() {
+async function setUp(): Promise<void> {
+  // @ts-ignore
   while (!runtimeInitialized) {
     await sleep(100)
   }
@@ -19,12 +28,14 @@ async function setUp() {
 }
 
 setUp().then(() => {
-  function (gloabal) {
-    gloabal.onmessage = function (e) {
+  function ready (gloabal: typeof globalThis) {
+    gloabal.onmessage = function (e: MessageEvent) {
       const action = e.data.action
       if (action === 'init') {
         ComPDFKitWorker.setup(gloabal)
       }
     }
-  }(typeof window !== 'undefined' ? window : self)
+  }
+
+  ready(typeof window !== 'undefined' ? window : self)
 })

+ 5 - 36
packages/core/src/worker/messageHandler.ts

@@ -14,7 +14,7 @@ interface PromiseCapability<T> {
 
 class MessageHandler {
   name: string
-  comObj: Window | Worker
+  comObj: typeof globalThis & { reset?: Function}
   callbackId: number
   postMessageTransfers: boolean
   callbacksCapabilities: CallbackCapabilities
@@ -23,7 +23,7 @@ class MessageHandler {
   nextAsync: Function | null
   msgHandler: (event: MessageEvent) => void
 
-  constructor(name: string, comObj: Window | Worker) {
+  constructor(name: string, comObj: typeof globalThis) {
     this.name = name
     this.comObj = comObj
     this.callbackId = 1
@@ -33,10 +33,6 @@ class MessageHandler {
     this.actionHandlerAsync = {}
     this.nextAsync = null
 
-    this.actionHandler.console_log = [(k: any) => console.log(k)]
-    this.actionHandler.console_error = [(k: any) => console.error(k)]
-    this.actionHandler.workerLoaded = [() => {}]
-
     this.msgHandler = this.handleMessage.bind(this)
     comObj.addEventListener("message", this.msgHandler)
   }
@@ -190,35 +186,8 @@ class MessageHandler {
     }
   }
 
-  postMessage(message: any) {
-    if (this.postMessageTransfers) {
-      const transfers = this.getTransfersArray(message)
-      this.comObj.postMessage(message, transfers)
-    } else {
-      this.comObj.postMessage(message)
-    }
-  }
-
-  getObjectTransfers(obj: any, transfers: any[]) {
-    if (obj !== null && typeof obj === "object") {
-      if (obj instanceof Uint8Array) {
-        transfers.push(obj.buffer)
-      } else if (obj instanceof ArrayBuffer) {
-        transfers.push(obj)
-      } else {
-        Object.keys(obj).forEach(key => {
-          if (obj.hasOwnProperty(key)) {
-            this.getObjectTransfers(obj[key], transfers)
-          }
-        })
-      }
-    }
-  }
-
-  getTransfersArray(message: any): any[] | undefined {
-    const transfers: any[] = []
-    this.getObjectTransfers(message, transfers)
-    return transfers.length === 0 ? undefined : transfers
+  postMessage(message: any, transfers?: Transferable[]) {
+    this.comObj.postMessage(message, transfers || [])
   }
 
   handleMessage(event: MessageEvent) {
@@ -281,4 +250,4 @@ class MessageHandler {
     return { promise, resolve, reject }
   }
 }
-export default MessageHandler
+export default MessageHandler

+ 1 - 1
packages/core/tsconfig.json

@@ -19,7 +19,7 @@
     "removeComments": false,
     "declaration": true,
     "jsx": "preserve",
-    "lib": ["esnext", "dom"],
+    "lib": ["esnext", "dom", "WebWorker"],
     // "types": ["vitest/globals", "puppeteer", "node"],
     "rootDir": ".",
     "paths": {