1.0.1 • Published 2 months ago

@starzhuimeng/formula-editor v1.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
2 months ago

Formula Editor

一个基于TypeScript的数学公式编辑器,支持公式编辑、验证和展示功能。

功能特点

  • 直观的公式编辑器界面
  • 支持各种数学符号和函数
  • 自定义符号配置
  • 公式验证功能
  • 可自定义样式

安装

npm install formula-editor

基本使用

import { FormulaEditor } from 'formula-editor';

// 创建编辑器实例
const editor = new FormulaEditor({
  container: document.getElementById('editor-container')
});

配置选项

const editor = new FormulaEditor({
  container: document.getElementById('editor-container'),
  initialFormula: 'a+b=c',
  readOnly: false,
  symbols: {
    basic: ['+', '-', '×', '÷', '='],
    greek: ['α', 'β', 'γ']
  },
  styles: {
    fontSize: '16px',
    color: '#333',
    backgroundColor: '#fff'
  },
  validation: {
    autoValidate: true,
    rules: [
      { type: 'bracketsMatch', message: '括号不匹配' },
      { type: 'operatorsSurrounded', message: '运算符两侧必须有操作数' }
    ]
  }
});

API参考

基本操作

// 设置公式
editor.setFormula('x^2+y^2=z^2');

// 获取公式
const formula = editor.getFormula();

// 清空编辑器
editor.clear();

// 设置只读模式
editor.setReadOnly(true);

元素操作API

// 获取所有公式元素
const elements = editor.getFormulaElements();

// 获取指定位置的元素
const element = editor.getElementAt(2);

// 在指定位置插入元素
editor.insertElement({
  type: 'number',
  value: '42'
}, 3);

// 更新指定位置的元素
editor.updateElement(1, {
  value: '×',
  type: 'operator'
});

// 删除指定位置的元素
editor.removeElement(4);

// 添加元素到末尾
editor.appendElement({
  type: 'variable',
  value: 'x'
});

// 查找符合条件的元素
const operators = editor.findElements((el) => el.type === 'operator');

// 设置焦点到指定位置
editor.setFocusToIndex(2);

// 获取当前焦点位置
const focusIndex = editor.getCurrentFocusIndex();

// 批量设置元素
editor.setElements([
  { type: 'variable', value: 'a' },
  { type: 'operator', value: '+' },
  { type: 'variable', value: 'b' }
]);

// 复制元素到剪贴板
editor.copyElement(3);

// 获取公式的纯文本表示
const text = editor.getFormulaText();

// 删除当前选中的元素
editor.deleteCurrentElement();

验证相关

// 验证公式
const result = editor.validateFormula();

// 获取最近一次验证结果
const lastResult = editor.getLastValidationResult();

// 设置验证规则
editor.setValidationRules([
  { type: 'bracketsMatch', message: '括号不匹配' }
]);

// 设置自动验证
editor.setAutoValidate(true);

// 设置自定义验证器
editor.setCustomValidator((formula, elements) => {
  // 自定义验证逻辑
  return {
    valid: true,
    errors: []
  };
});

事件监听

// 添加变更事件监听
editor.addEventListener('change', (formula) => {
  console.log('Formula changed:', formula);
});

// 添加验证错误事件监听
editor.addEventListener('validationError', (errors) => {
  console.log('Validation errors:', errors);
});

// 移除事件监听
editor.removeEventListener('change', callback);

自定义符号

const editor = new FormulaEditor({
  container: document.getElementById('editor-container'),
  symbols: {
    basic: [
      { value: '+', type: 'operator', description: '加法' },
      { value: '-', type: 'operator', description: '减法' }
    ],
    customGroup: {
      name: 'customGroup',
      displayName: '自定义符号',
      symbols: [
        { value: '∑', type: 'symbol', description: '求和' },
        { value: '∏', type: 'symbol', description: '求积' }
      ],
      style: {
        backgroundColor: '#f0f0f0',
        color: '#333',
        fontWeight: 'bold'
      }
    }
  }
});

许可证

MIT

