KJDrawEditor API

@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.3

Quickstart快速接入

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选项TypeDefault默认值Purpose用途
documentKJDocument | 'sample' | 'blank' | nullactive SDK document or 'sample'Initial drawing. 'sample' opens the included example; 'blank' and null create an empty drawing.初始图档。'sample' 打开内置示例;'blank' 与 null 创建空白图档。
sdkKJDrawSDKnew SDKReuse 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 起提供。
readonlybooleanfalseKeep inspection, navigation and export while disabling editing controls.保留检查、导航与导出,同时禁用编辑控件。
gridbooleantrueShow the drawing grid initially.初始显示绘图网格。
toolbarbooleantrueShow the ribbon toolbar.显示 Ribbon 工具栏。
layersbooleantrueShow the layers panel.显示图层面板。
propertiesbooleantrueShow the properties inspector.显示属性检查器。
titlestringdrawing IDOverride the drawing title displayed in the workbench header.覆盖工作台顶部显示的图档标题。
maxFileBytesnumber20 MiBMaximum input size checked before an opened file is read.打开文件前检查的最大输入字节数。
onReady(editor: KJDrawEditor) => voidCalled after the initial drawing and renderer are ready.初始图档与渲染器就绪后调用。
onChange(event: KJDrawWorkbenchChange) => voidReceives the document, revision and entity count after a drawing change.图档变化后接收 document、revision 与 entityCount。
onSelectionChange(event: KJDrawEditorSelectionEvent) => voidReceives the active document and selected object IDs.接收活动图档与已选对象 ID。
onError(error: unknown) => voidReceives initialization, file and command errors.接收初始化、文件与命令错误。

Properties

Read current editor state and reach lower-level integration points when needed.读取当前编辑器状态,并在需要时进入更底层的集成入口。

PropertyTypePurpose用途
readyPromise<KJDrawEditor>Resolves after the initial drawing is mounted and fitted.初始图档完成挂载和适配后 resolve。
elementHTMLElementMounted editor root element.已挂载的编辑器根元素。
documentKJDocument | nullCurrent drawing after ready resolves.ready 完成后的当前图档。
sdkKJDrawSDKSDK 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 来确定命令操作的图纸。
workbenchKJDrawWorkbenchAdvanced 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.当前工作台布局。
disposedbooleanWhether dispose() has released the editor.dispose() 是否已释放编辑器。

Methods

File operations and edits that return promises can be awaited in application workflows.文件操作与返回 Promise 的编辑方法可直接纳入应用异步流程。

MethodParameters参数Returns返回Purpose用途
open(source, options?)Blob | string | ArrayBuffer | ArrayBufferView; KJWorkbenchOpenOptionsPromise<KJDocument>Open DXF or KJD content. File names can supply format detection.打开 DXF 或 KJD 内容;可通过文件名自动识别格式。
save(options?)KJDrawEditorSaveOptionsPromise<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; KJCommandArgumentsPromise<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()KJDrawEditorFit the active drawing to the current viewport.将活动图档适配到当前视口。
setDocument(drawing)KJDocumentPromise<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'KJDrawEditorSwitch panel and canvas appearance immediately.立即切换面板与画布外观。
setLayout(layout)'classic' | 'compact' | 'focus'KJDrawEditorSwitch 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'KJDrawEditorSwitch workbench language immediately.立即切换工作台语言。
setTool(tool)KJWorkbenchToolKJDrawEditorActivate 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)stringKJDrawEditorUpdate the title displayed above the drawing.更新图档上方显示的标题。
setOptions(options)Pick<KJDrawEditorOptions, 'layout' | 'readonly' | 'grid' | 'toolbar' | 'layers' | 'properties' | 'title' | 'maxFileBytes'>KJDrawEditorUpdate layout, editor chrome, editing mode and file-size limit without replacing the drawing or its undo history.原位更新布局、编辑器界面、编辑模式与文件大小限制,不替换图档或撤销历史。
on(name, listener)keyof KJDrawEditorEvents; listener() => booleanSubscribe to an editor event and receive an unsubscribe function.订阅编辑器事件,并获得取消订阅函数。
dispose()voidUnmount 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()
EventPayloadCallback快捷回调When触发时机
readyKJDrawEditoronReadyInitial drawing and renderer are ready.初始图档与渲染器已经就绪。
change{ document, revision, entityCount }onChangeA drawing change has committed.一次图档变更已提交。
selectionchange{ document, ids }onSelectionChangeThe selected object IDs changed.已选对象 ID 发生变化。
documentchange{ document }editor.on()Open or setDocument activated another drawing.open 或 setDocument 激活了另一张图档。
errorunknownonErrorInitialization, file or queued command failed.初始化、文件操作或队列命令失败。
disposeundefinededitor.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 }} />
    </>
  )
}

React guideReact 指南

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>

Vue guideVue 指南

Advanced access高级入口