@kanjieteam/kjdraw
KJDraw Editor APIKJDraw 编辑器 API
Mount a complete CAD editor with one function, then control drawings, files, commands and selection through a small typed API.一个函数挂载完整 CAD 编辑器,再通过小而清晰的类型化 API 控制图档、文件、命令与选择。
npm install @kanjieteam/kjdraw@1.0.0-rc.3Quickstart快速接入#
Give the host element a height, create the editor, then wait for ready before using the current drawing.先给容器设置高度,创建编辑器,再等待 ready 完成后操作当前图档。
<div id="cad"></div>
<style>
#cad { width: 100%; height: 720px; }
</style>
import { createKJDrawEditor } from '@kanjieteam/kjdraw'
const editor = createKJDrawEditor('#cad', {
document: 'sample',
locale: 'en',
theme: 'dark',
layout: 'classic',
onChange: ({ revision, entityCount }) => {
console.log({ revision, entityCount })
},
})
await editor.ready
await editor.execute('CREATE', {
type: 'CIRCLE',
payload: { center: [40, 30, 0], radius: 12 },
})
editor.setLayout('compact').fit()
const kjd = await editor.save({ format: 'KJD', download: false })
// Call editor.dispose() when the owning screen unmounts.
Options#
Pass these values as the second argument to createKJDrawEditor().将这些选项作为 createKJDrawEditor() 的第二个参数传入。
| Option选项 | Type | Default默认值 | Purpose用途 |
|---|---|---|---|
document | KJDocument | 'sample' | 'blank' | null | active SDK document or 'sample' | Initial drawing. 'sample' opens the included example; 'blank' and null create an empty drawing.初始图档。'sample' 打开内置示例;'blank' 与 null 创建空白图档。 |
sdk | KJDrawSDK | new SDK | Reuse an application SDK so commands, plugins and documents share one registry.复用应用 SDK,让命令、插件与图档共享同一注册表。 |
locale | 'en' | 'zh-CN' | 'en' | Initial workbench language.工作台初始语言。 |
theme | 'dark' | 'light' | 'dark' | Initial panel and canvas appearance.面板与画布的初始外观。 |
layout | 'classic' | 'compact' | 'focus' | 'classic' | Workbench arrangement: full CAD ribbon and panels, a shorter compact ribbon, or a canvas-first focus view. Available since 1.0.0-rc.3.工作台布局:完整 CAD Ribbon 与面板、较矮的紧凑 Ribbon,或画布优先的专注视图。自 1.0.0-rc.3 起提供。 |
readonly | boolean | false | Keep inspection, navigation and export while disabling editing controls.保留检查、导航与导出,同时禁用编辑控件。 |
grid | boolean | true | Show the drawing grid initially.初始显示绘图网格。 |
toolbar | boolean | true | Show the ribbon toolbar.显示 Ribbon 工具栏。 |
layers | boolean | true | Show the layers panel.显示图层面板。 |
properties | boolean | true | Show the properties inspector.显示属性检查器。 |
title | string | drawing ID | Override the drawing title displayed in the workbench header.覆盖工作台顶部显示的图档标题。 |
maxFileBytes | number | 20 MiB | Maximum input size checked before an opened file is read.打开文件前检查的最大输入字节数。 |
onReady | (editor: KJDrawEditor) => void | — | Called after the initial drawing and renderer are ready.初始图档与渲染器就绪后调用。 |
onChange | (event: KJDrawWorkbenchChange) => void | — | Receives the document, revision and entity count after a drawing change.图档变化后接收 document、revision 与 entityCount。 |
onSelectionChange | (event: KJDrawEditorSelectionEvent) => void | — | Receives the active document and selected object IDs.接收活动图档与已选对象 ID。 |
onError | (error: unknown) => void | — | Receives initialization, file and command errors.接收初始化、文件与命令错误。 |
Properties#
Read current editor state and reach lower-level integration points when needed.读取当前编辑器状态,并在需要时进入更底层的集成入口。
| Property | Type | Purpose用途 |
|---|---|---|
ready | Promise<KJDrawEditor> | Resolves after the initial drawing is mounted and fitted.初始图档完成挂载和适配后 resolve。 |
element | HTMLElement | Mounted editor root element.已挂载的编辑器根元素。 |
document | KJDocument | null | Current drawing after ready resolves.ready 完成后的当前图档。 |
sdk | KJDrawSDK | SDK used by the editor. Register plugins here; use editor.execute() or pass a document explicitly for commands when several editors share this SDK.编辑器使用的 SDK,可在此注册插件。多个编辑器共享时,使用 editor.execute() 或显式指定 document 来确定命令操作的图纸。 |
workbench | KJDrawWorkbench | Advanced workbench access for custom tools and renderer integration.面向自定义工具与渲染集成的高级工作台入口。 |
locale | 'en' | 'zh-CN' | Current UI language.当前界面语言。 |
theme | 'dark' | 'light' | Current appearance.当前外观。 |
layout | 'classic' | 'compact' | 'focus' | Current workbench arrangement.当前工作台布局。 |
disposed | boolean | Whether dispose() has released the editor.dispose() 是否已释放编辑器。 |
Methods#
File operations and edits that return promises can be awaited in application workflows.文件操作与返回 Promise 的编辑方法可直接纳入应用异步流程。
| Method | Parameters参数 | Returns返回 | Purpose用途 |
|---|---|---|---|
open(source, options?) | Blob | string | ArrayBuffer | ArrayBufferView; KJWorkbenchOpenOptions | Promise<KJDocument> | Open DXF or KJD content. File names can supply format detection.打开 DXF 或 KJD 内容;可通过文件名自动识别格式。 |
save(options?) | KJDrawEditorSaveOptions | Promise<string | Uint8Array> | Save KJD by default or DXF when selected. Set download:false to handle the result yourself.默认保存 KJD,也可选择 DXF;设 download:false 后自行处理结果。 |
execute(command, args?) | string; KJCommandArguments | Promise<KJSDKCommandEnvelopeReceipt<T>> | Run a command against the current drawing and receive its revisioned receipt.对当前图档执行命令并获得带修订信息的回执。 |
undo() | — | Promise<KJSDKCommandEnvelopeReceipt> | Undo the most recent committed transaction.撤销最近一次已提交事务。 |
redo() | — | Promise<KJSDKCommandEnvelopeReceipt> | Redo the next transaction in session history.重做当前会话历史中的下一项事务。 |
fit() | — | KJDrawEditor | Fit the active drawing to the current viewport.将活动图档适配到当前视口。 |
setDocument(drawing) | KJDocument | Promise<KJDrawEditor> | Attach and activate an existing document.挂接并激活一个现有图档。 |
setSelection(ids) | readonly string[] | Promise<readonly string[]> | Replace selection through the serialized command queue and return the accepted IDs.通过串行命令队列替换选择集,并返回已接受的 ID。 |
getSelection() | — | readonly string[] | Read the current selected object IDs.读取当前已选对象 ID。 |
setTheme(theme) | 'dark' | 'light' | KJDrawEditor | Switch panel and canvas appearance immediately.立即切换面板与画布外观。 |
setLayout(layout) | 'classic' | 'compact' | 'focus' | KJDrawEditor | Switch workbench chrome in place without replacing the editor, drawing or undo history. Available since 1.0.0-rc.3.原位切换工作台界面,不替换编辑器、图档或撤销历史。自 1.0.0-rc.3 起提供。 |
setLocale(locale) | 'en' | 'zh-CN' | KJDrawEditor | Switch workbench language immediately.立即切换工作台语言。 |
setTool(tool) | KJWorkbenchTool | KJDrawEditor | Activate select, pan, move, copy or measure; drawing tools include line, polyline, circle, arc, ellipse, rectangle, polygon, spline, hatch, dimension, point, ray, xline and text. Configure construction modes in the workbench Drawing options dialog.启用 select、pan、move、copy、measure,或 line、polyline、circle、arc、ellipse、rectangle、polygon、spline、hatch、dimension、point、ray、xline、text 绘图工具。构造方式可在工作台绘图参数对话框中设置。 |
setTitle(title) | string | KJDrawEditor | Update the title displayed above the drawing.更新图档上方显示的标题。 |
setOptions(options) | Pick<KJDrawEditorOptions, 'layout' | 'readonly' | 'grid' | 'toolbar' | 'layers' | 'properties' | 'title' | 'maxFileBytes'> | KJDrawEditor | Update layout, editor chrome, editing mode and file-size limit without replacing the drawing or its undo history.原位更新布局、编辑器界面、编辑模式与文件大小限制,不替换图档或撤销历史。 |
on(name, listener) | keyof KJDrawEditorEvents; listener | () => boolean | Subscribe to an editor event and receive an unsubscribe function.订阅编辑器事件,并获得取消订阅函数。 |
dispose() | — | void | Unmount and release listeners and renderer resources. Safe to call twice.卸载并释放监听与渲染资源;可安全重复调用。 |
Events#
Use constructor callbacks for common events or editor.on() for every event.常用事件可通过初始化回调处理,全部事件都可用 editor.on() 订阅。
const off = editor.on('selectionchange', ({ ids }) => {
console.log(ids)
})
// Later
off()
| Event | Payload | Callback快捷回调 | When触发时机 |
|---|---|---|---|
ready | KJDrawEditor | onReady | Initial drawing and renderer are ready.初始图档与渲染器已经就绪。 |
change | { document, revision, entityCount } | onChange | A drawing change has committed.一次图档变更已提交。 |
selectionchange | { document, ids } | onSelectionChange | The selected object IDs changed.已选对象 ID 发生变化。 |
documentchange | { document } | editor.on() | Open or setDocument activated another drawing.open 或 setDocument 激活了另一张图档。 |
error | unknown | onError | Initialization, file or queued command failed.初始化、文件操作或队列命令失败。 |
dispose | undefined | editor.on() | The editor released its mounted resources.编辑器已释放挂载资源。 |
React / Vue#
React
import { useRef, useState } from 'react'
import { KJDraw, type KJDrawEditor, type KJWorkbenchLayout } from '@kanjieteam/kjdraw/react'
export function DrawingEditor() {
const editor = useRef<KJDrawEditor | null>(null)
const [layout, setLayout] = useState<KJWorkbenchLayout>('classic')
async function moveSelection() {
const instance = editor.current
const ids = instance?.getSelection() ?? []
if (!instance || !ids.length) return
await instance.execute('MOVE', { ids, dx: 10, dy: 0 })
}
return (
<>
<button onClick={() => setLayout('focus')}>Focus drawing</button>
<button onClick={() => void moveSelection()}>Move selected</button>
<KJDraw ref={editor} document="sample" layout={layout} style={{ height: 720 }} />
</>
)
}Vue
<script setup lang="ts">
import { ref } from 'vue'
import { KJDraw, type KJDrawExposed, type KJWorkbenchLayout } from '@kanjieteam/kjdraw/vue'
const editor = ref<KJDrawExposed | null>(null)
const layout = ref<KJWorkbenchLayout>('classic')
async function moveSelection() {
const instance = editor.value
const ids = instance?.getSelection() ?? []
if (!instance || !ids.length) return
await instance.execute('MOVE', { ids, dx: 10, dy: 0 })
}
</script>
<template>
<button @click="layout = 'focus'">Focus drawing</button>
<button @click="moveSelection">Move selected</button>
<KJDraw ref="editor" document="sample" :layout="layout" style="height: 720px" />
</template>