ababacceptsacornacorn-globalsacorn-jsxacorn-walkagent-baseajvajv-formatsansi-escapesansi-html-communityansi-regexansi-stylesanymatchargparsearray-flattenarray-unionasyncasynckitbabel-jestbabel-plugin-istanbulbabel-plugin-jest-hoistbabel-preset-current-node-syntaxbabel-preset-jestbalanced-matchbasic-authbatchbinary-extensionsbody-parserbonjour-serviceboolbasebrace-expansionbracesbrowserslistbs-loggerbserbuffer-frombytescall-bind-apply-helperscall-boundcallsitescamel-casecamelcasecaniuse-litechalkchar-regexchokidarchrome-trace-eventci-infocjs-module-lexerclean-csscliuiclone-deepcocollect-v8-coveragecolor-convertcolor-namecolorettecombined-streamcommandercompressiblecompressionconcat-mapconnect-history-api-fallbackcontent-dispositioncontent-typeconvert-source-mapcookiecookie-signaturecopy-webpack-plugincore-util-iscorsercreate-jestcross-spawncss-selectcss-whatcssomcssstyledata-urlsdebugdecimal.jsdedentdeep-isdeepmergedefault-gatewaydefine-lazy-propdelayed-streamdepddestroydetect-newlinedetect-nodediff-sequencesdir-globdns-packetdoctrinedom-converterdom-serializerdomelementtypedomexceptiondomhandlerdomutilsdot-casedunder-protoee-firstejselectron-to-chromiumemitteryemoji-regexencodeurlenhanced-resolveentitiesenvinfoerror-exes-define-propertyes-errorses-module-lexeres-object-atomses-set-tostringtagescaladeescape-htmlescape-string-regexpescodegeneslint-scopeeslint-visitor-keysespreeesprimaesqueryesrecurseestraverseesutilsetageventemitter3eventsexecaexitexpectexpressfast-deep-equalfast-globfast-json-stable-stringifyfast-levenshteinfast-urifastest-levenshteinfastqfaye-websocketfb-watchmanfile-entry-cachefilelistfill-rangefinalhandlerfind-upflatflat-cacheflattedfollow-redirectsform-dataforwardedfreshfs-monkeyfs.realpathfunction-bindgensyncget-caller-fileget-intrinsicget-package-typeget-protoget-streamglobglob-parentglob-to-regexpglobalsglobbygopdgraceful-fsgraphemerhandle-thinghas-flaghas-symbolshas-tostringtaghasownhehpack.jshtml-encoding-snifferhtml-entitieshtml-escaperhtml-minifier-terserhtmlparser2http-deceiverhttp-errorshttp-parser-jshttp-proxyhttp-proxy-agenthttp-proxy-middlewarehttp-serverhttps-proxy-agenthuman-signalsiconv-liteignoreimport-freshimport-localimurmurhashinflightinheritsinterpretipaddr.jsis-arrayishis-binary-pathis-core-moduleis-dockeris-extglobis-fullwidth-code-pointis-generator-fnis-globis-numberis-path-insideis-plain-objis-plain-objectis-potential-custom-element-nameis-streamis-wslisarrayisexeisobjectistanbul-lib-coverageistanbul-lib-instrumentistanbul-lib-reportistanbul-lib-source-mapsistanbul-reportsjakejest-changed-filesjest-circusjest-clijest-configjest-diffjest-docblockjest-eachjest-environment-nodejest-get-typejest-haste-mapjest-leak-detectorjest-matcher-utilsjest-message-utiljest-mockjest-pnp-resolverjest-regex-utiljest-resolvejest-resolve-dependenciesjest-runnerjest-runtimejest-snapshotjest-utiljest-validatejest-watcherjest-workerjs-tokensjs-yamljsdomjsescjson-bufferjson-parse-even-better-errorsjson-schema-traversejson-stable-stringify-without-jsonifyjson5keyvkind-ofkleurlaunch-editorlevenlevnlines-and-columnsloader-runnerlocate-pathlodashlodash.memoizelodash.mergelower-caselru-cachemake-dirmake-errormakeerrormath-intrinsicsmedia-typermemfsmerge-descriptorsmerge-streammerge2methodsmicromatchmimemime-dbmime-typesmimic-fnminimalistic-assertminimatchminimistmsmulticast-dnsnatural-comparenegotiatorneo-asyncno-casenode-forgenode-int64node-releasesnormalize-pathnpm-run-pathnth-checknwsapiobject-inspectobufon-finishedon-headersonceonetimeopenopeneroptionatorp-limitp-locatep-retryp-tryparam-caseparent-moduleparse-jsonparse5parseurlpascal-casepath-existspath-is-absolutepath-keypath-parsepath-to-regexppath-typepicocolorspicomatchpiratespkg-dirportfinderprelude-lspretty-errorpretty-formatprocess-nextick-argspromptsproxy-addrpslpunycodepure-randqsquerystringifyqueue-microtaskrandombytesrange-parserraw-bodyreact-isreadable-streamreaddirprechoirrelateurlrenderkidrequire-directoryrequire-from-stringrequires-portresolveresolve-cwdresolve-fromresolve.exportsretryreusifyrimrafrun-parallelsafe-buffersafer-buffersaxesschema-utilssecure-compareselect-hoseselfsignedsemversendserialize-javascriptserve-indexserve-staticsetprototypeofshallow-cloneshebang-commandshebang-regexshell-quoteside-channelside-channel-listside-channel-mapside-channel-weakmapsignal-exitsisteransislashsockjssource-mapsource-map-supportspdyspdy-transportsprintf-jsstack-utilsstatusesstring-lengthstring-widthstring_decoderstrip-ansistrip-bomstrip-final-newlinestrip-json-commentssupports-colorsupports-preserve-symlinks-flagsymbol-treetapableterserterser-webpack-plugintest-excludetext-tablethunkytmplto-regex-rangetoidentifiertough-cookietr46ts-api-utilstslibtype-checktype-detecttype-festtype-isundici-typesunionuniversalifyunpipeupdate-browserslist-dburi-jsurl-joinurl-parseutil-deprecateutilautils-mergeuuidv8-to-istanbulvaryw3c-xmlserializerwalkerwatchpackwbufwebidl-conversionswebpack-dev-middlewarewebpack-mergewebpack-sourceswebsocket-driverwebsocket-extensionswhatwg-encodingwhatwg-mimetypewhatwg-urlwhichwildcardword-wrapwrap-ansiwrappywrite-file-atomicwsxml-name-validatorxmlcharsy18nyallistyargsyargs-parseryocto-queue
1.0.1

2 months ago

1.0.0

2 months ago