Skip to content

Commit

Permalink
Add Capacitor support
Browse files Browse the repository at this point in the history
  • Loading branch information
aeharding authored and qq15725 committed Dec 5, 2023
1 parent b0fe2d8 commit 50e39c7
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 5 deletions.
1 change: 1 addition & 0 deletions src/create-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ export async function createContext<T extends Node>(node: T, options?: Options &
bypassingCache: false,
...options?.fetch,
},
fetchFn: null,
font: {},
drawImageInterval: 100,
workerUrl: null,
Expand Down
19 changes: 14 additions & 5 deletions src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ export function contextFetch(context: Context, options: ContextFetchOptions) {
timeout,
acceptOfImage,
requests,
fetchFn,
fetch: {
requestInit,
bypassingCache,
Expand Down Expand Up @@ -82,16 +83,24 @@ export function contextFetch(context: Context, options: ContextFetchOptions) {
response: null as any,
}

request.response = (
!IN_SAFARI && rawUrl.startsWith('http') && workers.length
? new Promise((resolve, reject) => {
request.response = (async () => {
if (fetchFn && requestType === 'image') {
const result = await fetchFn(rawUrl)

if (result) return result
}

if (!IN_SAFARI && rawUrl.startsWith('http') && workers.length) {
return new Promise<string>((resolve, reject) => {
const worker = workers[requests.size & (workers.length - 1)]
worker.postMessage({ rawUrl, ...baseFetchOptions })
request!.resolve = resolve
request!.reject = reject
})
: baseFetch(baseFetchOptions)
).catch(error => {
}

return baseFetch(baseFetchOptions)
})().catch(error => {
requests.delete(rawUrl)

if (requestType === 'image' && placeholderImage) {
Expand Down
17 changes: 17 additions & 0 deletions src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,23 @@ export interface Options {
*/
debug?: boolean

/**
* Custom implementation to get image data for a custom URL.
* This can be helpful for Capacitor or Cordova when using
* native fetch to bypass CORS issues.
*
* If returns a string, will completely bypass any `Options.fetch`
* settings with your custom implementation.
*
* If returns false, will fall back to normal fetch implementation
*
* @param url
* @returns A data URL for the image
*/
fetchFn?: ((
url: string,
) => Promise<string | false>) | null

/**
* The options of fetch resources.
*/
Expand Down

1 comment on commit 50e39c7

@vercel
Copy link

@vercel vercel bot commented on 50e39c7 Dec 5, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

modern-screenshot – ./

modern-screenshot-qq15725.vercel.app
modern-screenshot.vercel.app
modern-screenshot-git-main-qq15725.vercel.app

Please sign in to comment.