2019-08-05 11:11:08 +08:00
import './polyfills/index' ;
import React from 'react' ;
2021-06-17 01:06:34 +08:00
import { render as renderReact , unmountComponentAtNode } from 'react-dom' ;
2019-08-05 11:11:08 +08:00
import axios from 'axios' ;
2021-01-10 11:40:26 +08:00
import { match } from 'path-to-regexp' ;
2019-08-05 11:11:08 +08:00
import copy from 'copy-to-clipboard' ;
2020-11-18 17:26:20 +08:00
import { normalizeLink } from '../src/utils/normalizeLink' ;
2019-08-05 11:11:08 +08:00
import qs from 'qs' ;
import {
2019-11-07 10:41:14 +08:00
toast ,
alert ,
confirm ,
ToastComponent ,
AlertComponent ,
render as renderAmis
2019-08-05 11:11:08 +08:00
} from '../src/index' ;
2021-01-10 11:22:18 +08:00
import '../src/locale/en-US' ;
2021-06-17 21:22:31 +08:00
import 'history' ;
2020-12-29 12:21:10 +08:00
2019-11-07 10:41:14 +08:00
export function embed (
container : string | HTMLElement ,
schema : any ,
2021-01-07 23:35:03 +08:00
props : any ,
2019-11-07 10:41:14 +08:00
env : any
) {
if ( typeof container === 'string' ) {
container = document . querySelector ( container ) as HTMLElement ;
}
if ( ! container ) {
console . error ( '选择器不对,页面上没有此元素' ) ;
return ;
} else if ( container . tagName === 'BODY' ) {
let div = document . createElement ( 'div' ) ;
container . appendChild ( div ) ;
container = div ;
}
container . classList . add ( 'amis-scope' ) ;
let scoped : any ;
2020-11-26 11:03:33 +08:00
const attachmentAdpator = ( response : any ) = > {
if (
response &&
response . headers &&
response . headers [ 'content-disposition' ]
) {
const disposition = response . headers [ 'content-disposition' ] ;
let filename = '' ;
2021-06-17 01:06:34 +08:00
2020-11-26 11:03:33 +08:00
if ( disposition && disposition . indexOf ( 'attachment' ) !== - 1 ) {
2021-06-17 01:06:34 +08:00
// disposition 有可能是 attachment; filename="??.xlsx"; filename*=UTF-8''%E4%B8%AD%E6%96%87.xlsx
// 这种情况下最后一个才是正确的文件名
let filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)$/ ;
let matches = disposition . match ( filenameRegex ) ;
if ( matches && matches . length ) {
filename = matches [ 1 ] . replace ( ` UTF-8'' ` , '' ) . replace ( /['"]/g , '' ) ;
2020-11-26 11:03:33 +08:00
}
// 很可能是中文被 url-encode 了
if ( filename && filename . replace ( /[^%]/g , '' ) . length > 2 ) {
filename = decodeURIComponent ( filename ) ;
}
let type = response . headers [ 'content-type' ] ;
let blob =
response . data . toString ( ) === '[object Blob]'
? response . data
: new Blob ( [ response . data ] , { type : type } ) ;
if ( typeof window . navigator . msSaveBlob !== 'undefined' ) {
// IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
window . navigator . msSaveBlob ( blob , filename ) ;
} else {
let URL = window . URL || ( window as any ) . webkitURL ;
let downloadUrl = URL . createObjectURL ( blob ) ;
if ( filename ) {
// use HTML5 a[download] attribute to specify filename
let a = document . createElement ( 'a' ) ;
// safari doesn't support this yet
if ( typeof a . download === 'undefined' ) {
( window as any ) . location = downloadUrl ;
} else {
a . href = downloadUrl ;
a . download = filename ;
document . body . appendChild ( a ) ;
a . click ( ) ;
}
} else {
( window as any ) . location = downloadUrl ;
}
setTimeout ( function ( ) {
URL . revokeObjectURL ( downloadUrl ) ;
} , 100 ) ; // cleanup
}
return {
. . . response ,
data : {
status : 0 ,
msg : '文件即将开始下载。。'
}
} ;
}
} else if ( response . data . toString ( ) === '[object Blob]' ) {
return new Promise ( ( resolve , reject ) = > {
let reader = new FileReader ( ) ;
reader . addEventListener ( 'loadend' , e = > {
const text = reader . result as string ;
try {
resolve ( {
. . . response ,
data : {
. . . JSON . parse ( text )
}
} ) ;
} catch ( e ) {
reject ( e ) ;
}
} ) ;
reader . readAsText ( response . data ) ;
} ) ;
}
return response ;
} ;
2021-04-08 23:20:52 +08:00
const responseAdaptor = ( api : any ) = > ( value : any ) = > {
2021-06-17 01:06:34 +08:00
let response = value . data || { } ; // blob 下可能会返回内容为空?
2021-04-08 23:20:52 +08:00
// 之前拼写错了,需要兼容
2021-04-09 12:40:36 +08:00
if ( env && env . responseAdpater ) {
2021-04-08 23:20:52 +08:00
env . responseAdaptor = env . responseAdpater ;
}
if ( env && env . responseAdaptor ) {
2019-11-07 10:41:14 +08:00
const url = api . url ;
const idx = api . url . indexOf ( '?' ) ;
const query = ~ idx ? qs . parse ( api . url . substring ( idx ) ) : { } ;
const request = {
. . . api ,
query : query ,
body : api.data
} ;
2021-04-08 23:20:52 +08:00
response = env . responseAdaptor ( api , response , query , request ) ;
2019-11-07 10:41:14 +08:00
} else {
if ( response . hasOwnProperty ( 'errno' ) ) {
response . status = response . errno ;
response . msg = response . errmsg ;
} else if ( response . hasOwnProperty ( 'no' ) ) {
response . status = response . no ;
response . msg = response . error ;
}
2019-08-05 11:11:08 +08:00
}
2019-11-07 10:41:14 +08:00
const result = {
. . . value ,
data : response
} ;
return result ;
} ;
2021-06-17 01:06:34 +08:00
const amisEnv = {
getModalContainer : ( ) = >
env ? . getModalContainer ? . ( ) || document . querySelector ( '.amis-scope' ) ,
notify : ( type : string , msg : string ) = >
toast [ type ]
? toast [ type ] ( msg , type === 'error' ? '系统错误' : '系统消息' )
: console . warn ( '[Notify]' , type , msg ) ,
alert ,
confirm ,
updateLocation : ( to : any , replace : boolean ) = > {
if ( to === 'goBack' ) {
return window . history . back ( ) ;
}
2019-08-05 11:11:08 +08:00
2021-06-17 01:06:34 +08:00
if ( replace && window . history . replaceState ) {
window . history . replaceState ( '' , document . title , to ) ;
return ;
}
2020-12-07 14:56:16 +08:00
2021-06-17 01:06:34 +08:00
location . href = normalizeLink ( to ) ;
} ,
isCurrentUrl : ( to : string , ctx? : any ) = > {
const link = normalizeLink ( to ) ;
const location = window . location ;
let pathname = link ;
let search = '' ;
const idx = link . indexOf ( '?' ) ;
if ( ~ idx ) {
pathname = link . substring ( 0 , idx ) ;
search = link . substring ( idx ) ;
}
2019-11-07 10:41:14 +08:00
2021-06-17 01:06:34 +08:00
if ( search ) {
if ( pathname !== location . pathname || ! location . search ) {
return false ;
}
2019-11-07 10:41:14 +08:00
2021-06-17 01:06:34 +08:00
const query = qs . parse ( search . substring ( 1 ) ) ;
const currentQuery = qs . parse ( location . search . substring ( 1 ) ) ;
2019-11-07 10:41:14 +08:00
2021-06-17 01:06:34 +08:00
return Object . keys ( query ) . every (
key = > query [ key ] === currentQuery [ key ]
) ;
} else if ( pathname === location . pathname ) {
return true ;
} else if ( ! ~ pathname . indexOf ( 'http' ) && ~ pathname . indexOf ( ':' ) ) {
return match ( link , {
decode : decodeURIComponent ,
strict : ctx?.strict ? ? true
} ) ( location . pathname ) ;
}
2019-11-07 10:41:14 +08:00
2021-06-17 01:06:34 +08:00
return false ;
} ,
jumpTo : ( to : string , action? : any ) = > {
if ( to === 'goBack' ) {
return window . history . back ( ) ;
}
2019-11-07 10:41:14 +08:00
2021-06-17 01:06:34 +08:00
to = normalizeLink ( to ) ;
2019-08-05 11:11:08 +08:00
2021-06-17 01:06:34 +08:00
if ( action && action . actionType === 'url' ) {
action . blank === false ? ( window . location . href = to ) : window . open ( to ) ;
return ;
}
2019-11-07 10:41:14 +08:00
2021-06-17 01:06:34 +08:00
if ( /^https?:\/\// . test ( to ) ) {
window . location . replace ( to ) ;
} else {
location . href = to ;
}
} ,
fetcher : async ( api : any ) = > {
let { url , method , data , responseType , config , headers } = api ;
config = config || { } ;
config . withCredentials = true ;
responseType && ( config . responseType = responseType ) ;
2019-11-07 10:41:14 +08:00
2021-06-17 01:06:34 +08:00
if ( config . cancelExecutor ) {
config . cancelToken = new ( axios as any ) . CancelToken (
config . cancelExecutor
) ;
}
config . headers = headers || { } ;
config . method = method ;
if ( method === 'get' && data ) {
config . params = data ;
} else if ( data && data instanceof FormData ) {
// config.headers['Content-Type'] = 'multipart/form-data';
} else if (
data &&
typeof data !== 'string' &&
! ( data instanceof Blob ) &&
! ( data instanceof ArrayBuffer )
) {
data = JSON . stringify ( data ) ;
config . headers [ 'Content-Type' ] = 'application/json' ;
}
// 支持返回各种报错信息
config . validateStatus = function ( status ) {
return true ;
} ;
2021-04-09 12:40:36 +08:00
2021-06-17 01:06:34 +08:00
data && ( config . data = data ) ;
let response = await axios ( url , config ) ;
response = await attachmentAdpator ( response ) ;
response = responseAdaptor ( api ) ( response ) ;
if ( response . status >= 400 ) {
if ( response . data ) {
// 主要用于 raw: 模式下,后端自己校验登录,
if (
response . status === 401 &&
response . data . location &&
response . data . location . startsWith ( 'http' )
) {
location . href = response . data . location . replace (
'{{redirect}}' ,
encodeURIComponent ( location . href )
) ;
return new Promise ( ( ) = > { } ) ;
} else if ( response . data . msg ) {
throw new Error ( response . data . msg ) ;
} else {
throw new Error (
'接口报错:' + JSON . stringify ( response . data , null , 2 )
) ;
}
} else {
throw new Error ( ` 接口出错,状态码是 ${ response . status } ` ) ;
2019-11-07 10:41:14 +08:00
}
2021-06-17 01:06:34 +08:00
}
return response ;
} ,
isCancel : ( value : any ) = > ( axios as any ) . isCancel ( value ) ,
copy : ( contents : string , options : any = { } ) = > {
const ret = copy ( contents , options ) ;
ret && options . shutup !== true && toast . info ( '内容已拷贝到剪切板' ) ;
return ret ;
} ,
richTextToken : '' ,
affixOffsetBottom : 0 ,
. . . env
} ;
let amisProps : any = { } ;
function createElements ( props : any ) : any {
amisProps = {
. . . amisProps ,
. . . props ,
scopeRef : ( ref : any ) = > ( scoped = ref )
} ;
return (
< div className = "amis-routes-wrapper" >
< ToastComponent
position = { ( env && env . toastPosition ) || 'top-right' }
closeButton = { false }
timeout = { 5000 }
2021-06-29 14:03:44 +08:00
locale = { props . locale }
2021-06-17 01:06:34 +08:00
theme = { env ? . theme }
/ >
< AlertComponent
2021-06-29 14:03:44 +08:00
locale = { props . locale }
2021-06-17 01:06:34 +08:00
theme = { env ? . theme }
container = { ( ) = > env ? . getModalContainer ? . ( ) || container }
/ >
{ renderAmis ( schema , amisProps , amisEnv ) }
< / div >
) ;
}
renderReact ( createElements ( props ) , container ) ;
return {
. . . scoped ,
updateProps : ( props : any , callback ? : ( ) = > void ) = > {
renderReact ( createElements ( props ) , container as HTMLElement , callback ) ;
} ,
unmount : ( ) = > {
unmountComponentAtNode ( container as HTMLElement ) ;
}
} ;
2019-08-05 11:11:08 +08:00
}