Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x | import React, { useRef, useEffect, MutableRefObject, useState } from "react"; import classNames from "classnames"; import { useLast } from "../_util/use-last"; import { StyledProps } from "../_type"; import { mergeStyle } from "../_util/merge-style"; import { ErrorTip, LoadingTip } from "../tips"; import { injectValue } from "../_util/inject-value"; import { useConfig } from "../_util/config-context"; type BasicType = string | boolean | number | (string | boolean | number)[]; type ExtractBasic<T> = Extract<T, BasicType>; interface Message { type: string; payload?: any; } type PickBasic<T> = { [key in keyof T]: T[key] extends { [key: string]: any } ? PickBasic<T[key]> : ExtractBasic<T[key]> }; type IEditorOptions = import("monaco-editor").editor.IEditorOptions; type IEditorConstructionOptions = import("monaco-editor").editor.IEditorConstructionOptions; /** * `options` 详见: [IEditorConstructionOptions](https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.ieditorconstructionoptions.html) */ export interface CodeEditorOptions extends PickBasic<IEditorConstructionOptions> {} export interface CodeEditorProps extends StyledProps { /** * 编辑器配置,会合并下面的默认值: ```js { "language": "javascript" } ``` * 该配置只有在初始渲染时传入有效,后续传入不再生效。 * 支持的配置请参考: [IEditorConstructionOptions](https://microsoft.github.io/monaco-editor/api/interfaces/monaco.editor.ieditorconstructionoptions.html) * * > 注意:由于 `options` 经过 JSON 序列化给到 iframe,所以配置中传入函数的方式都会无效 */ options?: CodeEditorOptions; /** * 是否自动获得焦点 * @default false */ autoFocus?: boolean; /** * 加载时显示的文本 * @default <LoadingTip /> */ loadingPlaceholder?: React.ReactNode; /** * 出现错误或超时显示的文本 * @docType React.ReactNode | ((retry: () => void) => React.ReactNode) * @default retry => <ErrorTip onRetry={retry} /> */ errorPlaceholder?: React.ReactNode | ((retry: () => void) => React.ReactNode); /** * 发生编辑时回调 */ onEdit?: (editor: CodeEditorInstance) => void; /** * 发生保存(Ctrl + S)时回调 */ onSave?: (editor: CodeEditorInstance) => void; /** * 编辑器可用时回调 */ onReady?: (editor: CodeEditorInstance) => void; /** * 加载编辑器发生错误时回调 */ onError?: (error: Error) => void; /** * 接收到 iframe 消息时回调,若用户调用了 event.preventDefault, 则不执行内部的默认行为 */ onMessage?: (message: Message, event: MessageEvent) => void; /** * 加载编辑器超时时间(ms) * @default 10000 */ timeout?: number; /** * 加载编辑器超时时回调 */ onTimeout?: () => void; /* * 供 iframe 加载的 URL 地址 * * 当默认提供的 Editor 不满足要求时,可定制页面供 iframe 加载,实现可参考:[tea-component/src/codeeditor/frame](https://git.code.oa.com/CFETeam/tea2/tree/master/tea-component/src/codeeditor/frame) */ src?: string; } export interface CodeEditorInstance { /** * 异步获取编辑器当前文本 */ getValue(options?: { preserveBOM: boolean; lineEnding: "\n" | "\r\n"; }): Promise<string>; /** * 设置编辑器当前文本 * @param value */ setValue(value: string): void; /** * 聚焦编辑器 */ focus(): void; /** * 更新配置 */ updateOptions(newOptions: IEditorOptions): void; /** * 向编辑器内部传递消息 */ sendMessage(type: string, payload?: any): void; } // 获取值时自增引用 let nextValueKey = 0; export function CodeEditor(props: CodeEditorProps) { const { classPrefix } = useConfig(); const [ready, setReady] = useState(false); const [error, setError] = useState(false); const timerRef = useRef(null); const { options, autoFocus, className, style, onEdit, onReady, onSave, onError, onMessage, timeout = 10000, onTimeout, loadingPlaceholder = <LoadingTip />, errorPlaceholder = retry => <ErrorTip onRetry={retry} />, src = "https://imgcache.qq.com/qcloud/vendors/monaco-editor/frame/editor.html", } = props; const handler = useLast({ onEdit, onReady, onSave, onError, onMessage }); const iframeRef = useRef<HTMLIFrameElement>(null); const valueCallbackMap = useRef(new Map<string, Function>()); useEffect(() => { Iif (!iframeRef.current) { return () => null; } let instance: CodeEditorInstance; const callHandler = (method: keyof typeof handler.current, ...args) => { if (handler.current && typeof handler.current[method] === "function") { if (method === "onError") { handler.current[method](args[0]); return; } if (method === "onMessage") { handler.current[method](args[0], args[1]); return; } handler.current[method](instance); } }; const receive = (evt: MessageEvent) => { if (evt.source !== iframeRef.current.contentWindow) { return; } const { source } = evt; const message = decodeMessage(evt.data); if (!message) { return; } let isEventPrevented = false; if (onMessage) { const preventDefault = evt.preventDefault.bind(evt); callHandler( "onMessage", message, Object.assign(evt, { preventDefault() { preventDefault(); isEventPrevented = true; }, }) ); } if (isEventPrevented) { return; } const send = (type: string, payload?: any) => { (source as WindowProxy).postMessage( encodeMessage(type, payload), src.replace(/(\w)\/(.*)/, "$1") ); }; const { type, payload } = message; switch (type) { case "ready": { send("create", { language: "javascript", autoFocus, ...(options || null), }); instance = { focus: () => send("focus"), getValue: option => new Promise(resolve => { const key = nextValueKey; nextValueKey += 1; send("get-value", { key, option }); valueCallbackMap.current.set(key.toString(), resolve); }), setValue: value => send("set-value", { value }), updateOptions: options => send("update-options", { options }), sendMessage: send, }; removeTimeoutListener(); setReady(true); callHandler("onReady"); break; } case "value": { const { key, value } = payload; const resolve = valueCallbackMap.current.get(String(key)); if (resolve) { valueCallbackMap.current.delete(String(key)); resolve(value); } break; } case "edit": { callHandler("onEdit"); break; } case "save": { callHandler("onSave"); break; } case "error": { removeTimeoutListener(); setError(true); callHandler("onError", new Error(payload.message)); break; } } }; addTimeoutListener(); window.addEventListener("message", receive); return () => { removeTimeoutListener(); window.removeEventListener("message", receive); }; }, []); // eslint-disable-line react-hooks/exhaustive-deps function addTimeoutListener() { removeTimeoutListener(); timerRef.current = setTimeout(() => { setError(true); if (typeof onTimeout === "function") { onTimeout(); } }, timeout); } function removeTimeoutListener() { clearTimeout(timerRef.current); } Iif (error) { return ( <div className={classNames(`${classPrefix}-code-editor`, className)} style={mergeStyle({ position: "relative" }, style)} > <Tips classPrefix={classPrefix}> {injectValue(errorPlaceholder)(() => { setError(false); addTimeoutListener(); })} </Tips> </div> ); } return ( <div className={classNames(`${classPrefix}-code-editor`, className)} style={mergeStyle({ position: "relative" }, style)} > <iframe title="code-editor" ref={iframeRef} src={src} className={`${classPrefix}-code-editor-frame`} style={{ width: "100%", height: "100%" }} frameBorder="no" /> {!ready && <Tips classPrefix={classPrefix}>{loadingPlaceholder}</Tips>} </div> ); } function decodeMessage(message: string) { try { const { type, payload } = JSON.parse(message); if (type) { return { type, payload }; } } catch (err) { // continue } return null; } function encodeMessage(type: string, payload?: any) { return JSON.stringify({ type, payload }); } function DefaultTipsWrapper({ children, style = {} }) { return ( <div style={{ padding: "20px 0", textAlign: "center", ...style }}> {children} </div> ); } function Tips({ children, classPrefix, }: { children: React.ReactNode; classPrefix: string; }) { return ( <div className={`${classPrefix}-code-editor-loading`} style={{ position: "absolute", left: 0, top: 0, bottom: 0, right: 0, }} > {typeof children === "string" ? ( <DefaultTipsWrapper style={{ padding: 0, height: 30, lineHeight: 30, opacity: 0.5, }} > {children} </DefaultTipsWrapper> ) : ( <DefaultTipsWrapper>{children}</DefaultTipsWrapper> )} </div> ); } |