AIStoreHub Package Vault: Univer
Package Slug: univer
Archetype: agent
Upstream Repository: https://github.com/dream-num/univer
Workspace Files & Specifications (66 files)
- aistorehub.json (556 bytes)
{ "name": "Univer", "slug": "univer", "version": "1.0.0", "type": "agent", "description": "Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.", "owner": "community", "repository": "catalog", "github_repo_url": "https://github.com/dream-num/univer", "tags": [ "trending", "typescript", "github", "open-source", "dream-num" ], "imported_at": "2026-11-21T23:56:37.968Z" } - CODE_OF_CONDUCT.md (3247 bytes)
# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: - Using welcoming and inclusive language - Being respectful of differing viewpoints and experiences - Gracefully accepting constructive criticism - Focusing on what is best for the community - Showing empathy towards other community members Examples of unacceptable behavior by participants include: - The use of sexualized language or imagery and unwelcome sexual attention or advances - Trolling, insulting/derogatory comments, and personal or political attacks - Public or private harassment - Publishing others' private information, such as a physical or electronic address, without explicit permission - Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [[email protected]](mailto:[email protected]). The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]. [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/
- codecov.yml (330 bytes)
coverage: status: project: default: # basic target: 80% threshold: 0 base: auto # advanced settings if_ci_failed: error informational: false only_pulls: false patch: off - commitlint.config.cjs (67 bytes)
module.exports = { extends: ['@commitlint/config-conventional'] }; - common/debugger/package.json (1573 bytes)
{ "name": "@univerjs/debugger", "version": "1.5.0", "private": true, "description": "", "author": "DreamNum <[email protected]>", "license": "Apache-2.0", "funding": { "type": "opencollective", "url": "https://opencollective.com/univer" }, "homepage": "https://univer.ai", "repository": { "type": "git", "url": "https://github.com/dream-num/univer" }, "bugs": { "url": "https://github.com/dream-num/univer/issues" }, "keywords": [], "exports": { ".": "./src/index.ts", "./*": "./src/*" }, "main": "./src/index.ts", "scripts": { "typecheck": "tsrs --noEmit" }, "peerDependencies": { "react": "^16.9.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc", "rxjs": ">=7.0.0" }, "dependencies": { "@univerjs/core": "workspace:*", "@univerjs/design": "workspace:*", "@univerjs/docs-drawing-ui": "workspace:*", "@univerjs/engine-render": "workspace:*", "@univerjs/icons": "1.47.0", "@univerjs/sheets": "workspace:*", "@univerjs/sheets-drawing-ui": "workspace:*", "@univerjs/themes": "workspace:*", "@univerjs/ui": "workspace:*", "@univerjs/watermark": "workspace:*" }, "devDependencies": { "@univerjs-infra/shared": "workspace:*", "postcss": "^8.5.32", "react": "18.3.1", "rxjs": "7.8.2", "tailwindcss": "3.4.18", "tsrs": "0.23.0-ts7.1.0-beta", "vue": "^3.5.42" } } - common/debugger/postcss.config.mjs (58 bytes)
export { default } from '@univerjs-infra/shared/postcss'; - common/debugger/README.md (985 bytes)
# @univerjs/debugger > [!CAUTION] > NEVER use this plugin in your production environment! ## Package Overview | Package Name | UMD Namespace | Version | License | Downloads | Contains CSS | Contains i18n locales | | --- | --- | --- | --- | --- | :---: | :---: | | `@univerjs/debugger` | `UniverDebugger` | [![][npm-version-shield]][npm-version-link] | ![][npm-license-shield] | ![][npm-downloads-shield] | ⭕️ | ❌ | ## Introduction > This plugin provides a lot of utilities to help you debug Univer. ## Usage ### Installation ```shell # Using npm npm install @univerjs/debugger # Using pnpm pnpm add @univerjs/debugger ``` <!-- Links --> [npm-version-shield]: https://img.shields.io/npm/v/@univerjs/debugger?style=flat-square [npm-version-link]: https://npmjs.com/package/@univerjs/debugger [npm-license-shield]: https://img.shields.io/npm/l/@univerjs/debugger?style=flat-square [npm-downloads-shield]: https://img.shields.io/npm/dm/@univerjs/debugger?style=flat-square
- common/debugger/src/components/FloatButton.tsx (1924 bytes)
export const FloatButton = () => { const divStyle = { width: '100px', height: '30px', backgroundColor: '#fff', border: '1px solid #ccc', display: 'flex', justifyContent: 'center', alignItems: 'center', textAlign: 'center' as const, }; const clickHandler = () => { console.warn('click'); }; return ( <div style={divStyle} onClick={clickHandler}> FloatButton </div> ); }; export const AIButton = () => { const divStyle = { width: '80px', height: '50px', backgroundColor: '#fff', display: 'flex', justifyContent: 'center', alignItems: 'center', textAlign: 'center' as const, borderRadius: '25px', border: 'none', color: 'white', cursor: 'pointer', transition: 'all 0.3s ease', background: 'linear-gradient(90deg, #00C9FF 0%, #92FE9D 50%, #00C9FF 100%)', backgroundSize: '200% auto', animation: 'gradient 3s linear infinite', ':hover': { transform: 'translateY(-2px)', boxShadow: '0 10px 20px rgba(0, 201, 255, 0.3)', }, }; const clickHandler = () => { console.warn('click'); }; return ( <button type="button" style={divStyle} onClick={clickHandler}> AI <style> {` @keyframes gradient { 0% { background-position: 0% 50%; } 50% { background-position: 100% 50%; } 100% { background-position: 0% 50%; } } button:hover { transform: translateY(-2px); box-shadow: 0 10px 20px rgba(0, 201, 255, 0.3); } `} </style> </button> ); }; - common/debugger/src/components/Image.tsx (5401 bytes)
const image = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxITEBUSExMWFhIVFhIXEhYYFRUWGBYYFRUWFhUWGBUYHyghGB4lGxYVJDEhJSktLi4uGh8zODMsNyktLisBCgoKDg0OGxAQGysgHSYrLS03Ky4tKzctKy8tNysvLS83LS0tLS0rLS0rLS0tLS0vLTItLTc1LS0tLS0tNS0tLf/AABEIASsAqAMBIgACEQEDEQH/xAAcAAEAAgMBAQEAAAAAAAAAAAAABQYDBAcCAQj/xAA8EAACAQIEAggEAgoCAwEAAAAAAQIDEQQFEiExQQYTIjJRYXGRB4GhwUKxFCMzUmJygpLR4UPwFlPCFf/EABkBAQADAQEAAAAAAAAAAAAAAAABAwQFAv/EADERAQACAgEDAQQIBwEAAAAAAAABAgMRBBIhMQUTIjJRQWFxgZGxwdEUJDNSoeHwI//aAAwDAQACEQMRAD8A7iAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQ+n3TupgMRTpRpRlF0+slqbTktbi4wtwasvHvIm+nU8asI5YG7rKUW0lFycN9Shq2vw89nY4Zm/SbFYpwoY2Fq1GU3GpOm6VWMZLS6bWyalZPh+FEwiX6DwudUZ4WOL1qNCUFPVLbSmuD809reJ9ybOsPioOdCoqkYvTK100+Nmmk1sfmfE59Wjhlg6c5dU5a+rW61KV9lx4q9vHfidw+FPRCeAw0pVp6q+IcZ1Eu7Cy7MF4tXd34+gnW9QRteAeKk7f9+pS+kXTejRm6VNSr1ucYq9vXkvmNEzpcq2IjFXk0jSnnMOSk/kl+bKDHpRiZbywclH+GS1L8vzJDC5vGotUbu3ei1acfW/H5+5m5Fc+t4ph6pfHv3lr/8A2o/uS+hlp5xTfG8fVf4uV/D1FOyju3yPmOxNOku3JX8Lo5mDkc3JMxWN6+cNN64qx3W2lWjJXi0/RmQ59h8+pN9iSv4xnv8AcsmV5/GTUZvd8G9vf/J1aXyR/Urr648M09M/DKdABcgAILPel2DwlSFOvVUZz02Vm9Kk7Jyt3Vfx8wJ0AAAAAAAAgulnRTD4+l1dZNSX7OpGynB+Ta3XinsToA/Lue5K8LXr4aEnUq0aqSmovXJaYyi7Ju20l7H6C6B4+vWy+jUxEHCrps7uLc0tlPZu11ye9zPn2Ag0p6VqTabsr9rz+SMHRis4wqUrX6uTlBeUt7f3avcxfxcxyfYWjtrcSu9lHs+uPKO6fZ1PDYKpOO9ScnGn6ylpgiP6CdFYQpqc+1J7yb4zlzbZpdO6kquBjUa7VKpTnUXgozvL2T+hduj9WLw9Nx4OKfub/oZfMsWcZvhcIoqrJRv3UoSk/aKdjQrUsPiKaxFBxls7SjztxjJfZ8DnfxL/AEn9MnSlU0QlUVSlrk4wlFwhG8ZcLxas1x9y19AMLKFCrJ/s6k46G7rXpgozqpPgm1bz03Kq5N26Xua9tsOY508JQm0u03ZW4tvZRXqzRyPohUxT63Eycm97Pux8ox5+prZ/aeIw6fddacvmovT+Zv8AxAzd0ofo0YyShTpTTjOUb6taepR7y2RbM9MPFK9Up2p0Bwum2l35NWTXpsRtfKJ4d2cnOn+GT70fJvn6mP4YZrWm3Sm24Ok6kYybbg4zUNm99Mk728UW3N6acWmRW3U9ZMfT2fejWaa49XJ9pLbztxX3JDPHW/Rq36Pbr+rqdTf9/S9P1scozLNpYacMTvppapTinZy3p7W57X9zrmCx9OrRhXhJOlOEakZctMo6k/LY8xXp7Ji3VDhHQf4m4nD16sMX1lSnZpwm/wBZTqx5drgnwa5EDUxSx+ZRqYuqqdGc3Vry7VlCHdpwSTd2kor3MPxOz2hjMxqYjDx0wSjDWn+2cLrrbW28Fxuopm50F+HuKzGUZy1UcLZXqtbzXJUovvfzcF58D39HdGnbejvT/BYzEfo1GU+s0SnHVDSpRja9vDitnYtZWeiXQXBZfeVCDdVrTKrOWqbWzaT4RV0tklwLMeXoAAAAAAABgx1PVTkvLb1W6Kth8T1VfVylCUfna8fqrfMuBS86tTqb8FJ+3FfQ43qlLxemTHHfx/3+WvjWr3rbwx4mg2nspXVpRfCS8Nzz0YxaoQ6m94RfYT2lBfuu/G3jxNuLTV1wZG5hSXC0W+Slxt5NNMp4PqcY6+zy7+1GXjTa3VRZ62OpuPas1x3St67lczvPU4yjTa2T1zbtCEebcnwIWtflSjf+KdVr+3UvzIbMcvq1lpqSvBbqnFKMF56Vxfm7s6F/VOPWPdnauvDy2nv2bE5xxFGM6VRTtPVSnZxWuHGLT3js3x5NMulfKsNmFKnOpqjVgrKUXpnG/ei+Kkr8ndcyi5Tlc6EnoV4yt1kH3ZW4ejV3ZonqGIcO7UcP4aie3pOKafzse8PPw546ZnU/KXnJxsmGd18LflOU0cLGWjU5StrnOWqUrcFfgkt9kkt2+ZG5/majFpO8ntFLjvsQ2Jzidt61L+mTm/7Yps0YycndXbfGctnvxUI/h9Xv4WLsmfDgruZj7IVxTJlt9P2q1n+Fq1OuhsrRhGN77yc9dTdK1laMf6WdM6KY6WFyTDyqpKcKahFJ31NScKe/mkm/Dcrjw6saGLzd1Y0cNF9jDp6/Oo27+0Wl6tnLj1O94tOtduzbHErXUfi163w3pZhWlKEnQm1KdWcYpxcpX/Bsrtt8Lczs+Dw8adOFOO0YRjGPpFJL8iM6K5f1WHV1259qX/yvb82TJ0eHW9cMRedyz5pibzoABpVAAAAAAAABVemWG2cl4J+2z+li1ERny7vz+xm5V/Z09p/bMS9Vr1e781UyPGXWh/0/dEJ8RsRiMLBY3DQpycYypVtcNemE2mprdWtJcfM3cVT6mrtwlvF8k+X+Ccw9aNWm4ySaacZxdnx4prmjlcnHGDNXk4u9Ld/3hdhvN6zjt8Udv9uOYf4o1NCjUwtOU0ra4TnTv5uLUlf0sSOD+JmH0rrKNWM7drTonG/k9Sdvkb2dfCWm6jnh6mmD36qT7v8ALLw8n7lXx/w0xke5By+cX9zXFuFmjc6/KVla5o+GVny74lYOd+sUqVn2dUJSuuT7F7Py+pvf+cZfOWnr4ra+pwqKPpdx4nPqfw5zB/8ADb1lFfcnsm+FFRyUsVWjGPOFK8pPyc2ko/JMz5MXp1O8zH3TP7vXVyfH7LZlObUsTKfVdqENK6xd2Td20vNbe6JOVkZsLl9KhSjSpQUKcVsl9W3zb8SAz/HveEHZ23l4ehzMeGeVn6MFdR+TRbJGHH1ZJfcZnCjLRCzkuPgvLzfkbXQrKutxTuuy5uc/Rbv3e3zK/kWVSnPVLaC935f7OrdCMAoRqTS7zsvRbv6v6HbtxcGO9cFO9ondp/Rhpmy2iclu0T4j9VmR9AOmzgAAAAAAAAAAETnv4fn9iWIzPV2Ivz/Nf6MnOjeCyzF8cKzmtBSpu/FJtHP8rx9dv9cmql7LbTslvez3SeyfP8uh5i/1U/Qp0qNm342+duC8vQeg7thtE+Iln9RmK3jXmYe1mE4LvterPlbOavFVHa37zf3MVu007cFtf15H1YGm76kk/OP3sducGK3msT90OdGS8eLSVM+rWvqu/cxrO621n67X28DXrYOG9or2X0NOMktfBdrZXSXdjtZedzx/AcW3nHX8Ie45GWPFpZM66T1acYt76tW2ytbi2/G3BcXc9ZVhnUtJ91re/maFeipxatHezV1smn3lfnbYtOU0VGnFeC8b/U5/qMxwcMzgrFeqddobuL/M3j2kzOm9hoJJJHQuj9O2Hh5pv3bZz+B0nAU9NKEfCEV9Ecf0qJm9rS6PK8RDYAB22IAAAAAAAAAAArXTmc40aco3sqkVKztZST7T8bfcspq5nglWpSpvhJbPwa3T97ExET8UbhFt67eXMq+aSkpQvx2+SNTS7b2b/wC8TzmGFlQnKM7qor7Phbxj438TQeM8eBtwYceOP/OIiJ+TmZb3tPvztmrztulvdqz5mvPGS4aJP0advqJ4uDVtzzFxve/yu7mhXDFLESttB78G2kvzZ6oU2lZq7d22vO/I8SqxfFvnzMUqsbbP6cD1A91HpV3ZLwe7fyNiGZzjddnZpbJrkn4+Zp06sGrS3e139jXxMNUnPU4u1pbak7cOzdblOfj4s0RXJG4XYcl8czNZ1Kcp4+bmopyu1eNrcbpJcOLudnwGvqqfWftNEOstw1aVqt87nNvh1kEqs44morUob09ra5rml4L87eZ1E598WLHPTjjTdjte0bvOwAHlYAAAAAAAAAAAAAI3Osko4mOmpHdd2S2lH0f2OeZz8PMTC8qEo1VyTahP69l+51W55cj3TJavh4tjrby/NucYqeHn1WIpTpy8JRav5p815o0qedUV+PnzX+jonxn6SZbUoSwrqasXTkpQ0QctD/FCU+Cur7XdttjhVSqvBmqOR7vdT7Gu1yedULbSV/mYqmfQ4atvmVTaKg731xcrW4ducLcd+7f5k50Ljh542mq8koKSajJNqcl3YtrZK9nvs7W5k15HYnDC15DkeMxaUqGHqOD4VJWp0/VSnbUv5UzovR34bRi1PGTVSX/qhdQ/qk7OXpsvU3aeZS/eNmnjW+f1K75b2+pNa1haqajFJKySSSSskkuCS5HrWvErcMV5meGIM/St6k7rXiNa8SIjWM0apGk9SS1C5oxqGSMhpO22DFBsEJZQAAAAAAAeJxNLGYWrKLUZpX8USACNOLZh8GcTVnKTxsNLlJpdQ7rU2+OsUfgRH8eLk3/DCMV9ztIJ2acZr/Aqnb9XiZRkuDcVJfNNmrH4KYtNacXR2d0+pkmvPaR3ADZpTsH0PqRilKtdpK9o8fqb8OjNv+R+xYgT1SjohC08gS/G/Y2KeUQXFtkkCNynphrQwMFyMypR8EewQnTzoXgfbH0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH//2Q=='; export const ImageDemo = () => { return <img className="univer-size-full" draggable={false} src={image} />; }; - common/debugger/src/components/RangeLoading.tsx (420 bytes)
import { borderClassName, clsx } from '@univerjs/design'; export const RangeLoading = () => { return ( <div className={clsx(` univer-flex univer-size-full univer-origin-top-left univer-items-center univer-justify-center univer-bg-gray-0 dark:!univer-bg-gray-900 `, borderClassName)} > Loading... </div> ); }; - common/debugger/src/components/WebComponent.ts (1353 bytes)
export class CounterComponent extends HTMLElement { constructor() { super(); const shadow = this.attachShadow({ mode: 'open' }); const container = document.createElement('div'); container.setAttribute('class', 'counter-container'); const countDisplay = document.createElement('span'); countDisplay.setAttribute('class', 'count-display'); countDisplay.textContent = '0'; const a = document.createElement('a'); a.textContent = '🍔'; a.addEventListener('click', (e) => { e.preventDefault(); const currentCount = Number.parseInt(countDisplay.textContent || '0', 10); countDisplay.textContent = (currentCount + 1).toString(); }); const style = document.createElement('style'); style.textContent = ` .counter-container { display: flex; flex-direction: column; align-items: center; justify-content: center; } .count-display { position: relative; top: 2px; font-size: 10px; } a { font-size: 10px; }`; shadow.appendChild(style); shadow.appendChild(container); container.appendChild(countDisplay); container.appendChild(a); } } - common/debugger/src/config/config.ts (771 bytes)
import type { ILanguagePack, LocaleType, UniverInstanceType } from '@univerjs/core'; import type { MenuConfig } from '@univerjs/ui'; export const DEBUGGER_PLUGIN_CONFIG_KEY = 'debugger.config'; export const configSymbol = Symbol(DEBUGGER_PLUGIN_CONFIG_KEY); export type UniverDebuggerLocaleLoader = (locale: LocaleType) => ILanguagePack | Promise<ILanguagePack>; export interface IUniverDebuggerConfig { menu?: MenuConfig; fab?: boolean; fabEntryUnitType: UniverInstanceType; localeLoader: UniverDebuggerLocaleLoader; performanceMonitor?: { enabled: boolean; }; } export const defaultPluginConfig: Pick<IUniverDebuggerConfig, 'fab' | 'performanceMonitor'> = { fab: true, performanceMonitor: { enabled: true, }, }; - common/debugger/src/controllers/components.controller.ts (1692 bytes)
import { Disposable, Inject } from '@univerjs/core'; import { ComponentManager } from '@univerjs/ui'; import { AIButton, FloatButton } from '../components/FloatButton'; import { ImageDemo } from '../components/Image'; import { RangeLoading } from '../components/RangeLoading'; // @ts-ignore // import VueComponent from '../components/VueComponent.vue'; // import { CounterComponent } from '../components/WebComponent'; import { WatermarkPanel } from '../views/watermark/WatermarkPanel'; import { WatermarkPanelFooter } from '../views/watermark/WatermarkPanelFooter'; export const WATERMARK_PANEL = 'WATERMARK_PANEL'; export const WATERMARK_PANEL_FOOTER = 'WATERMARK_PANEL_FOOTER'; export class ComponentsController extends Disposable { constructor( @Inject(ComponentManager) private readonly _componentManager: ComponentManager ) { super(); this._registerComponents(); } private _registerComponents(): void { ([ ['ImageDemo', ImageDemo], ['RangeLoading', RangeLoading], ['FloatButton', FloatButton], ['AIButton', AIButton], [WATERMARK_PANEL, WatermarkPanel], [WATERMARK_PANEL_FOOTER, WatermarkPanelFooter], ] as const).forEach(([key, component]) => { this.disposeWithMe(this._componentManager.register(key, component)); }); // this.disposeWithMe(this._componentManager.register('VueComponent', VueComponent, { // framework: 'vue3', // })); // this.disposeWithMe(this._componentManager.register('counter-component', CounterComponent, { // framework: 'web-component', // })); } } - common/debugger/src/controllers/debugger.controller.ts (2226 bytes)
import type { IUniverDebuggerConfig } from '../config/config'; import { Disposable, IConfigService, Inject, Injector } from '@univerjs/core'; import { BuiltInUIPart, connectInjector, IMenuManagerService, IUIPartsService, // MenuItemType, // RibbonStartGroup, } from '@univerjs/ui'; import { DEBUGGER_PLUGIN_CONFIG_KEY } from '../config/config'; import { Fab } from '../views/Fab'; import { RecordController } from './local-save/record.controller'; export class DebuggerController extends Disposable { constructor( @Inject(Injector) private readonly _injector: Injector, @IConfigService private readonly _configService: IConfigService, @IUIPartsService protected readonly _uiPartsService: IUIPartsService, @IMenuManagerService private readonly _menuManagerService: IMenuManagerService ) { super(); this._initCustomComponents(); // this._menuManagerService.mergeMenu({ // [RibbonStartGroup.OTHERS]: { // EMOJI: { // order: 9999, // menuItemFactory: () => { // return { // id: 'EMOJI', // icon: 'VueComponent', // type: MenuItemType.BUTTON, // }; // }, // }, // COUNTER: { // order: 9999, // menuItemFactory: () => { // return { // id: 'COUNTER', // icon: 'counter-component', // type: MenuItemType.BUTTON, // }; // }, // }, // }, // }); this._injector.add([RecordController]); } private _initCustomComponents(): void { const configs = this._configService.getConfig<IUniverDebuggerConfig>(DEBUGGER_PLUGIN_CONFIG_KEY); if (configs?.fab) { this.disposeWithMe( this._uiPartsService.registerComponent(BuiltInUIPart.GLOBAL, () => connectInjector(Fab, this._injector)) ); } } } - common/debugger/src/controllers/local-save/record.controller.ts (2274 bytes)
import { CommandType, ICommandService, Inject } from '@univerjs/core'; import { Observable } from 'rxjs'; export class RecordController { constructor(@Inject(ICommandService) private _commandService: ICommandService) { // empty } record() { return new Observable<{ type: 'start' } | { type: 'finish'; data: Blob }>((subscribe) => { navigator.mediaDevices.getDisplayMedia({ video: true }).then((stream) => { subscribe.next({ type: 'start' }); const mime = MediaRecorder.isTypeSupported('video/webm; codecs=vp9') ? 'video/webm; codecs=vp9' : 'video/webm'; const mediaRecorder = new MediaRecorder(stream, { mimeType: mime }); const chunks: Blob[] = []; mediaRecorder.addEventListener('dataavailable', function (e) { chunks.push(e.data); }); mediaRecorder.addEventListener('stop', function () { const blob = new Blob(chunks, { type: chunks[0].type }); subscribe.next({ type: 'finish', data: blob }); subscribe.complete(); }); mediaRecorder.start(); }); }); } startSaveCommands() { type SecondsString = string & {}; type CommandString = string & {}; type TypeString = string & {}; type ParamsString = string & {}; const result: Array<[SecondsString, CommandString, TypeString, ParamsString]> = []; const startTime = performance.now(); const disposable = this._commandService.beforeCommandExecuted((commandInfo) => { try { result.push([ String((performance.now() - startTime) / 1000), commandInfo.id, String(commandInfo.type || CommandType.COMMAND), JSON.stringify(commandInfo.params || ''), ]); } catch (err) { console.error(`${commandInfo.id} unable to serialize`); console.error(err); } }); return () => { disposable.dispose(); return result; }; } } - common/debugger/src/controllers/local-save/util.ts (234 bytes)
export function createDownloadElement(fileName: string, blob: Blob) { const a = document.createElement('a'); a.download = fileName; a.href = window.URL.createObjectURL(blob); return () => { a.click(); }; } - common/debugger/src/controllers/performance-monitor.controller.ts (2201 bytes)
import type { Nullable } from '@univerjs/core'; import type { Subscription } from 'rxjs'; import { Inject, IUniverInstanceService, LifecycleService, LifecycleStages, RxDisposable } from '@univerjs/core'; import { IRenderManagerService } from '@univerjs/engine-render'; import { distinctUntilChanged, filter, take, takeUntil } from 'rxjs'; export class PerformanceMonitorController extends RxDisposable { private _containerElement: HTMLDivElement | null; private _currentUnitSub: Nullable<Subscription>; constructor( @Inject(LifecycleService) lifecycleService: LifecycleService, @IUniverInstanceService private readonly _instanceService: IUniverInstanceService, @IRenderManagerService private readonly _renderManagerService: IRenderManagerService ) { super(); lifecycleService.subscribeWithPrevious() .pipe( filter((stage) => stage === LifecycleStages.Rendered), take(1) ) .subscribe(() => this._listenDocumentTypeChange()); } override dispose(): void { super.dispose(); this._disposeCurrentObserver(); } private _disposeCurrentObserver(): void { this._currentUnitSub?.unsubscribe(); this._currentUnitSub = null; } private _listenDocumentTypeChange() { this._instanceService.focused$.pipe(takeUntil(this.dispose$), distinctUntilChanged()).subscribe((unitId) => { this._disposeCurrentObserver(); if (unitId) { this._listenToRenderer(unitId); } }); } private _listenToRenderer(unitId: string) { const renderer = this._renderManagerService.getRenderUnitById(unitId); if (renderer) { const { engine } = renderer; this._currentUnitSub = engine.endFrame$.subscribe(() => { if (!this._containerElement) { this._containerElement = document.querySelector('[data-u-comp=debugger-fps]'); } else { this._containerElement.textContent = `FPS: ${Math.round(engine.getFps()).toString()}`; } }); } } } - common/debugger/src/global.css (43 bytes)
@tailwind components; @tailwind utilities;
- common/debugger/src/index.ts (163 bytes)
import './global.css'; export type { IUniverDebuggerConfig, UniverDebuggerLocaleLoader } from './config/config'; export { UniverDebuggerPlugin } from './plugin'; - common/debugger/src/plugin.ts (2266 bytes)
import type { Dependency } from '@univerjs/core'; import type { IUniverDebuggerConfig } from './config/config'; import { IConfigService, Inject, Injector, merge, Plugin, registerDependencies, touchDependencies } from '@univerjs/core'; import pkg from '../package.json'; import { DEBUGGER_PLUGIN_CONFIG_KEY, defaultPluginConfig } from './config/config'; import { ComponentsController } from './controllers/components.controller'; import { DebuggerController } from './controllers/debugger.controller'; import { PerformanceMonitorController } from './controllers/performance-monitor.controller'; export class UniverDebuggerPlugin extends Plugin { static override pluginName = 'UNIVER_DEBUGGER_PLUGIN'; static override packageName = pkg.name; static override version = pkg.version; private _debuggerController!: DebuggerController; constructor( private readonly _config: IUniverDebuggerConfig, @Inject(Injector) override readonly _injector: Injector, @IConfigService private readonly _configService: IConfigService ) { super(); // Manage the plugin configuration. const { menu, ...rest } = merge( {}, defaultPluginConfig, this._config ); if (menu) { this._configService.setConfig('menu', menu, { merge: true }); } this._configService.setConfig(DEBUGGER_PLUGIN_CONFIG_KEY, rest); } override onStarting(): void { const dependencies: Dependency[] = [ [DebuggerController], [ComponentsController], ]; if (this._config.performanceMonitor?.enabled !== false) { dependencies.push([PerformanceMonitorController]); } registerDependencies(this._injector, dependencies); } override onReady(): void { touchDependencies(this._injector, [ [ComponentsController], [DebuggerController], ]); } override onRendered(): void { touchDependencies(this._injector, [ [PerformanceMonitorController], ]); } getDebuggerController() { this._debuggerController = this._injector.get(DebuggerController); return this._debuggerController; } } - common/debugger/src/views/Fab.tsx (4348 bytes)
import type { IDropdownMenuProps } from '@univerjs/design'; import type { IUniverDebuggerConfig } from '../config/config'; import { IConfigService, UniverInstanceType } from '@univerjs/core'; import { borderClassName, clsx, DropdownMenu } from '@univerjs/design'; import { useDependency } from '@univerjs/ui'; import { DEBUGGER_PLUGIN_CONFIG_KEY } from '../config/config'; import { useCellContent } from './use-cell-content'; import { useDarkMode } from './use-dark-mode'; import { useDialog } from './use-dialog'; import { useDispose } from './use-dispose'; import { useEditable } from './use-editable'; import { useFloatingDom } from './use-floating-dom'; import { useLocale } from './use-locale'; import { useMessage } from './use-message'; import { useNotification } from './use-notification'; import { useRTL } from './use-rtl'; import { useSidebar } from './use-sidebar'; import { useSnapshot } from './use-snapshot'; import { useTheme } from './use-theme'; import { useUnits } from './use-units'; import { useUser } from './use-user'; import { useWatermark } from './use-watermark'; export function Fab() { const configService = useDependency(IConfigService); const configs = configService.getConfig<IUniverDebuggerConfig>(DEBUGGER_PLUGIN_CONFIG_KEY); const performanceMonitor = configs?.performanceMonitor; const fabEntryUnitType = configs?.fabEntryUnitType; const locale = useLocale(); const rtl = useRTL(); const darkMode = useDarkMode(); const theme = useTheme(); const watermark = useWatermark(); const notification = useNotification(); const message = useMessage(); const dialog = useDialog(); const sidebar = useSidebar(); const floatingDom = useFloatingDom(fabEntryUnitType); const cellContent = useCellContent(fabEntryUnitType); const units = useUnits(); const snapshot = useSnapshot(); const editable = useEditable(); const user = useUser(); const dispose = useDispose(); const globalItems = [locale, rtl, darkMode, theme]; const lightweightItems = [ ...globalItems, watermark, ]; const commonDebugItems = [ watermark, { type: 'separator' as const }, notification, message, dialog, sidebar, { type: 'separator' as const }, snapshot, editable, dispose, ]; const sheetItems = [ ...globalItems, watermark, { type: 'separator' as const }, notification, message, dialog, sidebar, { type: 'separator' as const }, floatingDom, cellContent, units, snapshot, editable, user, dispose, ]; const items: IDropdownMenuProps['items'] = fabEntryUnitType === UniverInstanceType.UNIVER_BASE || fabEntryUnitType === UniverInstanceType.UNIVER_SLIDE ? lightweightItems : fabEntryUnitType === UniverInstanceType.UNIVER_DOC ? [...globalItems, ...commonDebugItems, floatingDom].filter(Boolean) as IDropdownMenuProps['items'] : sheetItems.filter(Boolean) as IDropdownMenuProps['items']; return ( <div data-u-comp="debugger-fab" className={` univer-fixed univer-bottom-12 univer-right-8 univer-z-[9999] univer-flex univer-select-none univer-flex-col univer-items-center univer-gap-1 `} > <DropdownMenu align="end" items={items}> <button className={clsx(` univer-flex univer-size-9 univer-cursor-pointer univer-items-center univer-justify-center univer-rounded-full univer-bg-gray-0 univer-text-base univer-text-gray-900 univer-shadow univer-outline-none univer-transition-shadow hover:univer-ring-1 hover:univer-ring-primary-400 dark:!univer-bg-gray-900 dark:!univer-text-gray-200 `, borderClassName)} type="button" > 🏗️ </button> </DropdownMenu> {performanceMonitor?.enabled && ( <span data-u-comp="debugger-fps" className="univer-text-xs univer-text-gray-400" /> )} </div> ); } - common/debugger/src/views/test-editor/component-name.ts (70 bytes)
export const TEST_EDITOR_CONTAINER_COMPONENT = 'TestEditorContainer';
- common/debugger/src/views/use-cell-content.ts (1228 bytes)
import { ILogService, IUniverInstanceService, ObjectMatrix, Range, UniverInstanceType } from '@univerjs/core'; import { getSheetCommandTarget, SheetsSelectionsService } from '@univerjs/sheets'; import { useDependency } from '@univerjs/ui'; export function useCellContent(fabEntryUnitType?: UniverInstanceType) { const logService = useDependency(ILogService); const selectionManagerService = fabEntryUnitType === UniverInstanceType.UNIVER_SHEET ? useDependency(SheetsSelectionsService) : null; const univerInstanceService = useDependency(IUniverInstanceService); const onSelect = () => { if (!selectionManagerService) return; const selections = selectionManagerService.getCurrentSelections(); const target = getSheetCommandTarget(univerInstanceService); const matrix = new ObjectMatrix(); selections.forEach((selection) => { Range.foreach(selection.range, (row, col) => { matrix.setValue(row, col, target?.worksheet.getCell(row, col)); }); }); logService.debug('cell-content', matrix); }; return { type: 'item' as const, children: '🗒️ Console cell content', onSelect, }; } - common/debugger/src/views/use-dark-mode.ts (894 bytes)
import { ThemeService } from '@univerjs/core'; import { useDependency } from '@univerjs/ui'; import { useEffect } from 'react'; export function useDarkMode() { const themeService = useDependency(ThemeService); useEffect(() => { const darkMode = localStorage.getItem('local.darkMode'); if (darkMode === 'dark') { document.documentElement.classList.add('univer-dark'); themeService.setDarkMode(true); } else if (darkMode === 'system') { themeService.setDarkMode(false); } }, []); const onSelect = () => { const darkMode = themeService.darkMode ? 'light' : 'dark'; themeService.setDarkMode(darkMode === 'dark'); localStorage.setItem('local.darkMode', darkMode); }; return { type: 'item' as const, children: '🌓 Toggle dark mode', onSelect, }; } - common/debugger/src/views/use-dialog.ts (2743 bytes)
import { IConfirmService } from '@univerjs/core'; import { IDialogService, useDependency } from '@univerjs/ui'; const menu = [ { label: 'Open dialog', value: 'dialog', }, { label: 'Draggable dialog', value: 'draggable', }, { label: 'Open confirm', value: 'confirm', }, ]; export function useDialog() { const dialogService = useDependency(IDialogService); const confirmService = useDependency(IConfirmService); const onSelect = (value: string) => { if (value === 'draggable') { dialogService.open({ id: 'draggable', children: { title: 'Draggable Dialog Content' }, title: { title: 'Draggable Dialog' }, draggable: true, preservePositionOnDestroy: true, width: 350, onClose() { // dialogService.close('draggable'); }, onOpenChange(open: boolean) { if (!open) { dialogService.close('draggable'); } }, }); } else if (value === 'dialog') { dialogService.open({ id: 'dialog1', children: { title: 'Dialog Content' }, footer: { title: 'Dialog Footer' }, title: { title: 'Dialog Title' }, draggable: false, onClose() { // dialogService.close('dialog1'); }, onOpenChange(open: boolean) { if (!open) { dialogService.close('dialog1'); } }, }); } else if (value === 'confirm') { confirmService.open({ id: 'confirm1', children: { title: 'Confirm Content' }, title: { title: 'Confirm Title' }, confirmText: 'hello', cancelText: 'world', onClose() { confirmService.close('confirm1'); }, }); confirmService.open({ id: 'confirm2', children: { title: 'Confirm2 Content' }, title: { title: 'Confirm2 Title' }, onClose() { confirmService.close('confirm2'); }, }); } }; return { type: 'subItem' as const, children: '💬 Dialog & Confirm', options: menu.map((item) => ({ type: 'item' as const, children: item.label, onSelect: () => onSelect(item.value), })), }; } - common/debugger/src/views/use-dispose.ts (1256 bytes)
import type { Univer } from '@univerjs/core'; import { IUniverInstanceService } from '@univerjs/core'; import { useDependency } from '@univerjs/ui'; const menu = [ { label: 'Dispose Univer', value: 'univer', }, { label: 'Dispose current unit', value: 'unit', }, ]; export function useDispose() { const univerInstanceService = useDependency(IUniverInstanceService); const onSelect = (value: string) => { if (value === 'univer') { const debuggerWindow = window as typeof window & { univer?: Univer }; debuggerWindow.univer?.dispose(); Reflect.deleteProperty(debuggerWindow, 'univer'); Reflect.deleteProperty(debuggerWindow, 'univerAPI'); } else if (value === 'unit') { const focused = univerInstanceService.getFocusedUnit(); if (!focused) return false; return univerInstanceService.disposeUnit(focused.getUnitId()); } }; return { type: 'subItem' as const, children: '🗑️ Dispose', options: menu.map((item) => ({ type: 'item' as const, children: item.label, onSelect: () => onSelect(item.value), })), }; } - common/debugger/src/views/use-editable.ts (1731 bytes)
import { IPermissionService, IUniverInstanceService } from '@univerjs/core'; import { getSheetCommandTarget, WorkbookEditablePermission, WorksheetEditPermission } from '@univerjs/sheets'; import { useDependency } from '@univerjs/ui'; const menu = [ { label: 'Change workbook editable', value: 'univer', }, { label: 'Change worksheet editable', value: 'sheet', }, ]; export function useEditable() { const univerInstanceService = useDependency(IUniverInstanceService); const permissionService = useDependency(IPermissionService); const onSelect = (value: string) => { const target = getSheetCommandTarget(univerInstanceService); if (!target) { return false; } const { workbook, worksheet, unitId, subUnitId } = target; if (!workbook || !worksheet) { return false; } if (value === 'sheet') { const editable = permissionService.getPermissionPoint(new WorksheetEditPermission(unitId, subUnitId).id); permissionService.updatePermissionPoint(new WorksheetEditPermission(unitId, subUnitId).id, !editable); } else { const unitId = workbook!.getUnitId(); const editable = permissionService.getPermissionPoint(new WorkbookEditablePermission(unitId).id); permissionService.updatePermissionPoint(new WorkbookEditablePermission(unitId).id, !editable); } }; return { type: 'subItem' as const, children: '✍️ Editable', options: menu.map((item) => ({ type: 'item' as const, children: item.label, onSelect: () => onSelect(item.value), })), }; } - common/debugger/src/views/use-floating-dom.ts (1942 bytes)
import { IUniverInstanceService, UniverInstanceType } from '@univerjs/core'; import { DocFloatDomController } from '@univerjs/docs-drawing-ui'; import { SheetCanvasFloatDomManagerService } from '@univerjs/sheets-drawing-ui'; import { useDependency } from '@univerjs/ui'; export function useFloatingDom(entryUnitType?: UniverInstanceType) { const univerInstanceService = useDependency(IUniverInstanceService); const floatDomService = entryUnitType === UniverInstanceType.UNIVER_SHEET ? useDependency(SheetCanvasFloatDomManagerService) : null; const floatDomController = entryUnitType === UniverInstanceType.UNIVER_DOC ? useDependency(DocFloatDomController) : null; const onSelect = () => { if (entryUnitType === UniverInstanceType.UNIVER_SHEET) { const currentSheet = univerInstanceService.getCurrentUnitOfType(UniverInstanceType.UNIVER_SHEET); if (!currentSheet) return; floatDomService?.addFloatDomToPosition({ allowTransform: true, initPosition: { startX: 200, endX: 400, startY: 200, endY: 400, }, componentKey: 'ImageDemo', data: { aa: '128', }, }); } else if (entryUnitType === UniverInstanceType.UNIVER_DOC) { const currentDoc = univerInstanceService.getCurrentUnitOfType(UniverInstanceType.UNIVER_DOC); if (!currentDoc) return; floatDomController?.insertFloatDom({ allowTransform: true, componentKey: 'ImageDemo', data: { aa: '128', }, }, { height: 300, }); } }; return { type: 'item' as const, children: '☁️ Create floating DOM', onSelect, }; } - common/debugger/src/views/use-locale.ts (2671 bytes)
import type { IUniverDebuggerConfig } from '../config/config'; import { IConfigService, LocaleService, LocaleType } from '@univerjs/core'; import { useDependency } from '@univerjs/ui'; import { useCallback, useEffect } from 'react'; import { DEBUGGER_PLUGIN_CONFIG_KEY } from '../config/config'; const localeLabels: Record<LocaleType, string> = { [LocaleType.AR_SA]: 'العربية', [LocaleType.CA_ES]: 'Català', [LocaleType.DE_DE]: 'Deutsch', [LocaleType.EN_US]: 'English', [LocaleType.ES_ES]: 'Español', [LocaleType.FA_IR]: 'فارسی', [LocaleType.FR_FR]: 'Français', [LocaleType.ID_ID]: 'Bahasa Indonesia', [LocaleType.IT_IT]: 'Italiano', [LocaleType.JA_JP]: '日本語', [LocaleType.KO_KR]: '한국어', [LocaleType.PL_PL]: 'Polski', [LocaleType.PT_BR]: 'Português (Brasil)', [LocaleType.RU_RU]: 'Русский', [LocaleType.SK_SK]: 'Slovenčina', [LocaleType.VI_VN]: 'Tiếng Việt', [LocaleType.ZH_CN]: '简体中文', [LocaleType.ZH_HK]: '繁體中文(香港)', [LocaleType.ZH_TW]: '繁體中文(台灣)', }; export function useLocale() { const configService = useDependency(IConfigService); const localeService = useDependency(LocaleService); const configs = configService.getConfig<IUniverDebuggerConfig>(DEBUGGER_PLUGIN_CONFIG_KEY); const localeLoader = configs?.localeLoader; const loadLocales = useCallback(async (value: string) => { const locale = value as LocaleType; if (!localeLoader) { throw new Error('[UniverDebuggerPlugin]: localeLoader is required.'); } const localePack = await localeLoader(locale); localeService.load({ [locale]: localePack, }); }, [localeLoader, localeService]); useEffect(() => { const locale = localStorage.getItem('local.locale'); if (locale) { loadLocales(locale).then(() => { localeService.setLocale(locale as LocaleType); }); } }, [loadLocales, localeService]); const onSelect = async (value: string) => { await loadLocales(value); localeService.setLocale(value as LocaleType); localStorage.setItem('local.locale', value); }; return { type: 'subItem' as const, children: '🌐 Languages', options: Object.values(LocaleType).map((locale) => ({ type: 'radio' as const, value: localeService.getCurrentLocale(), options: [{ label: localeLabels[locale], value: locale, }], onSelect, })), }; } - common/debugger/src/views/use-message.ts (1073 bytes)
import { MessageType } from '@univerjs/design'; import { IMessageService, useDependency } from '@univerjs/ui'; const menu = [ { label: 'Open message', value: '', }, { label: 'Open loading message', value: 'loading', }, ]; export function useMessage() { const messageService = useDependency(IMessageService); const onSelect = (value: string) => { if (value === 'loading') { messageService.show({ type: MessageType.Loading, content: 'Loading message', duration: 3000, }); } else { messageService.show({ type: MessageType.Success, content: 'Demo message', duration: 1500, }); } }; return { type: 'subItem' as const, children: '✉️ Message', options: menu.map((item) => ({ type: 'item' as const, children: item.label, onSelect: () => onSelect(item.value), })), }; } - common/debugger/src/views/use-notification.ts (1163 bytes)
import type { INotificationOptions } from '@univerjs/ui'; import { INotificationService, useDependency } from '@univerjs/ui'; const menu = [ { label: 'Notification success', value: 'success', }, { label: 'Notification info', value: 'info', }, { label: 'Notification warning', value: 'warning', }, { label: 'Notification error', value: 'error', }, ]; export function useNotification() { const notificationService = useDependency(INotificationService); const onSelect = (value: string) => { notificationService.show({ type: value as INotificationOptions['type'], content: 'Lorem Ipusm dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', title: 'Notification Title', }); }; return { type: 'subItem' as const, children: '🔔 Notification', options: menu.map((item) => ({ type: 'item' as const, children: item.label, onSelect: () => onSelect(item.value), })), }; } - common/debugger/src/views/use-rtl.ts (807 bytes)
import { LocaleService } from '@univerjs/core'; import { useDependency } from '@univerjs/ui'; import { useEffect } from 'react'; export function useRTL() { const localeService = useDependency(LocaleService); useEffect(() => { const dir = localStorage.getItem('local.direction'); if (dir === 'rtl' || dir === 'ltr') { localeService.setDirection(dir); } }, [localeService]); const onSelect = () => { const current = localeService.getDirection(); const nextDirection = current === 'rtl' ? 'ltr' : 'rtl'; localeService.setDirection(nextDirection); localStorage.setItem('local.direction', nextDirection); }; return { type: 'item' as const, children: '↔️ Toggle RTL', onSelect, }; } - common/debugger/src/views/use-sidebar.ts (1096 bytes)
import { ISidebarService, useDependency } from '@univerjs/ui'; import { TEST_EDITOR_CONTAINER_COMPONENT } from './test-editor/component-name'; const menu = [ { label: 'Open sidebar', value: 'open', }, { label: 'Close sidebar', value: 'close', }, ]; export function useSidebar() { const sidebarService = useDependency(ISidebarService); const onSelect = (value: string) => { if (value === 'open') { sidebarService.open({ header: { title: 'Sidebar title' }, children: { label: TEST_EDITOR_CONTAINER_COMPONENT }, footer: { title: 'Sidebar Footer' }, onClose: () => { }, }); } else if (value === 'close') { sidebarService.close(); } }; return { type: 'subItem' as const, children: '🧩 Sidebar', options: menu.map((item) => ({ type: 'item' as const, children: item.label, onSelect: () => onSelect(item.value), })), }; } - common/debugger/src/views/use-snapshot.ts (5110 bytes)
/* eslint-disable node/prefer-global/process */ import type { DocumentDataModel, IStyleData, IWorkbookData, Workbook } from '@univerjs/core'; import { IResourceLoaderService, IUniverInstanceService, ObjectMatrix, UniverInstanceType } from '@univerjs/core'; import { ILocalFileService, useDependency } from '@univerjs/ui'; import { RecordController } from '../controllers/local-save/record.controller'; const menu = [ { label: 'Save workbook', value: 'workbook', }, { label: 'Save worksheet', value: 'sheet', }, { label: 'Record', value: 'record', }, { label: 'Load snapshot', value: 'load', }, ]; export interface ISaveSnapshotParams { value: 'sheet' | 'workbook' | 'record'; } const filterStyle = (workbookData: IWorkbookData) => { const sheets = workbookData.sheets; const cacheStyle: Record<string, IStyleData> = {}; Object.keys(sheets).forEach((sheetId) => { const sheet = sheets[sheetId]; new ObjectMatrix(sheet.cellData).forValue((_r, _c, value) => { const s = value?.s; if (s && typeof s === 'string') { const style = workbookData.styles[s]; if (style) { cacheStyle[s] = style; } } }); }); workbookData.styles = cacheStyle; return workbookData; }; export function useSnapshot() { const univerInstanceService = useDependency(IUniverInstanceService); const resourceLoaderService = useDependency(IResourceLoaderService); const localFileService = useDependency(ILocalFileService); const recordController = useDependency(RecordController); const onSelect = async (value: string) => { const preName = new Date().toLocaleString(); const workbook = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!; if (!workbook) { const doc = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)!; const snapshot = resourceLoaderService.saveUnit(doc.getUnitId()); if (process.env.NODE_ENV === 'production') { const gitHash = process.env.GIT_COMMIT_HASH; const gitBranch = process.env.GIT_REF_NAME; const buildTime = process.env.BUILD_TIME; (snapshot as any).__env__ = { gitHash, gitBranch, buildTime }; } const text = JSON.stringify(snapshot, null, 2); localFileService.downloadFile(new Blob([text]), `${preName} snapshot.json`); return true; } const worksheet = workbook.getActiveSheet(); if (!worksheet) { return false; } const snapshot = resourceLoaderService.saveUnit<ReturnType<typeof workbook.getSnapshot>>(workbook.getUnitId())!; if (process.env.NODE_ENV === 'production') { const gitHash = process.env.GIT_COMMIT_HASH; const gitBranch = process.env.GIT_REF_NAME; const buildTime = process.env.BUILD_TIME; (snapshot as any).__env__ = { gitHash, gitBranch, buildTime }; } if (value === 'sheet') { const sheetId = worksheet.getSheetId(); const sheet = snapshot.sheets[sheetId]; snapshot.sheets = { [sheetId]: sheet }; snapshot.sheetOrder = [sheetId]; const text = JSON.stringify(filterStyle(snapshot), null, 2); localFileService.downloadFile(new Blob([text]), `${preName} snapshot.json`); } else if (value === 'workbook') { const text = JSON.stringify(filterStyle(snapshot), null, 2); localFileService.downloadFile(new Blob([text]), `${preName} snapshot.json`); } else if (value === 'record') { let endCommands = () => []; recordController.record().subscribe((v) => { if (v.type === 'start') { endCommands = recordController.startSaveCommands() as any; } if (v.type === 'finish') { const commands = endCommands(); localFileService.downloadFile(v.data, `${preName} video.webm`); localFileService.downloadFile(new Blob([JSON.stringify(commands, null, 2)]), `${preName} commands.json`); } }); } else if (value === 'load') { const snapshotFile = await localFileService.openFile({ multiple: false, accept: '.json' }); if (snapshotFile.length !== 1) return false; const text = await snapshotFile[0].text(); univerInstanceService.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, JSON.parse(text)); return true; } }; return { type: 'subItem' as const, children: '📷 Snapshot', options: menu.map((item) => ({ type: 'item' as const, children: item.label, onSelect: () => onSelect(item.value), })), }; } - common/debugger/src/views/use-theme.ts (1612 bytes)
import { ThemeService } from '@univerjs/core'; import { blueTheme, darkBlueTheme, greenTheme, orangeTheme, purpleTheme, redTheme, yellowTheme, } from '@univerjs/themes'; import { useDependency } from '@univerjs/ui'; import { useEffect } from 'react'; const themes = [ { label: '🟢', value: greenTheme, }, { label: '🔵', value: blueTheme, }, { label: '🔵🌑', value: darkBlueTheme, }, { label: '🟠', value: orangeTheme, }, { label: '🔴', value: redTheme, }, { label: '🟣', value: purpleTheme, }, { label: '🟡', value: yellowTheme, }, ]; export function useTheme() { const themeService = useDependency(ThemeService); useEffect(() => { const themeKey = localStorage.getItem('local.theme'); const theme = themes.find((theme) => theme.label === themeKey); if (theme) { themeService.setTheme(theme.value); } }, [themeService]); const onSelect = (value: string) => { localStorage.setItem('local.theme', value); const theme = themes.find((theme) => theme.label === value); if (theme) { themeService.setTheme(theme.value); } }; return { type: 'subItem' as const, children: '🎨 Themes', options: themes.map((theme) => ({ type: 'item' as const, children: theme.label, onSelect: () => onSelect(theme.label), })), }; } - common/debugger/src/views/use-units.ts (1676 bytes)
import type { Workbook } from '@univerjs/core'; import { IUniverInstanceService, UniverInstanceType } from '@univerjs/core'; import { useDependency, useObservable } from '@univerjs/ui'; import { useEffect, useState } from 'react'; const defaultMenu = [ { label: 'Create another sheet', value: 'create', }, ]; export function useUnits() { const univerInstanceService = useDependency(IUniverInstanceService); const [menu, setMenu] = useState<{ label: string; value: string }[]>([...defaultMenu]); const unitAdded = useObservable(univerInstanceService.unitAdded$); const unitDisposed = useObservable(univerInstanceService.unitDisposed$); useEffect(() => { const sheets = univerInstanceService.getAllUnitsForType<Workbook>(UniverInstanceType.UNIVER_SHEET); const options = sheets.map((sheet) => ({ label: sheet.name || sheet.getUnitId(), value: sheet.getUnitId(), })); setMenu([ ...defaultMenu, ...(options as any[]), ]); }, [unitAdded, unitDisposed]); const onSelect = (value: string) => { if (value === 'create') { univerInstanceService.createUnit(UniverInstanceType.UNIVER_SHEET, {}); } else { if (!univerInstanceService.getUnit(value)) return false; univerInstanceService.setCurrentUnitForType(value); } }; return { type: 'subItem' as const, children: '🪸 Units', options: menu.map((item) => ({ type: 'item' as const, children: item.label, onSelect: () => onSelect(item.value), })), }; } - common/debugger/src/views/use-user.ts (1698 bytes)
import type { Workbook } from '@univerjs/core'; import { createDefaultUser, IPermissionService, IUniverInstanceService, UniverInstanceType, UserManagerService } from '@univerjs/core'; import { WorkbookManageCollaboratorPermission } from '@univerjs/sheets'; import { useDependency } from '@univerjs/ui'; enum UnitRole { Reader = 0, Editor = 1, Owner = 2, UNRECOGNIZED = -1, } const menu = [ { label: 'Owner', value: UnitRole.Owner, }, { label: 'Editor', value: UnitRole.Editor, }, { label: 'Reader', value: UnitRole.Reader, }, ]; export function useUser() { const univerInstanceService = useDependency(IUniverInstanceService); const userManagerService = useDependency(UserManagerService); const permissionService = useDependency(IPermissionService); const onSelect = (value: UnitRole) => { userManagerService.setCurrentUser(createDefaultUser(value)); const workbook = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!; const unitId = workbook.getUnitId(); if (value === UnitRole.Owner) { permissionService.updatePermissionPoint(new WorkbookManageCollaboratorPermission(unitId).id, true); } else { permissionService.updatePermissionPoint(new WorkbookManageCollaboratorPermission(unitId).id, false); } }; return { type: 'subItem' as const, children: '👥 Change user\'s role', options: menu.map((item) => ({ type: 'item' as const, children: item.label, onSelect: () => onSelect(item.value), })), }; } - common/debugger/src/views/use-watermark.ts (653 bytes)
import { ISidebarService, useDependency } from '@univerjs/ui'; import { WATERMARK_PANEL, WATERMARK_PANEL_FOOTER } from '../controllers/components.controller'; export function useWatermark() { const sidebarService = useDependency(ISidebarService); const onSelect = () => { sidebarService.open({ header: { title: 'Watermark' }, children: { label: WATERMARK_PANEL }, footer: { label: WATERMARK_PANEL_FOOTER }, onClose: () => { }, width: 330, }); }; return { type: 'item' as const, children: '🌊 Watermark Settings', onSelect, }; } - common/debugger/src/views/watermark/WatermarkImageSetting.tsx (9981 bytes)
import type { IImageWatermarkConfig } from '@univerjs/engine-render'; import { Button, Checkbox, InputNumber } from '@univerjs/design'; import { ILocalFileService, useDependency } from '@univerjs/ui'; import { WATERMARK_IMAGE_ALLOW_IMAGE_LIST } from '@univerjs/watermark'; interface IWatermarkImageSettingProps { config?: IImageWatermarkConfig; onChange: (config: IImageWatermarkConfig) => void; } export function WatermarkImageSetting({ config, onChange }: IWatermarkImageSettingProps) { const fileOpenService = useDependency(ILocalFileService); if (!config) return null; const handleUpdateImageUrl = async () => { const files = await fileOpenService.openFile({ multiple: false, accept: WATERMARK_IMAGE_ALLOW_IMAGE_LIST.map((image) => `.${image.replace('image/', '')}`).join(','), }); const fileLength = files.length; if (fileLength === 0) { return false; } const file = files[0]; const reader = new FileReader(); reader.onload = function (event) { if (event.target?.result) { const base64String = event.target.result; const img = new Image(); img.onload = function () { onChange({ ...config, url: base64String as string, width: Math.max(20, img.width), height: Math.max(img.height, 20), originRatio: img.width / img.height }); }; img.src = base64String as string; } }; reader.readAsDataURL(file); }; return ( <div className="univer-grid univer-gap-2"> <div className="univer-text-gray-400">Image</div> <div className="univer-mb-4 univer-grid univer-gap-1"> <Button className="univer-mb-2" onClick={handleUpdateImageUrl} > {config.url ? 'Replace Image' : 'Upload Image'} </Button> <div className="univer-flex univer-gap-2 univer-text-center"> <div className="univer-grid univer-flex-1 univer-gap-1"> <div>Opacity</div> <InputNumber className="univer-box-border univer-h-7" value={config.opacity} max={1} min={0} step={0.05} onChange={(val) => { if (val != null) { onChange({ ...config, opacity: Number.parseFloat(val.toString()) }); } }} /> </div> <div className="univer-grid univer-flex-1 univer-gap-1"> <div>Keep Ratio</div> <Checkbox className="univer-justify-center univer-self-baseline" checked={config.maintainAspectRatio} onChange={(val) => { if (val === true) { onChange({ ...config, maintainAspectRatio: val as boolean, height: Math.round(config.width / config.originRatio) }); } else { onChange({ ...config, maintainAspectRatio: val as boolean }); } }} /> </div> </div> </div> <div className="univer-grid univer-gap-2 univer-text-center"> <div className="univer-flex univer-gap-2"> <div className="univer-grid univer-flex-1 univer-gap-1"> <div>Width</div> <InputNumber className="univer-box-border univer-h-7" value={config.width} min={20} onChange={(val) => { if (val != null) { const newWidth = Math.max(20, Number.parseInt(val.toString())); if (config.maintainAspectRatio) { onChange({ ...config, width: newWidth, height: Math.round(newWidth / config.originRatio) }); } else { onChange({ ...config, width: newWidth }); } } }} /> </div> <div className="univer-grid univer-flex-1 univer-gap-1"> <div>Height</div> <InputNumber className="univer-box-border univer-h-7" value={config.height} min={20} onChange={(val) => { if (val != null) { const newHeight = Math.max(20, Number.parseInt(val.toString())); if (config.maintainAspectRatio) { onChange({ ...config, height: newHeight, width: Math.round(newHeight * config.originRatio) }); } else { onChange({ ...config, height: Number.parseInt(val.toString()) }); } } }} /> </div> </div> </div> <div className="univer-text-gray-400">Layout Settings</div> <div className="univer-grid univer-gap-2 univer-text-center"> <div className="univer-flex univer-gap-2"> <div className="univer-grid univer-flex-1 univer-gap-1"> <div>Rotate</div> <InputNumber className="univer-box-border univer-h-7" value={config.rotate} max={360} min={-360} onChange={(val) => { if (val != null) { onChange({ ...config, rotate: Number.parseInt(val.toString()) }); } }} /> </div> <div className="univer-grid univer-flex-1 univer-gap-1"> <div>Repeat</div> <Checkbox className="univer-justify-center univer-self-baseline" checked={config.repeat} onChange={(val) => onChange({ ...config, repeat: val as boolean })} /> </div> </div> <div className="univer-flex univer-gap-2"> <div className="univer-grid univer-flex-1 univer-gap-1"> <div>Horizontal Spacing</div> <InputNumber className="univer-box-border univer-h-7" value={config.spacingX} min={0} onChange={(val) => { if (val != null) { onChange({ ...config, spacingX: Number.parseInt(val.toString()) }); } }} /> </div> <div className="univer-grid univer-flex-1 univer-gap-1"> <div>Vertical Spacing</div> <InputNumber className="univer-box-border univer-h-7" value={config.spacingY} min={0} onChange={(val) => { if (val != null) { onChange({ ...config, spacingY: Number.parseInt(val.toString()) }); } }} /> </div> </div> <div className="univer-flex univer-gap-2"> <div className="univer-grid univer-flex-1 univer-gap-1"> <div>Horizontal Start Position</div> <InputNumber className="univer-box-border univer-h-7" value={config.x} min={0} onChange={(val) => { if (val != null) { onChange({ ...config, x: Number.parseInt(val.toString()) }); } }} /> </div> <div className="univer-grid univer-flex-1 univer-gap-1"> <div>Vertical Start Position</div> <InputNumber className="univer-box-border univer-h-7" value={config.y} min={0} onChange={(val) => { if (val != null) { onChange({ ...config, y: Number.parseInt(val.toString()) }); } }} /> </div> </div> </div> </div> ); }; - common/debugger/src/views/watermark/WatermarkPanel.tsx (3212 bytes)
import type { IWatermarkConfig, IWatermarkConfigWithType } from '@univerjs/engine-render'; import { ILocalStorageService } from '@univerjs/core'; import { Select } from '@univerjs/design'; import { IWatermarkTypeEnum, UNIVER_WATERMARK_STORAGE_KEY } from '@univerjs/engine-render'; import { useDependency, useObservable } from '@univerjs/ui'; import { WatermarkImageBaseConfig, WatermarkService, WatermarkTextBaseConfig } from '@univerjs/watermark'; import { useCallback, useEffect, useState } from 'react'; import { WatermarkImageSetting } from './WatermarkImageSetting'; import { WatermarkTextSetting } from './WatermarkTextSetting'; export function WatermarkPanel() { const [watermarkType, setWatermarkType] = useState<IWatermarkTypeEnum>(IWatermarkTypeEnum.Text); const [config, setConfig] = useState<IWatermarkConfig>(); const watermarkService = useDependency(WatermarkService); const localStorageService = useDependency(ILocalStorageService); const _refresh = useObservable(watermarkService.refresh$); function handleConfigChange(config: IWatermarkConfig, type?: IWatermarkTypeEnum) { setConfig(config); watermarkService.updateWatermarkConfig({ type: type ?? watermarkType, config }); } const getWatermarkConfig = useCallback(async () => { const watermarkConfig = await localStorageService.getItem<IWatermarkConfigWithType>(UNIVER_WATERMARK_STORAGE_KEY); if (watermarkConfig) { setWatermarkType(watermarkConfig.type); setConfig(watermarkConfig.config); } else { setConfig({ text: WatermarkTextBaseConfig }); } }, []); useEffect(() => { getWatermarkConfig(); }, [_refresh, getWatermarkConfig]); return ( <div className="univer-grid univer-gap-3 univer-text-sm"> {/* Watermark type */} <div className="univer-grid univer-gap-2"> <div className="univer-text-gray-400">Type</div> <Select value={watermarkType} options={[ { label: 'Text', value: IWatermarkTypeEnum.Text }, { label: 'Image', value: IWatermarkTypeEnum.Image }, ]} onChange={(v) => { setWatermarkType(v as IWatermarkTypeEnum); if (v === IWatermarkTypeEnum.Text) { handleConfigChange({ text: WatermarkTextBaseConfig }, IWatermarkTypeEnum.Text); } else if (v === IWatermarkTypeEnum.Image) { handleConfigChange({ image: WatermarkImageBaseConfig }, IWatermarkTypeEnum.Image); } }} /> </div> <div className="univer-grid univer-gap-2"> {watermarkType === IWatermarkTypeEnum.Text && <WatermarkTextSetting config={config?.text} onChange={(v) => handleConfigChange({ text: v })} />} {watermarkType === IWatermarkTypeEnum.Image && <WatermarkImageSetting config={config?.image} onChange={(v) => handleConfigChange({ image: v })} />} </div> </div> ); }; - common/debugger/src/views/watermark/WatermarkPanelFooter.tsx (2619 bytes)
import { Button } from '@univerjs/design'; import { IWatermarkTypeEnum } from '@univerjs/engine-render'; import { IClipboardInterfaceService, ISidebarService, useDependency } from '@univerjs/ui'; import { WatermarkService, WatermarkTextBaseConfig } from '@univerjs/watermark'; export function WatermarkPanelFooter() { const sidebarService = useDependency(ISidebarService); const watermarkService = useDependency(WatermarkService); const clipboardService = useDependency(IClipboardInterfaceService); return ( <div className="univer-flex univer-items-center univer-justify-between"> <a className="univer-text-sm univer-text-primary-600 univer-underline" onClick={() => { watermarkService.updateWatermarkConfig({ type: IWatermarkTypeEnum.Text, config: { text: WatermarkTextBaseConfig }, }); watermarkService.refresh(); }} > Cancel Watermark </a> <div className="univer-flex univer-items-center univer-gap-2"> <Button onClick={async () => { const watermarkConfig = await watermarkService.getWatermarkConfig(); let config; if (watermarkConfig?.type === IWatermarkTypeEnum.Text) { config = watermarkConfig.config.text; } else if (watermarkConfig?.type === IWatermarkTypeEnum.Image) { config = watermarkConfig.config.image; } clipboardService.writeText(JSON.stringify(config)); }} > Copy Config </Button> <Button onClick={async () => { const watermarkConfig = await watermarkService.getWatermarkConfig(); if (watermarkConfig?.type === IWatermarkTypeEnum.Text && !watermarkConfig.config.text?.content) { watermarkService.deleteWatermarkConfig(); } else if (watermarkConfig?.type === IWatermarkTypeEnum.Image && !watermarkConfig.config.image?.url) { watermarkService.deleteWatermarkConfig(); } sidebarService.close(); }} > Close Panel </Button> </div> </div> ); }; - common/debugger/src/views/watermark/WatermarkTextSetting.tsx (8784 bytes)
import type { ITextWatermarkConfig } from '@univerjs/engine-render'; import { Checkbox, clsx, ColorPicker, Dropdown, Input, InputNumber, Select } from '@univerjs/design'; import { BoldIcon, FontColorDoubleIcon, ItalicIcon } from '@univerjs/icons'; interface IWatermarkTextSettingProps { config?: ITextWatermarkConfig; onChange: (config: ITextWatermarkConfig) => void; } export function WatermarkTextSetting(props: IWatermarkTextSettingProps) { const { config, onChange } = props; if (!config) return null; return ( <div className="univer-grid univer-gap-2"> <div className="univer-text-gray-400">Style Settings</div> <div className="univer-mb-4 univer-grid univer-gap-1"> <div>Content</div> <Input value={config.content} onChange={(val) => onChange({ ...config, content: val })} placeholder="Enter text" /> </div> <div className="univer-grid univer-gap-4"> <div className="univer-flex univer-gap-2"> <div className="univer-grid univer-gap-1"> <div>Font Size</div> <InputNumber value={config.fontSize} max={72} min={12} onChange={(val) => { if (val != null) { onChange({ ...config, fontSize: Number.parseInt(val.toString()) }); } }} /> </div> <div className="univer-grid univer-gap-1"> <div>Direction</div> <Select value={config.direction} options={[ { label: 'Left to Right', value: 'ltr' }, { label: 'Right to Left', value: 'rtl' }, ]} onChange={(v) => onChange({ ...config, direction: v as 'ltr' | 'rtl' })} /> </div> <div className="univer-grid univer-gap-1"> <div>Opacity</div> <InputNumber max={1} min={0} step={0.05} value={config.opacity} onChange={(val) => { if (val != null) { onChange({ ...config, opacity: Number.parseFloat(val.toString()) }); } }} /> </div> </div> <div className={` univer-flex univer-justify-around univer-gap-4 [&_a]:univer-flex [&_a]:univer-size-6 [&_a]:univer-items-center [&_a]:univer-justify-center [&_a]:univer-rounded `} > <Dropdown overlay={( <div className="univer-rounded-lg univer-p-4"> <ColorPicker value={config.color} onChange={(val) => onChange({ ...config, color: val })} /> </div> )} > <a className={` hover:univer-bg-gray-100 dark:hover:!univer-bg-gray-700 `} > <FontColorDoubleIcon extend={{ colorChannel1: config.color ?? '#2c53f1' }} /> </a> </Dropdown> <a className={clsx(` hover:univer-bg-gray-100 dark:hover:!univer-bg-gray-700 `, { 'univer-bg-gray-200 dark:!univer-bg-gray-600': config.bold, })} onClick={() => { onChange({ ...config, bold: !config.bold }); }} > <BoldIcon /> </a> <a className={clsx(` hover:univer-bg-gray-100 dark:hover:!univer-bg-gray-700 `, { 'univer-bg-gray-200 dark:!univer-bg-gray-600': config.italic, })} onClick={() => { onChange({ ...config, italic: !config.italic }); }} > <ItalicIcon /> </a> </div> </div> {/* Layout */} <div className="univer-text-gray-400">Layout Settings</div> <div className="univer-grid univer-gap-2 univer-text-center"> <div className="univer-flex univer-gap-2"> <div className="univer-grid univer-flex-1 univer-gap-1"> <div>Rotate</div> <InputNumber value={config.rotate} max={360} min={-360} onChange={(val) => { if (val != null) { onChange({ ...config, rotate: Number.parseInt(val.toString()) }); } }} /> </div> <div className="univer-grid univer-flex-1 univer-gap-1"> <div>Repeat</div> <Checkbox className="univer-justify-center univer-self-baseline" checked={config.repeat} onChange={(val) => onChange({ ...config, repeat: val as boolean })} /> </div> </div> <div className="univer-flex univer-gap-2"> <div className="univer-grid univer-gap-1"> <div>Horizontal Spacing</div> <InputNumber value={config.spacingX} min={0} onChange={(val) => { if (val != null) { onChange({ ...config, spacingX: Number.parseInt(val.toString()) }); } }} /> </div> <div className="univer-grid univer-gap-1"> <div>Vertical Spacing</div> <InputNumber value={config.spacingY} min={0} onChange={(val) => { if (val != null) { onChange({ ...config, spacingY: Number.parseInt(val.toString()) }); } }} /> </div> </div> <div className="univer-flex univer-gap-2"> <div className="univer-grid univer-gap-1"> <div>Horizontal Start Position</div> <InputNumber value={config.x} min={0} onChange={(val) => { if (val != null) { onChange({ ...config, x: Number.parseInt(val.toString()) }); } }} /> </div> <div className="univer-grid univer-gap-1"> <div>Vertical Start Position</div> <InputNumber value={config.y} min={0} onChange={(val) => { if (val != null) { onChange({ ...config, y: Number.parseInt(val.toString()) }); } }} /> </div> </div> </div> </div> ); }; - common/debugger/tailwind.config.ts (233 bytes)
import type { Config } from 'tailwindcss'; import preset from '@univerjs-infra/shared/tailwind'; const config: Config = { presets: [preset], content: [ './src/**/*.{js,ts,jsx,tsx}', ], }; export default config; - common/debugger/tsconfig.json (171 bytes)
{ "extends": "@univerjs-infra/shared/tsconfigs/base", "compilerOptions": { "rootDir": "src", "outDir": "lib/types" }, "include": ["src"] } - common/shared/esbuild/index.ts (2292 bytes)
import fs from 'node:fs'; interface IResolveArgs { importer: string; path: string; } interface ILoadArgs { path: string; } interface IPluginBuild { onResolve( options: { filter: RegExp; namespace?: string }, callback: (args: IResolveArgs) => unknown ): void; onLoad( options: { filter: RegExp; namespace?: string }, callback: (args: ILoadArgs) => unknown ): void; } interface IEsbuildPlugin { name: string; setup: (build: IPluginBuild) => void; } export function ignoreGlobalCssPlugin(): IEsbuildPlugin { return { name: 'ignore-global-css', setup(build: IPluginBuild) { build.onResolve({ filter: /\/global\.css$/ }, (args: IResolveArgs) => { if (args.importer.includes('packages')) { return { path: args.path, namespace: 'ignore-global-css', pluginData: { importer: args.importer, }, }; } }); build.onLoad({ filter: /\/global\.css$/, namespace: 'ignore-global-css' }, () => { return { contents: '' }; }); }, }; } export function removeClassnameNewlinesPlugin(): IEsbuildPlugin { return { name: 'remove-classname-newlines', setup(build: IPluginBuild) { build.onLoad({ filter: /\.(tsx)$/ }, (args: ILoadArgs) => { const source = fs.readFileSync(args.path, 'utf8'); const transformedSource = source.replace( /className\s*=\s*{([^}]*?)}/gs, (_match: string, classNameValue: string) => { const cleanedValue = classNameValue.replace(/`([^`]*?)`/gs, (_templateMatch: string, templateContent: string) => { return `\`${templateContent.replace(/\s*\n\s*/g, ' ').trim()}\``; }); return `className={${cleanedValue.trim()}}`; } ); return { contents: transformedSource, loader: 'tsx', }; }); }, }; } - common/shared/eslint/config.ts (2081 bytes)
import type { Rules } from '@antfu/eslint-config'; import type { ESLint, Linter } from 'eslint'; import antfu from '@antfu/eslint-config'; import reactHooks from 'eslint-plugin-react-hooks'; import { facadePreset, headerPreset, indexEntryPreset, noBarrelImportPreset, penetratingPreset, specPreset, tailwindcssPreset, typescriptPreset, univerSourcePreset, } from './presets'; import { baseRules } from './rules'; export interface IUniverEslintConfigOptions { ignores?: string[]; header?: boolean; noFacadeImportsOutsideFacade?: { ignore?: string[]; }; rules?: Partial<Rules>; } export const createUniverEslintConfig = (options: IUniverEslintConfigOptions = {}) => { const configs: Linter.Config[] = [ { files: ['**/*.{js,mjs,cjs,jsx,ts,mts,cts,tsx}'], plugins: { 'react-hooks': reactHooks as unknown as ESLint.Plugin, }, rules: { ...baseRules, ...options.rules, }, }, penetratingPreset(), typescriptPreset(), indexEntryPreset(), univerSourcePreset({ noFacadeImportsOutsideFacade: options.noFacadeImportsOutsideFacade, }), facadePreset(), noBarrelImportPreset(), tailwindcssPreset(), specPreset(), ]; if (options.header ?? true) { configs.push(headerPreset()); } return antfu( { ignores: options.ignores, stylistic: { indent: 4, semi: true, }, e18e: false, regexp: false, react: true, pnpm: false, yaml: { overrides: { 'yaml/indent': ['error', 4, { indicatorValueIndent: 2 }], }, }, markdown: false, typescript: true, formatters: { css: true, html: true, }, }, ...configs ); }; - common/shared/eslint/index.ts (371 bytes)
export { createUniverEslintConfig } from './config'; export type { IUniverEslintConfigOptions } from './config'; export { facadePreset, headerPreset, indexEntryPreset, noBarrelImportPreset, penetratingPreset, specPreset, tailwindcssPreset, typescriptPreset, univerSourcePreset, } from './presets'; export { baseRules } from './rules'; - common/shared/eslint/plugins/no-external-imports-in-facade.spec.ts (2326 bytes)
/** * Copyright 2023-present DreamNum Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { RuleTester } from 'eslint'; import { describe, it } from 'vitest'; import noExternalImportsInFacade from './no-external-imports-in-facade'; const ruleTester = new RuleTester({ languageOptions: { ecmaVersion: 2022, sourceType: 'module', }, }); describe('no-external-imports-in-facade', () => { it('explains the facade package-entry migration path', () => { ruleTester.run('no-external-imports-in-facade', noExternalImportsInFacade, { valid: [ { code: 'import { PublicCommand } from "@univerjs/example";', filename: '/repo/packages/example/src/facade/f-univer.ts', }, { code: 'import { FThing } from "./f-thing";', filename: '/repo/packages/example/src/facade/f-univer.ts', }, ], invalid: [ { code: 'import { PrivateCommand } from "../commands/private.command";', filename: '/repo/packages/example/src/facade/f-univer.ts', errors: [ { message: 'Facade files are published as a separate package entry. Do not import package-internal runtime modules through "../commands/private.command"; it can duplicate module singletons when consumers import both the package root and the facade entry. Move the needed symbol to the package root export if necessary, then import it through the package name. Type-only imports should also use a public package entry.', }, ], }, ], }); }); }); - common/shared/eslint/plugins/no-external-imports-in-facade.ts (2443 bytes)
import type { Rule } from 'eslint'; import path from 'node:path'; function getImportSourceValue(node: Rule.Node): string | null { if (!('source' in node)) { return null; } const source = (node as { source?: { value?: unknown } }).source; if (!source || typeof source.value !== 'string') { return null; } return source.value; } function getRuleFilename(context: Rule.RuleContext): string { const filenameFromProperty = (context as { filename?: unknown }).filename; if (typeof filenameFromProperty === 'string' && filenameFromProperty) { return filenameFromProperty; } const getFilename = (context as { getFilename?: () => string }).getFilename; return typeof getFilename === 'function' ? getFilename.call(context) : ''; } const rule: Rule.RuleModule = { meta: { type: 'problem', docs: { description: 'Disallow imports from outside facade directory in facade files', }, messages: { noExternalImports: 'Facade files are published as a separate package entry. Do not import package-internal runtime modules through "{{importPath}}"; it can duplicate module singletons when consumers import both the package root and the facade entry. Move the needed symbol to the package root export if necessary, then import it through the package name. Type-only imports should also use a public package entry.', }, }, create(context) { const filename = getRuleFilename(context); const normalizedPath = filename.split(path.sep).join('/'); const isFacadeFile = normalizedPath.includes('/facade/'); if (!isFacadeFile) { return {}; } const currentDir = path.dirname(filename); return { ImportDeclaration(node: Rule.Node) { const importPath = getImportSourceValue(node); if (!importPath || !importPath.startsWith('.')) { return; } const resolvedPath = path.resolve(currentDir, importPath).split(path.sep).join('/'); if (!resolvedPath.includes('/facade/')) { context.report({ node, messageId: 'noExternalImports', data: { importPath }, }); } }, }; }, }; export default rule; - common/shared/eslint/plugins/no-facade-imports-outside-facade.ts (4364 bytes)
import type { Rule } from 'eslint'; import path from 'node:path'; interface IRuleOptions { ignore?: unknown[] } function getImportSourceValue(node: Rule.Node): string | null { if (!('source' in node)) { return null; } const source = (node as { source?: { value?: unknown } }).source; if (!source || typeof source.value !== 'string') { return null; } return source.value; } function normalizePath(filePath: string): string { return filePath.split(path.sep).join('/'); } function shouldIgnoreFile(normalizedFilePath: string, ignorePaths: readonly unknown[]): boolean { return ignorePaths.some((ignorePath: unknown) => { if (typeof ignorePath !== 'string') { return false; } const normalizedIgnorePath = normalizePath(ignorePath).replace(/^\.\//, ''); if (!normalizedIgnorePath) { return false; } return normalizedFilePath === normalizedIgnorePath || normalizedFilePath.endsWith(`/${normalizedIgnorePath}`) || normalizedFilePath.includes(normalizedIgnorePath); }); } function getRuleFilename(context: Rule.RuleContext): string { const filenameFromProperty = (context as { filename?: unknown }).filename; if (typeof filenameFromProperty === 'string' && filenameFromProperty) { return filenameFromProperty; } const getFilename = (context as { getFilename?: () => string }).getFilename; return typeof getFilename === 'function' ? getFilename.call(context) : ''; } const rule: Rule.RuleModule = { meta: { type: 'problem', docs: { description: 'Disallow imports containing facade in non-facade files', }, schema: [ { type: 'object', properties: { ignore: { type: 'array', items: { type: 'string', }, }, }, additionalProperties: false, }, ], messages: { noFacadeImports: 'Imports containing "facade" are not allowed in non-facade files: "{{importPath}}"', }, }, create(context) { const filename = getRuleFilename(context); const normalizedPath = normalizePath(filename); const [ruleOptions = {} as IRuleOptions] = context.options as [IRuleOptions?]; const ignorePaths = Array.isArray(ruleOptions.ignore) ? ruleOptions.ignore : []; if (shouldIgnoreFile(normalizedPath, ignorePaths)) { return {}; } const isInPackages = normalizedPath.includes('/packages/'); const isInFacade = normalizedPath.includes('/facade/'); if (!isInPackages || isInFacade) { return {}; } // get parent dir const parentDirMatch = normalizedPath.match(/\/([^/]+)\/packages\//); if (!parentDirMatch) { return {}; } return { ImportDeclaration(node: Rule.Node) { const importPath = getImportSourceValue(node); // Check if the import path contains 'facade' if (importPath?.includes('facade')) { context.report({ node, messageId: 'noFacadeImports', data: { importPath }, }); } }, ExportNamedDeclaration(node: Rule.Node) { const exportPath = getImportSourceValue(node); if (exportPath?.includes('facade')) { context.report({ node, messageId: 'noFacadeImports', data: { importPath: exportPath }, }); } }, ExportAllDeclaration(node: Rule.Node) { const exportPath = getImportSourceValue(node); if (exportPath?.includes('facade')) { context.report({ node, messageId: 'noFacadeImports', data: { importPath: exportPath }, }); } }, }; }, }; export default rule; - common/shared/eslint/plugins/no-mixed-type-specifiers-in-index.ts (4360 bytes)
import type { Rule, SourceCode } from 'eslint'; import path from 'node:path'; type ImportOrExportSpecifier = Rule.Node & { importKind?: 'type' | 'value'; exportKind?: 'type' | 'value'; }; function normalizePath(filePath: string): string { return filePath.split(path.sep).join('/'); } function getRuleFilename(context: Rule.RuleContext): string { const filenameFromProperty = (context as { filename?: unknown }).filename; if (typeof filenameFromProperty === 'string' && filenameFromProperty) { return filenameFromProperty; } const getFilename = (context as { getFilename?: () => string }).getFilename; return typeof getFilename === 'function' ? getFilename.call(context) : ''; } function isSrcIndexFile(context: Rule.RuleContext): boolean { return normalizePath(getRuleFilename(context)).endsWith('/src/index.ts'); } function isInlineTypeSpecifier(specifier: ImportOrExportSpecifier, kind: 'import' | 'export'): boolean { return kind === 'import' ? specifier.importKind === 'type' : specifier.exportKind === 'type'; } function trimInlineTypeKeyword(specifierText: string): string { return specifierText.replace(/^type\s+/, ''); } function buildReplacement( sourceCode: SourceCode, node: Rule.Node, kind: 'import' | 'export' ): string | null { const specifiers = (node as { specifiers?: ImportOrExportSpecifier[] }).specifiers; if (!specifiers?.length) { return null; } const typeSpecifiers = specifiers.filter((specifier) => isInlineTypeSpecifier(specifier, kind)); const valueSpecifiers = specifiers.filter((specifier) => !isInlineTypeSpecifier(specifier, kind)); if (typeSpecifiers.length === 0 || valueSpecifiers.length === 0) { return null; } const nodeText = sourceCode.getText(node); const openingBraceIndex = nodeText.indexOf('{'); const closingBraceIndex = nodeText.lastIndexOf('}'); if (openingBraceIndex === -1 || closingBraceIndex === -1 || closingBraceIndex < openingBraceIndex) { return null; } const suffixWithSemicolon = nodeText.slice(closingBraceIndex + 1); const hasSemicolon = suffixWithSemicolon.trimEnd().endsWith(';'); const suffix = hasSemicolon ? suffixWithSemicolon.replace(/;\s*$/, '') : suffixWithSemicolon; const semicolon = hasSemicolon ? ';' : ''; const valueSpecifierText = valueSpecifiers.map((specifier) => sourceCode.getText(specifier)).join(', '); const typeSpecifierText = typeSpecifiers .map((specifier) => trimInlineTypeKeyword(sourceCode.getText(specifier))) .join(', '); return `${kind} { ${valueSpecifierText} }${suffix}${semicolon}\n${kind} type { ${typeSpecifierText} }${suffix}${semicolon}`; } const rule: Rule.RuleModule = { meta: { type: 'suggestion', docs: { description: 'Disallow mixing inline type specifiers with value specifiers in src/index.ts', }, fixable: 'code', messages: { noMixedExportSpecifiers: 'Do not mix type and value export specifiers in src/index.ts.', noMixedImportSpecifiers: 'Do not mix type and value import specifiers in src/index.ts.', }, }, create(context) { if (!isSrcIndexFile(context)) { return {}; } return { ImportDeclaration(node: Rule.Node) { const replacement = buildReplacement(context.sourceCode, node, 'import'); if (!replacement) { return; } context.report({ node, messageId: 'noMixedImportSpecifiers', fix(fixer) { return fixer.replaceText(node, replacement); }, }); }, ExportNamedDeclaration(node: Rule.Node) { const replacement = buildReplacement(context.sourceCode, node, 'export'); if (!replacement) { return; } context.report({ node, messageId: 'noMixedExportSpecifiers', fix(fixer) { return fixer.replaceText(node, replacement); }, }); }, }; }, }; export default rule; - common/shared/eslint/plugins/no-self-package-imports.ts (2783 bytes)
import type { Rule } from 'eslint'; import path from 'node:path'; function getImportSourceValue(node: Rule.Node): string | null { if (!('source' in node)) { return null; } const source = (node as { source?: { value?: unknown } }).source; if (!source || typeof source.value !== 'string') { return null; } return source.value; } function getRuleFilename(context: Rule.RuleContext): string { const filenameFromProperty = (context as { filename?: unknown }).filename; if (typeof filenameFromProperty === 'string' && filenameFromProperty) { return filenameFromProperty; } const getFilename = (context as { getFilename?: () => string }).getFilename; return typeof getFilename === 'function' ? getFilename.call(context) : ''; } const rule: Rule.RuleModule = { meta: { type: 'problem', docs: { description: 'Disallow self package imports in packages directory except facade', }, messages: { noSelfImport: 'Package cannot import itself: "{{importPath}}" in {{packageName}}', }, }, create(context) { const filename = getRuleFilename(context); const normalizedPath = filename.split(path.sep).join('/'); const isInPackages = normalizedPath.includes('/packages/'); const isInFacade = normalizedPath.includes('/facade/'); if (!isInPackages || isInFacade) { return {}; } // get parent dir const parentDirMatch = normalizedPath.match(/\/([^/]+)\/packages\//); if (!parentDirMatch) { return {}; } const parentDir = parentDirMatch[1]; const packagePrefix = parentDir === 'univer' ? '@univerjs/' : parentDir === 'univer-pro' ? '@univerjs-pro/' : null; if (!packagePrefix) { return {}; } // get package name const packageMatch = normalizedPath.match(/\/packages\/([^/]+)/); if (!packageMatch) { return {}; } const packageName = packageMatch[1]; const possiblePackageName = `${packagePrefix}${packageName}`; return { ImportDeclaration(node: Rule.Node) { const importPath = getImportSourceValue(node); if (importPath && importPath === possiblePackageName) { context.report({ node, messageId: 'noSelfImport', data: { importPath, packageName: importPath, }, }); } }, }; }, }; export default rule; - common/shared/eslint/presets.ts (9359 bytes)
import type { ESLint, Linter } from 'eslint'; import os from 'node:os'; import path from 'node:path'; import { fixupPluginRules } from '@eslint/compat'; import typescriptParser from '@typescript-eslint/parser'; import eslintPluginBetterTailwindcss from 'eslint-plugin-better-tailwindcss'; import header from 'eslint-plugin-header'; import barrel from 'eslint-plugin-no-barrel-import'; import penetrating from 'eslint-plugin-no-penetrating-import'; import noExternalImportsInFacade from './plugins/no-external-imports-in-facade'; import noFacadeImportsOutsideFacade from './plugins/no-facade-imports-outside-facade'; import noMixedTypeSpecifiersInIndex from './plugins/no-mixed-type-specifiers-in-index'; import noSelfPackageImports from './plugins/no-self-package-imports'; const univerPlugin = { rules: { 'no-external-imports-in-facade': noExternalImportsInFacade, 'no-self-package-imports': noSelfPackageImports, 'no-facade-imports-outside-facade': noFacadeImportsOutsideFacade, 'no-mixed-type-specifiers-in-index': noMixedTypeSpecifiersInIndex, }, } satisfies ESLint.Plugin; /** * TypeScript preset configuration for ESLint. * Applies TypeScript-specific rules and custom Univer rules. * * @returns ESLint configuration object for TypeScript files */ export const typescriptPreset = (): Linter.Config => { return { files: ['**/*.{ts,tsx,mts,cts}'], rules: { 'ts/naming-convention': [ 'warn', // Interfaces' names should start with a capital 'I'. { selector: 'interface', format: ['PascalCase'], custom: { regex: '^I[A-Z0-9]', match: true, }, }, // Private fields of a class should start with an underscore '_'. { selector: ['classMethod', 'classProperty'], modifiers: ['private'], format: ['camelCase'], leadingUnderscore: 'require', }, ], // 'ts/consistent-type-exports': 'warn', }, languageOptions: { parser: typescriptParser, }, }; }; /** * Index entry preset configuration for ESLint. * Keeps type-only imports and exports separate from value imports and exports. * * @returns ESLint configuration object for package entry files */ export const indexEntryPreset = (): Linter.Config => { return { files: ['**/src/index.ts'], rules: { 'univer/no-mixed-type-specifiers-in-index': 'error', }, plugins: { univer: univerPlugin, }, languageOptions: { parser: typescriptParser, }, }; }; /** * Univer source code preset configuration. * Enforces package structure rules for source files. * * @returns ESLint configuration object for Univer source files */ export const univerSourcePreset = (options: { noFacadeImportsOutsideFacade?: { ignore?: string[]; }; } = {}): Linter.Config => { return { files: ['**/*.ts', '**/*.tsx'], ignores: [ '**/__tests__/**/*', '**/*.spec.ts', '**/*.test.ts', ], rules: { 'univer/no-self-package-imports': 'error', 'univer/no-facade-imports-outside-facade': ['error', { ignore: options.noFacadeImportsOutsideFacade?.ignore ?? [], }], }, plugins: { univer: univerPlugin, }, languageOptions: { parser: typescriptParser, }, }; }; /** * Facade preset configuration for ESLint. * Enforces strict typing and import rules for facade files. * * @returns ESLint configuration object for facade files */ export const facadePreset = (): Linter.Config => { return { files: ['**/src/facade/**/*.ts'], ignores: [ '**/__tests__/**/*', '**/*.spec.ts', '**/*.test.ts', ], rules: { 'ts/explicit-function-return-type': 'error', 'univer/no-external-imports-in-facade': 'error', }, plugins: { univer: univerPlugin, }, }; }; /** * Tailwind CSS preset configuration for ESLint. * Enforces Tailwind CSS class usage and formatting rules. * * @returns ESLint configuration object for files using Tailwind CSS */ export const tailwindcssPreset = (): Linter.Config => { const isWindows = os.platform() === 'win32'; const lineBreakStyle = isWindows ? 'windows' : 'unix'; return { files: ['**/*.tsx'], languageOptions: { parserOptions: { ecmaFeatures: { jsx: true, }, }, }, plugins: { 'better-tailwindcss': eslintPluginBetterTailwindcss, }, settings: { 'better-tailwindcss': { tailwindConfig: path.resolve(__dirname, '../tailwind/tailwind.config.ts'), }, }, rules: { // enable all recommended rules to error ...eslintPluginBetterTailwindcss.configs['recommended-error'].rules, 'better-tailwindcss/enforce-consistent-line-wrapping': ['error', { printWidth: 120, group: 'newLine', lineBreakStyle, }], 'better-tailwindcss/no-unknown-classes': 'off', 'better-tailwindcss/no-conflicting-classes': 'off', }, }; }; /** * Test/spec files preset configuration for ESLint. * Relaxed rules for test files to allow more flexible testing patterns. * * @returns ESLint configuration object for test files */ export const specPreset = (): Linter.Config => { return { files: [ '**/*.spec.ts', '**/__tests__/**/*.ts', ], rules: { 'ts/explicit-function-return-type': 'off', }, }; }; /** * Penetrating import preset configuration for ESLint. * Prevents direct imports from internal package directories. * * @returns ESLint configuration object for preventing penetrating imports */ export const penetratingPreset = (): Linter.Config => { return { // Not penetrating for source files files: ['**/*.ts', '**/*.tsx'], plugins: { penetrating: fixupPluginRules(penetrating), }, ignores: [ '**/__tests__/**/*', '**/__testing__/**/*', 'examples/**/*', ], rules: { 'penetrating/no-penetrating-import': 2, }, }; }; /** * No barrel import preset configuration for ESLint. * Prevents barrel imports and enforces code complexity limits. * * @returns ESLint configuration object for preventing barrel imports */ export const noBarrelImportPreset = (): Linter.Config => { return { files: ['**/*.ts', '**/*.tsx'], ignores: [ 'packages/engine-render/src/components/docs/**/*.ts', '**/*.tsx', '**/*.d.ts', '**/tsdown.config.ts', '**/*.spec.ts', '**/*.spec.tsx', '**/*.test.ts', '**/*.test.tsx', ], // do not check test files plugins: { barrel: fixupPluginRules(barrel), }, rules: { 'barrel/no-barrel-import': 2, complexity: ['warn', { max: 20 }], 'max-lines-per-function': ['warn', 80], }, }; }; /** * Header preset configuration for ESLint. * Enforces Apache License 2.0 header in package and preset source files. * * @returns ESLint configuration object for enforcing file headers */ export const headerPreset = (): Linter.Config => { header.rules.header.meta.schema = false; return { files: ['{packages,presets}/**/*.{ts,tsx}'], ignores: [ '**/*.d.ts', '**/vitest.config.ts', '**/vitest.workspace.ts', ], plugins: { header: fixupPluginRules(header), }, rules: { 'header/header': [ 2, 'block', [ '*', ' * Copyright 2023-present DreamNum Co., Ltd.', ' *', ' * Licensed under the Apache License, Version 2.0 (the "License");', ' * you may not use this file except in compliance with the License.', ' * You may obtain a copy of the License at', ' *', ' * http://www.apache.org/licenses/LICENSE-2.0', ' *', ' * Unless required by applicable law or agreed to in writing, software', ' * distributed under the License is distributed on an "AS IS" BASIS,', ' * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.', ' * See the License for the specific language governing permissions and', ' * limitations under the License.', ' ', ], 2, ], }, }; }; - common/shared/eslint/rules.ts (6951 bytes)
import type { Rules } from '@antfu/eslint-config'; /** * Base ESLint rules configuration for Univer project. * These rules apply to all TypeScript and JavaScript files. */ const qualityRules: Partial<Rules> = { // Code style and formatting rules curly: ['error', 'multi-line'], 'antfu/if-newline': 'off', 'no-param-reassign': ['warn'], 'eol-last': ['error', 'always'], 'no-empty-function': 'off', }; const typescriptRules: Partial<Rules> = { // TypeScript specific rules 'ts/no-explicit-any': 'warn', 'ts/no-redeclare': 'off', 'ts/method-signature-style': 'off', }; const styleRules: Partial<Rules> = { // Style and formatting rules 'style/no-multiple-empty-lines': ['error', { max: 1, maxEOF: 0 }], 'style/brace-style': ['warn', '1tbs', { allowSingleLine: true }], 'style/jsx-first-prop-new-line': ['warn', 'multiline'], 'style/arrow-parens': ['error', 'always'], 'style/spaced-comment': 'off', 'style/indent-binary-ops': 'off', 'style/operator-linebreak': 'off', 'style/indent': ['error', 4, { ObjectExpression: 'first', SwitchCase: 1, ignoreComments: true, }], 'style/quotes': ['warn', 'single', { avoidEscape: true }], 'style/jsx-closing-tag-location': 'warn', 'style/jsx-curly-newline': ['warn', { multiline: 'forbid', singleline: 'forbid' }], 'style/jsx-wrap-multilines': 'warn', 'style/quote-props': ['warn', 'as-needed'], 'style/jsx-curly-brace-presence': 'warn', 'style/multiline-ternary': 'warn', // Comma and punctuation rules 'style/comma-dangle': ['error', { arrays: 'always-multiline', objects: 'always-multiline', imports: 'always-multiline', exports: 'always-multiline', enums: 'always-multiline', functions: 'never', }], }; const filenameRules: Partial<Rules> = { // Filename conventions 'unicorn/filename-case': [ 'error', { cases: { kebabCase: true, pascalCase: true, }, ignore: [ '^README-(\w+)?\\.md$', '^[a-z]{2}-[A-Z]{2}\.ts$', '^__tests__$', '^__testing__$', '^FUNDING.yml$', '^bug_report.yml$', '^bug_report.zh-CN.yml$', '^feature_request.yml$', '^feature_request.zh-CN.yml$', ], }, ], }; const reactRules: Partial<Rules> = { // JSX and React rules 'style/jsx-self-closing-comp': ['error', { component: true, html: true, }], 'react-refresh/only-export-components': 'off', 'react/no-unstable-context-value': 'warn', 'react/no-unstable-default-props': 'warn', 'react/no-direct-mutation-state': 'warn', 'react/no-create-ref': 'warn', 'react/rules-of-hooks': 'off', 'react/static-components': 'off', 'react/dom-no-render': 'off', 'react/unsupported-syntax': 'off', 'react/jsx-no-key-after-spread': 'off', 'react/use-memo': 'warn', 'react-hooks/static-components': 'off', 'react-hooks/preserve-manual-memoization': 'off', 'react-hooks/set-state-in-effect': 'off', 'react-hooks/refs': 'off', 'react-hooks/immutability': 'warn', 'react-hooks/use-memo': 'warn', 'react-hooks/purity': 'warn', 'react-hooks/globals': 'warn', }; const importRules: Partial<Rules> = { // Import and export rules 'sort-imports': [ 'error', { allowSeparatedGroups: false, ignoreCase: true, ignoreDeclarationSort: true, ignoreMemberSort: false, memberSyntaxSortOrder: ['none', 'all', 'multiple', 'single'], }, ], 'perfectionist/sort-imports': ['warn', { groups: [ ['type-builtin', 'type-external'], ['value-builtin', 'value-external'], 'type-internal', 'value-internal', ['type-parent', 'type-sibling', 'type-index'], ['value-parent', 'value-sibling', 'value-index'], 'side-effect', 'ts-equals-import', 'unknown', ], newlinesBetween: 0, newlinesInside: 0, }], 'perfectionist/sort-named-imports': 'off', 'perfectionist/sort-named-exports': 'warn', // Code quality rules 'accessor-pairs': 'warn', 'react-hooks/exhaustive-deps': 'off', 'react-hooks/rules-of-hooks': 'off', 'jsdoc/tag-lines': 'off', // Restricted imports for consistency 'no-restricted-imports': [ 'error', { paths: [ { name: 'clsx', message: 'Please use `import { clsx } from \'@univerjs/design\'` instead.', }, ], }, ], }; const disabledDebatableRules: Partial<Rules> = { // IMPORTANT: To ensure compatibility, some features of React 19 will be disabled. 'react/no-forward-ref': 'off', 'react/no-context-provider': 'off', 'react-dom/no-render': 'off', 'react/no-use-context': 'off', // Debatable rules - currently disabled 'test/prefer-lowercase-title': 'off', 'antfu/top-level-function': 'off', 'unicorn/no-new-array': 'off', 'unicorn/prefer-includes': 'off', 'prefer-arrow-callback': 'off', 'no-restricted-globals': 'off', 'unicorn/prefer-string-starts-ends-with': 'warn', }; const migrationWarningRules: Partial<Rules> = { // Compatibility rules for legacy code - set to warn for gradual migration 'unused-imports/no-unused-vars': 'warn', 'ts/no-restricted-types': 'warn', 'ts/no-wrapper-object-types': 'warn', 'ts/no-empty-object-type': 'warn', 'ts/no-unsafe-function-type': 'warn', 'ts/no-unused-expressions': 'warn', 'unicorn/prefer-dom-node-text-content': 'warn', 'unicorn/prefer-number-properties': 'warn', 'no-prototype-builtins': 'warn', 'eslint-comments/no-unlimited-disable': 'off', 'ts/prefer-ts-expect-error': 'off', 'ts/ban-ts-comment': 'off', 'ts/no-duplicate-enum-values': 'off', 'no-cond-assign': 'warn', 'ts/no-use-before-define': 'warn', 'test/no-identical-title': 'warn', 'ts/no-non-null-asserted-optional-chain': 'warn', 'no-restricted-syntax': 'warn', 'prefer-regex-literals': 'warn', 'ts/no-this-alias': 'warn', 'prefer-promise-reject-errors': 'warn', 'no-new': 'warn', 'unicorn/error-message': 'warn', 'ts/prefer-literal-enum-member': 'warn', 'no-control-regex': 'warn', 'ts/no-import-type-side-effects': 'warn', 'unicorn/number-literal-case': 'warn', 'unicorn/prefer-type-error': 'warn', }; export const baseRules: Partial<Rules> = { ...qualityRules, ...typescriptRules, ...styleRules, ...filenameRules, ...reactRules, ...importRules, ...disabledDebatableRules, ...migrationWarningRules, }; - CONTRIBUTING.md (8365 bytes)
<!-- https://univer.ai/guides/sheet/contributing/ --> # Univer Contributing Guide Welcome, and thank you for your interest in contributing to Univer! Please read our [Code of Conduct](./CODE_OF_CONDUCT.md) before you join in the Univer community. ## Asking Questions If you encounter any issues while using Univer, you can seek help in the following communities: - [Discord community](https://discord.gg/z3NKNT6D2f) - [GitHub Discussions](https://github.com/dream-num/univer/discussions) - Join the Univer Chinese community (please scan the QR code [here](https://univer.ai/contact)) ## Reporting Issues If you encounter any issues or have any suggestions while using Univer, please feel free to raise them in the Github Issues. We will respond promptly. To better assist you, we recommend: - Before submitting an issue, please search to see if someone has already raised a similar question. - We provide an [issue template](https://github.com/dream-num/univer/issues/new/choose) and encourage you to fill it out with sufficient information, which helps us quickly identify the problem. - Please try to describe the issue in English, as it enables more people to participate in the discussion. We will also make an effort to reply in English to benefit a wider audience. > If you're new to submitting issues, we recommend to read [How To Ask Questions The Smart Way](http://www.catb.org/~esr/faqs/smart-questions.html) and [How to Report Bugs Effectively](https://www.chiark.greenend.org.uk/~sgtatham/bugs.html) before posting. Well-written bug reports help us and help you! ## Contributing Code ### Install dependencies The development of Univer requires Node.js >= 22.18 and pnpm >= 11. Please make sure you have the correct versions installed. ```shell git clone https://github.com/dream-num/univer cd univer # install package manager pnpm npm i -g pnpm # install dependencies pnpm install ``` ### Start dev server ```shell pnpm dev ``` ### Architecture Please refer to [Architecture](https://docs.univer.ai/guides/recipes/architecture/univer), and also [ISOMORPHIC.md](./docs/ISOMORPHIC.md) for more guidance on how to set up plugins. For public API compatibility expectations, experimental APIs, internal APIs, and deprecation rules, read [API_STABILITY.md](./docs/API_STABILITY.md). ### Source code organization The structure of the repository is as follows: ```txt . ├── common/ shared configuration, mock data, Storybook, and utilities ├── docs/ documentation ├── examples/ all-in-one Vite workbench for browser development ├── packages/ Univer core and plugins ├── presets/ curated plugin collections └── tests/ additional integration test projects ``` The file structure of a plugin should be organized as follows: ```txt |- common/ |- models/ |- services/ |- commands/ |- commands/ |- mutations/ |- operations/ |- controllers/ |- views/ |- components/ |- parts/ |- plugin.ts |- index.ts ``` There are some limits on what paths could a file import from. - common cannot import file in other folders - models can only import files from common - services can only import files from models and common - commands can only import files from common, models and services During the refactoring process, it is recommended to remove legacy folders such as `Enum`, `Interface`, `Basics`, and `Shared`. Avoid creating barrel imports (index.ts) unless it is the main root index.ts file of a plugin. #### Desktop & Mobile We added experimental support for mobile platforms since June 2024. After that, all UI plugins should split ui related code by their running platforms: ```txt |- controllers/ |- render-controllers/ |- common/ |- desktop/ |- mobile/ |- views/ |- components/ |- common/ |- desktop/ |- mobile/ |- parts/ |- common/ |- desktop/ |- mobile/ ``` ### Connecting context To effectively contribute as a member of a software engineering team (and community as well!), it is crucial to establish strong contextual connections. Providing links to relevant resources can greatly assist others in understanding the context. Consider the following practices: - Include the link to the corresponding issue in your commit message. - Leave comments with links to the relevant context within the code. - Whenever possible, document important information directly within the codebase itself. By adopting these practices, you can enhance collaboration and facilitate a better understanding of the codebase within our community. ### Naming convention Please refer to [Univer Naming Convention](./docs/NAMING_CONVENTION.md). ### Submitting pull requests Before merging a pull request, please make sure the following requirements are met: - All tests pass. ESLint, including its formatting checks, passes. - Test coverage is not decreased. We provide preview deployments for pull requests. You can view the preview deployment by clicking the "Preview" link in the "View Deployment" section. ### Storybook We use Storybook to develop and test components in isolation. It is a great tool to develop UI components in isolation, which can improve component reuse, testability, and development efficiency. You can use the following command to start Storybook: ```shell pnpm storybook:dev ``` When a new pull request is submitted, a Storybook deployment will be automatically generated. You can view the Storybook deployment by clicking the "Preview" link in the "View Storybook" section. ### Debugging We provided some Visual Studio Code (vscode) tasks to help you debug in vscode. After stating dev server, you can launch Edge or Chrome instance and debug in vscode, and you can debug directly in vscode!  ### Unit test To ensure the quality of the code and move with confidence, we require that all code must be covered by unit tests. We use vitest as the unit test framework. You can use the following command to run unit tests: ```shell pnpm test ``` Also, with the help of vscode and its rich ecosystem, you could directly debug unit tests in vscode. Please install the extension we recommend, and you will see the debug button in the side bar. The `packages/*` glob in `vitest.workspace.ts` automatically includes new plugins created under `packages/`.  ### Browser workbench `pnpm dev` starts one Vite workbench with lazy-loaded Sheets and Docs routes. Use the navigation bar or `#sheets` and `#docs` URLs to switch products; only one Univer instance stays mounted. The Settings menu provides every built-in language, LTR/RTL direction, region, theme, appearance, ribbon, UI chrome, and zoom controls. Preferences are stored in localStorage and applied to the active instance through runtime APIs without remounting it. Development locale data is loaded on demand so unused product and language graphs do not remain in Vite's memory. End-to-end suites should consume built packages outside this repository instead of coupling tests to source examples. ### Build Preview Build the production artifacts to check for differences between the source and compiled output: ```shell pnpm build pnpm dev:umd ``` ### Clean code > Programs are meant to be ready by humans and only incidentally for computers to execute. - Harold Abelson - Do not expose properties or methods those are not necessary to be exposed. - Group related methods or properties together. Do not always use blank lines to separate them. - Keep your concepts consistent by naming your variables consistently. References: - [Make your code readable](https://www.notonlycode.org/make-your-code-readable/) ### New Package Create a new package with our CLI tool: ```shell # pnpm pnpm create @univerjs/cli init <project-name> # npm npm create @univerjs/cli init <project-name> ``` ### How to Contribute to Facade API Please refer to [How to Contribute to Facade API](./docs/CONTRIBUTING-FACADE.md). ### Deprecate API Follow the [deprecation requirements](./docs/API_STABILITY.md#deprecated) in the API Stability Policy for JSDoc annotations, runtime warnings, and migration guidance. Removing or incompatibly changing a deprecated API still requires a [breaking-change notice](./docs/API_STABILITY.md#breaking-changes). - DREAMNUM.md (3959 bytes)
# dream-num/univer > The open-source, isomorphic office SDK for building embeddable spreadsheet and document experiences in browsers and Node.js. ## Responsibilities ### Owns - The open-source Univer runtime, plugin system, command and service infrastructure, Facade API, formula engine, and Canvas rendering engine. See the [repository overview](README.md#-what-is-univer). - Open-source models, editing capabilities, and UI plugins for Sheets and Docs, including shared drawing, commenting, validation, formatting, and localization infrastructure. See the [open-source capability boundary](README.md#-open-source-and-pro). - Browser, Node.js, and Web Worker integration paths, plus React-based UI and Vue 3 and Web Component adapters. See the [compatibility and integration overview](README.md#-compatibility). - First-party open-source package presets and the examples and test projects used to exercise the SDK. See the [workspace definition](pnpm-workspace.yaml) and [repository guide](README.md#-repository-guide). - Public API compatibility rules for stable, experimental, internal, and deprecated interfaces. See the [API Stability Policy](docs/API_STABILITY.md). The repository does not own Univer Pro's commercial collaboration, import/export, server, or enterprise capabilities; those are a separate extension layer described in the [open-source and Pro boundary](README.md#-open-source-and-pro). ## Provides - `@univerjs/core`, `@univerjs/engine-formula`, and `@univerjs/engine-render` — Core runtime and data models, Facade APIs, formula calculation, and shared rendering. Contract: [package manifests](packages/core/package.json) and [API reference](https://docs.univer.ai/reference/classes/univer). - `@univerjs/sheets`, `@univerjs/docs`, and their UI and feature packages — Composable office models, plugins, and editing interfaces. Contract: [package directory](packages) and [API stability rules](docs/API_STABILITY.md). - `@univerjs/presets` and `@univerjs/preset-*` — Curated plugin collections for browser and Node.js integrations. Contract: [preset packages](presets/packages) and [preset-mode guide](README.md#-quick-start). - `@univerjs/ui-adapter-vue3` and `@univerjs/ui-adapter-web-component` — Framework adapters for integrating Univer UI services. Contract: [Vue 3 adapter](packages/ui-adapter-vue3/README.md) and [Web Component adapter](packages/ui-adapter-web-component/README.md). - `sync-univer` repository-dispatch event — Notifies the separate Univer Pro repository after changes reach `dev`. Contract: [dispatch workflow](.github/workflows/dispatch-sync-univer-pro.yml). ## Depends on - [`dream-num/univer-icons`](https://github.com/dream-num/univer-icons) — Owns the React icon components and SVG assets consumed by Univer UI packages. Contract: [`@univerjs/ui` manifest](packages/ui/package.json) and [SVG asset dependency](packages/sheets-conditional-formatting/package.json). - [`jikkai/verso`](https://github.com/jikkai/verso) — Owns the workspace release CLI used to version and tag Univer packages. Contract: [root package manifest](package.json). ## Authoritative sources - **Product documentation:** [docs.univer.ai](https://docs.univer.ai). - **API reference:** [Univer Facade API](https://docs.univer.ai/reference/classes/univer). - **Development guidance:** [README.md](README.md) and [CONTRIBUTING.md](CONTRIBUTING.md). - **Package contracts:** [`packages/`](packages), [`presets/`](presets), and [API Stability Policy](docs/API_STABILITY.md). - **Package release source:** [npm release workflow](.github/workflows/release-npm.yml). - **Security policy:** [SECURITY.md](SECURITY.md). ## Update contract Update this file in the same change when any of these facts change: - repository responsibilities or boundaries; - outgoing cross-repository dependencies; - public packages, APIs, protocols, events, images, or data contracts; - deployment source, runbook, or data classification.
- eslint.config.ts (326 bytes)
import { createUniverEslintConfig } from '@univerjs-infra/shared/eslint'; export default createUniverEslintConfig({ ignores: [ 'pnpm-lock.yaml', 'examples/public', ], header: true, noFacadeImportsOutsideFacade: { ignore: [ 'presets/packages/preset-', ], }, }); - INSTRUCTIONS.md (614 bytes)
You are the autonomous runtime coordinator for univer. System Archetype: agent. Description: Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core. Core Directives: 1. Execute operations deterministically following verified repository manifests. 2. Strictly enforce safe input validation and local-first execution boundaries. 3. Provide structured outputs, formatted logs, and actionable resolution steps. 4. Preserve data integrity and respect local workspace isolation.
- LICENSE (10173 bytes)
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS - package.json (2720 bytes)
{ "name": "univer", "type": "module", "version": "1.5.0", "private": true, "packageManager": "[email protected]", "author": "DreamNum Co., Ltd. <[email protected]>", "license": "Apache-2.0", "funding": { "type": "opencollective", "url": "https://opencollective.com/univer" }, "homepage": "https://univer.ai", "repository": { "type": "git", "url": "https://github.com/dream-num/univer" }, "bugs": { "url": "https://github.com/dream-num/univer/issues" }, "devEngines": { "runtime": { "name": "node", "version": ">=22.18" } }, "scripts": { "prepare": "husky", "pre-commit": "lint-staged", "dev": "pnpm --filter univer-examples dev", "dev:umd": "serve .", "typecheck": "turbo typecheck", "serve:umd": "serve .", "test": "turbo test -- --passWithNoTests", "coverage": "turbo --concurrency 50% coverage -- --passWithNoTests ", "analyze:build": "node --experimental-strip-types ./scripts/build-analysis.mts", "build": "pnpm run build:plugins && pnpm run build:presets", "build:ci": "pnpm run build", "build:plugins": "turbo build --filter '!./common/*' --filter '!./presets/**'", "build:presets": "turbo build --filter './presets/**...' --filter '!./presets/**' && turbo build --filter './presets/**'", "lint": "eslint .", "storybook:dev": "pnpm --filter @univerjs/storybook dev:storybook", "storybook:build": "pnpm --filter @univerjs/storybook build:storybook", "release": "verso" }, "devDependencies": { "@amamo/verso": "1.3.0", "@antfu/eslint-config": "^9.2.0", "@commitlint/cli": "^21.2.4", "@commitlint/config-conventional": "^21.2.4", "@eslint-react/eslint-plugin": "^5.28.8", "@eslint/compat": "^2.1.1", "@types/node": "^26.6.6", "@types/react": "19.3.0", "@types/react-dom": "19.3.0", "@univerjs-infra/shared": "workspace:*", "@univerjs/design": "workspace:*", "eslint": "^10.14.0", "eslint-plugin-format": "^2.0.1", "eslint-plugin-react": "^7.37.5", "eslint-plugin-react-hooks": "^7.1.1", "eslint-plugin-react-refresh": "^0.5.7", "husky": "^9.1.7", "lint-staged": "^17.6.0", "react": "19.3.1", "react-dom": "19.3.1", "serve": "^14.2.7", "tailwindcss": "3.4.18", "tsrs": "0.23.0-ts7.1.0-beta", "turbo": "^2.11.10", "typescript": "^6.0.3", "vitest": "^5.1.0" }, "lint-staged": { "*": "eslint --fix" } } - pnpm-workspace.yaml (467 bytes)
packages: - common/* - examples - presets - presets/packages/* - packages/* - tests/* publicHoistPattern: - '@storybook/react' allowBuilds: '@parcel/watcher': false '@swc/core': false esbuild: false protobufjs: false overrides: '@types/react': 19.3.0 '@types/react-dom': 19.3.0 react: 19.3.0 react-dom: 19.3.0 minimumReleaseAgeExclude: - '@amamo/*' - '@univerjs/*' - [email protected] - README.md (51328 bytes)
<a id="readme-top"></a> <p align="center"><img src="./docs/img/readme/hero-banner.png" alt="Univer Office SDK" width="960" /></p> <h1 align="center">Build your own AI office with Univer Office SDK.</h1> <p align="center">Start with open-source Sheets and Docs, then connect your own application or agent.</p> <p align="center"><a href="#quick-start">🚀 Quick start</a> · <a href="https://docs.univer.ai/">📚 Documentation</a> · <a href="https://univer.ai/compare/">⚖️ Feature comparison</a> · <a href="https://univer.ai/">🌐 Website</a> · <a href="https://docs.univer.ai/showcase">🎮 Showcase</a> · <a href="https://docs.univer.ai/reference/classes/univer">🔧 API Reference</a> · <a href="https://docs.univer.ai/blog">📝 Blog</a></p> <p align="center"><strong>English</strong> · <a href="./docs/readme/fr-FR.md">Français</a> · <a href="./docs/readme/de-DE.md">Deutsch</a> · <a href="./docs/readme/es-ES.md">Español</a> · <a href="./docs/readme/zh-CN.md">简体中文</a> · <a href="./docs/readme/zh-TW.md">繁體中文</a> · <a href="./docs/readme/ja-JP.md">日本語</a> · <a href="./docs/readme/ko-KR.md">한국어</a></p> <p align="center"> <a href="https://github.com/dream-num/univer/releases"><img src="https://img.shields.io/github/v/release/dream-num/univer?style=flat&labelColor=30363D&color=4F46E5&logo=github&logoColor=white" alt="Release" /></a> <a href="./LICENSE"><img src="https://img.shields.io/github/license/dream-num/univer?style=flat&labelColor=30363D&color=0F766E" alt="License" /></a> <a href="https://github.com/dream-num/univer/actions/workflows/build-packages.yml"><img src="https://img.shields.io/github/actions/workflow/status/dream-num/univer/build-packages.yml?style=flat&labelColor=30363D" alt="Build" /></a> <a href="https://www.codefactor.io/repository/github/dream-num/univer/overview/dev"><img src="https://www.codefactor.io/repository/github/dream-num/univer/badge/dev?style=flat" alt="CodeFactor" /></a> <a href="https://codecov.io/gh/dream-num/univer"><img src="https://img.shields.io/codecov/c/gh/dream-num/univer?token=aPfyW2pIMN&style=flat&labelColor=30363D" alt="Codecov" /></a> </p> <p align="center"> <a href="https://github.com/dream-num/univer"><img src="https://img.shields.io/github/stars/dream-num/univer?style=flat&labelColor=30363D&color=4F46E5" alt="Stars" /></a> <a href="https://github.com/dream-num/univer/graphs/contributors"><img src="https://img.shields.io/github/contributors/dream-num/univer?style=flat&labelColor=30363D&color=4F46E5" alt="Contributors" /></a> <a href="https://github.com/dream-num/univer/issues"><img src="https://img.shields.io/github/issues/dream-num/univer?style=flat&labelColor=30363D&color=4F46E5" alt="Issues" /></a> <a href="https://github.com/dream-num/univer/commits/dev/"><img src="https://img.shields.io/github/last-commit/dream-num/univer?style=flat&labelColor=30363D&color=4F46E5" alt="Last Commit" /></a> </p> <p align="center"> <a href="https://discord.gg/z3NKNT6D2f"><img src="https://img.shields.io/discord/1136129819961217077?logo=discord&logoColor=FFFFFF&label=discord&color=5865F2&style=flat&labelColor=30363D" alt="Discord" /></a> <a href="https://twitter.com/univerhq"><img src="https://img.shields.io/badge/%40univerhq-18181B?style=flat&logo=x&logoColor=white" alt="X: @univerhq" /></a> <a href="https://opencollective.com/univer"><img src="https://img.shields.io/opencollective/all/univer?logo=opencollective&style=flat&labelColor=30363D&color=0F766E&label=supporters&logoColor=white" alt="Open Collective" /></a> </p> <p align="center"> <a href="https://trendshift.io/repositories/4376"><img src="https://trendshift.io/api/badge/repositories/4376" alt="Trendshift" /></a> </p> <details> <summary>Table of contents</summary> - [💡 What is Univer?](#what-is-univer) - [Open-source capabilities](#open-source-capabilities) - [🚀 Build on the open-source foundation](#what-you-can-build) - [Quick start: an open-source spreadsheet editor](#quick-start) - [Connect your application to editable content](#connect-your-application-to-editable-content) - [🏗️ Explore the open-source architecture](#open-source-architecture) - [Give custom features clear boundaries](#give-custom-features-clear-boundaries) - [Compose cross-feature edits and undo/redo](#compose-cross-feature-edits-and-undoredo) - [Connect applications and agents through Facade APIs and events](#connect-applications-and-agents-through-facade-apis-and-events) - [🧩 Extend your application with Univer Office SDK](#open-source-and-commercial-extensions) - [Scope and licensing](#scope-and-licensing) - [🌐 Application patterns and ecosystem](#application-patterns-and-ecosystem) - [Univer Workspace: an Office SDK reference application](#univer-workspace-an-office-sdk-reference-application) - [CLI, agent integrations, and developer skills](#cli-agent-integrations-and-developer-skills) - [📚 Documentation and contributing](#documentation-and-contributing) - [Runtime compatibility](#runtime-compatibility) - [💬 Community](#community) - [🔒 Security](#security) - [❤️ Sponsors](#sponsors) - [📄 License](#license) </details> <a id="what-is-univer"></a> ## 💡 What is Univer? <p align="center"><img src="./docs/img/readme/intro-banner.png" alt="Univer Office SDK: Web, Server, and AI SDKs" width="960" /></p> **Univer** is an Office SDK for building Office applications inside your own product. It provides Office editing, calculation, collaboration, and file processing for people and existing agents, using your data and permissions. The product family covers spreadsheets, documents, presentations, relational tables, canvases, and PDFs. Univer Office SDK has three parts: - **Web SDK** is the foundation: content models, editing, rendering, formula calculation, and Facade APIs (application-facing APIs). Compose its plugins into an embedded editor or your own Office application, and reuse the content models, commands, and calculation for Headless processing without an interactive editor. - **Server SDK** adds backend services for real-time collaboration, edit history, and Office file import and export. - **AI SDK** connects Office capabilities to existing agents and workflows, with content tools, execution, and review integrations. **This repository provides the Web SDK's core architecture and engine implementations under Apache-2.0**: content models and snapshot formats, plugin and dependency management, the command system, formula and rendering engines, Facade APIs, UI foundation, and Sheets and Docs editing capabilities. Commercial Web SDK plugins, Server SDK, and commercial AI SDK extensions are distributed and licensed separately. Agents can use the same open-source APIs; your application supplies the model and tool orchestration. The [quotation example](#connect-your-application-to-editable-content) demonstrates editing, calculation, and saving without an AI SDK dependency. <a id="open-source-capabilities"></a> ### Open-source capabilities <div align="center" style="overflow-x: auto;"> <table align="center" style="display: table; width: auto; margin-left: auto; margin-right: auto;"> <thead> <tr> <th>Area</th> <th>Selected capabilities</th> </tr> </thead> <tbody> <tr> <td><strong>Sheets · Editing and layout</strong></td> <td>Cell styles, merged cells, in-cell rich text, freeze panes, floating images, and undo/redo.</td> </tr> <tr> <td><strong>Sheets · Data and calculation</strong></td> <td>Formulas, defined names, filtering, sorting, data validation, conditional formatting, hyperlinks, comments, and find and replace.</td> </tr> <tr> <td><strong>Docs</strong></td> <td>Rich-text editing, paragraph formatting, lists, hyperlinks, comments, and drawing integration.</td> </tr> </tbody> </table> </div> Features are composed through plugins and presets; the [quick start](#quick-start) uses only the **Sheets Core preset**. Images use the corresponding drawing plugins. See the [feature comparison](https://univer.ai/compare/) for detailed open-source and commercial coverage. The demos below showcase the wider **Univer Office SDK**, including commercial capabilities. They show more than the default open-source setup; see [open source and commercial extensions](#open-source-and-commercial-extensions) for scope. <div align="center" style="overflow-x: auto;"> <table align="center" style="display: table; width: auto; margin-left: auto; margin-right: auto;"> <tbody> <tr> <td width="50%"><a href="https://univer.ai/demo/spreadsheets"><img src="./docs/img/readme/cards/sheets.webp" alt="Sheets — Editing and layout · Data and calculation — Open demo" width="420" /></a></td> <td width="50%"><a href="https://univer.ai/demo/docs"><img src="./docs/img/readme/cards/docs.webp" alt="Docs — Rich-text editing — Open demo" width="420" /></a></td> </tr> <tr> <td width="50%"><a href="https://univer.ai/demo/web-app"><img src="./docs/img/readme/cards/web-app.webp" alt="Web App — Sheet-powered apps — Open demo" width="420" /></a></td> <td width="50%"><a href="https://univer.ai/demo/universe"><img src="./docs/img/readme/cards/universe.webp" alt="Univer — Composed Office content — Open demo" width="420" /></a></td> </tr> <tr> <td width="50%"><a href="https://univer.ai/demo/slides"><img src="./docs/img/readme/cards/slides.webp" alt="Slides — Open demo" width="420" /></a></td> <td width="50%"><a href="https://univer.ai/demo/relational-tables"><img src="./docs/img/readme/cards/relational-tables.webp" alt="Relational Tables — Open demo" width="420" /></a></td> </tr> <tr> <td width="50%"><a href="https://univer.ai/demo/canvases"><img src="./docs/img/readme/cards/canvases.webp" alt="Canvases — Open demo" width="420" /></a></td> <td width="50%"><a href="https://univer.ai/demo/pdf"><img src="./docs/img/readme/cards/pdf.webp" alt="PDF — Open demo" width="420" /></a></td> </tr> </tbody> </table> </div> <p align="right"><a href="#readme-top"><img src="https://img.shields.io/badge/%E2%86%91%20Back%20to%20top-30363D?style=flat-square" alt="Back to top" height="20" /></a></p> <a id="what-you-can-build"></a> ## 🚀 Build on the open-source foundation <p align="center"><img src="./docs/img/readme/build-banner.png" alt="Build on open source" width="960" /></p> <div align="center" style="overflow-x: auto;"> <table align="center" style="display: table; width: auto; margin-left: auto; margin-right: auto;"> <thead> <tr> <th>Your goal</th> <th>Use the open-source foundation</th> <th>Start here</th> </tr> </thead> <tbody> <tr> <td><strong>Embed Sheets or Docs</strong></td> <td>Add an editable Office surface to your application or agent product, and connect your data through Facade APIs.</td> <td><a href="#quick-start">Quick start</a></td> </tr> <tr> <td><strong>Process content without an editor</strong></td> <td>Reuse content plugins, models, commands, and calculation in Node.js for editing, snapshots, and automated tasks.</td> <td><a href="https://docs.univer.ai/guides/sheets/getting-started/node">Headless guide</a></td> </tr> <tr> <td><strong>Develop custom features or editors</strong></td> <td>Reuse the engines, UI components, plugin boundaries, dependency injection, and command/undo systems. Follow existing features to extend Sheets and Docs or develop your own editors.</td> <td><a href="#open-source-architecture">Open-source architecture</a></td> </tr> </tbody> </table> </div> **Coordinate edits and undo/redo across features.** Inserting a row inside a filter range changes both the base content and the filter range; undo needs to restore both. Each feature supplies its own changes and undo data, and the command composes their execution and history. The architecture walkthrough explains how to extend these editing workflows. <a id="quick-start"></a> ### Quick start: an open-source spreadsheet editor In a browser application using a bundler such as Vite: ```bash pnpm add @univerjs/presets @univerjs/preset-sheets-core ``` Create the container before initializing Univer: ```html <div id="app" style="height: 100vh"></div> ``` ```ts import { UniverSheetsCorePreset } from '@univerjs/preset-sheets-core' import UniverPresetSheetsCoreEnUS from '@univerjs/preset-sheets-core/locales/en-US' import { createUniver, LocaleType, mergeLocales } from '@univerjs/presets' import '@univerjs/preset-sheets-core/lib/index.css' const { univerAPI } = createUniver({ locale: LocaleType.EN_US, locales: { [LocaleType.EN_US]: mergeLocales(UniverPresetSheetsCoreEnUS), }, presets: [ UniverSheetsCorePreset({ container: 'app', }), ], }) univerAPI.createWorkbook({}) ``` Your page now contains a spreadsheet editor. Use the returned `univerAPI` to work with its content. This example uses open-source packages and needs no commercial Univer license or Server SDK. For component frameworks, retain the `univer` instance returned by `createUniver` and call `univer.dispose()` when the component unmounts. See the [lifecycle guide](https://docs.univer.ai/guides/sheets/getting-started/lifecycle). Presets compose plugins and register their Facade APIs. For manual control, see the [Plugin Mode example](#manual-plugin-composition) below. The [installation guide](https://docs.univer.ai/guides/sheets/getting-started/installation) covers both modes, peer dependencies, and framework integrations. Keep coordinated `@univerjs/*` packages on the same version. Commercial packages must use the matching release line; independently released packages such as icons follow their declared compatibility. See the [API Stability Policy](./docs/API_STABILITY.md). <a id="connect-your-application-to-editable-content"></a> ### Connect your application to editable content Facade APIs are the application-facing interface to workbooks, worksheets, and ranges. Continue from the quick start to populate a quotation, update a quantity from application code, and read the recalculated total: ```ts // Wait for formula controllers before editing a newly created workbook. await new Promise<void>((resolve) => { if (univerAPI.getCurrentLifecycleStage() >= univerAPI.Enum.LifecycleStages.Steady) { resolve() return } const listener = univerAPI.addEvent(univerAPI.Event.LifeCycleChanged, ({ stage }) => { if (stage === univerAPI.Enum.LifecycleStages.Steady) { listener.dispose() resolve() } }) }) const workbook = univerAPI.getActiveWorkbook()! const sheet = workbook.getActiveSheet() sheet.getRange('A1:D4').setValues([ ['Item', 'Quantity', 'Unit price', 'Amount'], ['Seats', 2, 25, '=B2*C2'], ['Support', 1, 100, '=B3*C3'], ['Total', '', '', '=SUM(D2:D3)'], ]) // An application control or agent can make the same edit. sheet.getRange('B2').setValue(4) univerAPI.getFormula().onCalculationResultApplied().then(() => { console.log(sheet.getRange('D4').getValue()) // 200 localStorage.setItem('quotation', JSON.stringify(workbo - SECURITY.md (3377 bytes)
# Security Policy This Security Policy outlines the security practices for Univer (SDK and Univer Services) to ensure the integrity of our code, dependencies, and data. We welcome contributions from community members, developers, and security researchers to identify and address potential security issues collaboratively. ## Supported Versions We provide security updates for the following versions of Univer. | Version | Supported | | ------- | ------------------ | | latest | :white_check_mark: | As Univer is still not reaching version 1.0 and we are moving fast with latest feature updates, unsupported versions may contain unpatched vulnerabilities. We recommend upgrading to the latest supported version. ## Reporting a Vulnerability We encourage responsible disclosure of security vulnerabilities. If you discover a potential issue, please follow these steps: 1. How to Report: - Email us at: [email protected] - Alternatively, submit a private Security Advisory via GitHub (if applicable). 2. What to Include: - Description: A detailed explanation of the vulnerability and its potential impact. - Steps to Reproduce: Clear instructions to replicate the issue. - Affected Versions: Specify which versions are impacted. - (Optional) Suggested Fix: Any recommendations for resolution. 3. Response Timeline: - We will acknowledge your report within 1 business days. - Depending on the severity, we aim to release a fix within 7-30 days. 4. Confidentiality: - Please refrain from disclosing vulnerability details in public Issues, forums, or social media until a fix is released. - We will publicly acknowledge your contribution after the fix (unless you request anonymity). ## Security Update Process - **Detection**: We use Dependabot and GitHub Security Alerts to automatically monitor for known vulnerabilities in dependencies. - **Resolution**: Upon identifying a vulnerability: 1. We prioritize releasing security patches for supported versions. 2. Dependencies are updated to non-vulnerable versions. 3. Updates are announced via GitHub Releases. - **Recommendation:** Users should regularly check for updates and apply the latest security patches. ## Guidelines for Developers To maintain a secure codebase, developers should adhere to these best practices: - **Dependency Management**: - Use Dependabot or similar tools to keep dependencies up to date. - Avoid using dependencies with known vulnerabilities. - **Code Review**: - All Pull Requests must be reviewed by at least one team member. - Check for proper input validation, access controls, and handling of sensitive data. - **Security Testing**: - Integrate static analysis tools (e.g., CodeQL) into the CI/CD pipeline. - Conduct periodic manual penetration testing. ## User Responsibilities - Keep your software updated to the latest version to benefit from security fixes. - Monitor the security status of your dependencies to avoid introducing third-party risks. - Report any discovered issues to us promptly. ## Contact Us For questions or further assistance, reach out to: - Email: [email protected] - GitHub Issues: https://github.com/dream-num/univer/issues ## Acknowledgments We extend our gratitude to all developers, researchers, and users who contribute to the security of this project! - turbo.json (440 bytes)
{ "$schema": "https://turbo.build/schema.json", "tasks": { "transit": { "dependsOn": ["^transit"] }, "test": { "dependsOn": ["transit"] }, "coverage": { "dependsOn": ["transit"], "outputs": ["coverage/**"], "env": ["CI"] }, "build": { "outputs": ["lib/**"] }, "typecheck": {} } } - verso.toml (328 bytes)
[version] root_package = "package.json" [workspaces] patterns = [ "common/*", "packages/*", "presets", "presets/packages/*", ] include_root = true [changelog] infile = "CHANGELOG.md" preset = "angular" [git] commit_message = "chore(release): release v${version}" tag_name = "v${version}" push = "follow-tags" - vitest.workspace.ts (134 bytes)
import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { projects: ['packages/*'], }, });