@wordpress/editor
Version:
Enhanced block editor for WordPress posts.
8 lines (7 loc) • 2.33 kB
Source Map (JSON)
{
"version": 3,
"sources": ["../../../src/utils/media-sideload-from-url/index.js"],
"sourcesContent": ["import apiFetch from '@wordpress/api-fetch';\nimport { select } from '@wordpress/data';\nimport { transformAttachment } from '@wordpress/media-utils';\nimport { store as editorStore } from '../../store';\n\nconst noop = () => {};\n\n/**\n * Sideloads an external image into the media library from its URL.\n *\n * The server downloads the remote file, which avoids a cross-origin browser\n * fetch that fails when the editor is cross-origin isolated. Since the server\n * owns the upload it also generates sub-sizes, as with a regular upload.\n *\n * @param {Object} $0 Parameters object.\n * @param {string} $0.url URL of the external image to sideload.\n * @param {Function} $0.onSuccess Function called with the new attachment on success.\n * @param {Function} $0.onError Function called with an error message on failure.\n */\nexport default function mediaSideloadFromUrl( {\n\turl,\n\tonSuccess,\n\tonError = noop,\n} ) {\n\tconst currentPost = select( editorStore ).getCurrentPost();\n\t// Templates and template parts store their numerical ID in `wp_id`.\n\tconst currentPostId =\n\t\ttypeof currentPost?.id === 'number'\n\t\t\t? currentPost.id\n\t\t\t: currentPost?.wp_id;\n\tconst postData = currentPostId ? { post: currentPostId } : {};\n\n\tapiFetch( {\n\t\tpath: '/wp/v2/media',\n\t\tmethod: 'POST',\n\t\tdata: {\n\t\t\turl,\n\t\t\t...postData,\n\t\t},\n\t} )\n\t\t.then( ( attachment ) => {\n\t\t\tonSuccess?.( transformAttachment( attachment ) );\n\t\t} )\n\t\t.catch( ( error ) => {\n\t\t\tonError( error?.message || error );\n\t\t} );\n}\n"],
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,uBAAqB;AACrB,kBAAuB;AACvB,yBAAoC;AACpC,mBAAqC;AAErC,IAAM,OAAO,MAAM;AAAC;AAcL,SAAR,qBAAuC;AAAA,EAC7C;AAAA,EACA;AAAA,EACA,UAAU;AACX,GAAI;AACH,QAAM,kBAAc,oBAAQ,aAAAA,KAAY,EAAE,eAAe;AAEzD,QAAM,gBACL,OAAO,aAAa,OAAO,WACxB,YAAY,KACZ,aAAa;AACjB,QAAM,WAAW,gBAAgB,EAAE,MAAM,cAAc,IAAI,CAAC;AAE5D,uBAAAC,SAAU;AAAA,IACT,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,MAAM;AAAA,MACL;AAAA,MACA,GAAG;AAAA,IACJ;AAAA,EACD,CAAE,EACA,KAAM,CAAE,eAAgB;AACxB,oBAAa,wCAAqB,UAAW,CAAE;AAAA,EAChD,CAAE,EACD,MAAO,CAAE,UAAW;AACpB,YAAS,OAAO,WAAW,KAAM;AAAA,EAClC,CAAE;AACJ;",
"names": ["editorStore", "apiFetch"]
}