@domternal/extension-image

中文文档
1.8.1发布于 2026/11/08MITTypeScriptESM + CJS零依赖近 30 天下载 2425

Image node extension for Domternal editor

原始使用文档
文档目录9 节
  1. Install
  2. Quick start
  3. Upload files to your application
  4. Common options
  5. Commands and alt text
  6. Crop, rotate and mirror images
  7. Clipboard and source policy
  8. More documentation
  9. License

@domternal/extension-image

Version MIT License

Images for the Domternal editor, with resizing, alignment, text wrapping, alt text and file paste/drop support. Store files through your own upload handler or embed them as data URLs. Images are block nodes by default; inline images are optional.

Documentation · Examples

Install

The package declares Node.js 22 or later for tooling.

pnpm add @domternal/core @domternal/pm @domternal/extension-image @domternal/theme

Core and pm are peers with the range >=1.8.0 <2.0.0. Use version 1.8.1 for all installed Domternal Free packages. The optional theme provides the resize handles, placement styles and upload indicator; supply equivalent CSS if you omit it. Exported HTML includes placement styles independently of the theme.

Quick start

<div id="editor" class="dm-editor"></div>
import { Editor, StarterKit } from '@domternal/core';
import { Image } from '@domternal/extension-image';
import '@domternal/theme';

const editor = new Editor({
  element: document.getElementById('editor')!,
  extensions: [StarterKit, Image],
  content: '<p>Paste an image or add one by URL.</p>',
});

Add an image using a URL your application serves:

editor.chain().focus().setImage({
  src: '/uploads/photo.jpg',
  alt: 'A mountain reflected in a lake',
}).run();

Call editor.destroy() when removing the editor. The extension contributes image controls to Domternal's toolbar and bubble menu when those UI components are mounted; a bare Core editor does not create those components.

Upload files to your application

Without an upload handler, accepted files are embedded in the document as data URLs. To store files elsewhere, replace Image in the extension array with a configured instance. This example expects your own /api/upload endpoint to return JSON containing a url string:

Image.configure({
  allowBase64: false,
  allowedMimeTypes: ['image/jpeg', 'image/png', 'image/webp'],
  maxFileSize: 5 * 1024 * 1024,
  maxFiles: 5,
  uploadHandler: async (file) => {
    const form = new FormData();
    form.append('file', file);
    const response = await fetch('/api/upload', { method: 'POST', body: form });
    if (!response.ok) throw new Error('Image upload failed');

    const result = await response.json() as { url?: unknown };
    if (typeof result.url !== 'string' || !result.url) {
      throw new Error('The upload endpoint did not return an image URL');
    }
    return result.url;
  },
  onUploadError: (error) => {
    console.error(error.message);
  },
});

The same MIME, size and count rules apply to pasted, dropped and file-picker images. Validate uploads on your server too. Files keep their insertion order while asynchronous uploads finish. The theme renders the .domternal-image-uploading placeholder as a localized loading status with a light/dark indicator. It respects reduced motion and is hidden when printing. It is view-only, has no keyboard stop and never enters saved content or Undo history. A failed upload or deletion of its insertion point removes the loading indicator. See file insertion and undo for selection replacement, cancellation and collaborative edits.

Common options

OptionDefaultPurpose
inlinefalsePlace images inside text instead of as blocks.
enableTransformsfalseOpt into the image geometry schema attribute and crop, rotate and mirror commands.
placementnullLet the preset choose float or align controls; set 'float' or 'align' explicitly to override.
allowBase64trueAccept image data URLs and embed files when no upload handler is supplied.
uploadHandlernullStore a file and return its URL.
maxFileSize0Maximum bytes per file; 0 leaves size unlimited.
maxFiles10Maximum accepted files per operation; 0 removes the count limit.
allowedMimeTypesJPEG, PNG, GIF, WebP, SVG, AVIFMIME types accepted for files.

With allowBase64: false and no uploadHandler, files cannot be inserted. Remote image URLs can still be used. The full option reference also covers HTML attributes and upload callbacks.

Commands and alt text

CommandPurpose
setImage({ src, alt, ... })Insert an image with its attributes.
setImageFloat('left')Wrap text around the selected image.
setImageAlign('center')Align the selected image without text wrapping.
setImageTransform({ crop, rotation, flipX, flipY })With enableTransforms: true, replace the selected image's non-destructive geometry; null resets it.
deleteImage()Remove the selected image.

Float and align each accept 'none', 'left', 'center' and 'right'; setting one clears the other. Commands operate on the current selection.

Use a descriptive alt for meaningful images. alt: '' marks an image as decorative and renders alt=""; null means no description has been supplied and omits the attribute. See alt text editing.

Crop, rotate and mirror images

Free 1.6.0 adds non-destructive image geometry. Enable it explicitly in the editor's extension array:

Image.configure({ enableTransforms: true });

The default Image schema and ordinary image JSON stay unchanged. Enabling this option adds the imageTransform attribute, with a default of null. Update any strict application schema to allow that field and enable the option in every collaborating editor before storing transformed images. Editors without the option cannot preserve geometry from an enabled editor.

The imageTransform attribute keeps source bytes unchanged. Cropping uses fractions of the original image, followed by horizontal/vertical mirroring and clockwise rotation. The editor and saved HTML use a viewport with the rotated bounding box; resizing changes that box's width while preserving its aspect ratio.

editor.commands.setImageTransform({
  naturalWidth: 1600,
  naturalHeight: 900,
  crop: { left: 0.1, right: 0.1 },
  rotation: 90,
  flipX: true,
});

The command requires an image node selection. Omit naturalWidth and naturalHeight only when that image is loaded, or when its current transform already records them. setImage({ src, imageTransform: { ... } }) always needs explicit intrinsic dimensions. A command replaces the complete transform and is undoable; loading, rendering and exporting never author geometry in the document. Without enableTransforms: true, setImageTransform and setImage with an explicit transform or null return false without changing the document. No crop/rotation controls are added to the default menu.

Each crop edge must be between zero and one, with at least 1/65,536 of the image remaining in both directions. Intrinsic dimensions must be finite and between 1 and 1,000,000; rotation must be finite within plus or minus 1,000,000 degrees. Whole turns are normalized away. Invalid commands return false, malformed stored geometry renders as an ordinary image, and null or identity transforms keep ordinary image markup unchanged. The ImageTransform and SetImageTransformOptions types are exported for application controls.

Clipboard and source policy

A screenshot or image-only clipboard inserts image files. When copied content has text of its own, the HTML/text takes priority so Word's picture of a copied selection does not replace the actual content. Office HTML normalization is a separate opt-in PasteCleanup feature; Image alone does not apply its raster or structural limits.

Built-in parsing, commands and rendering apply Core's URL policy. A refused stored source remains in JSON but is not loaded by the node view. URL checks do not inspect remote response bytes. See image security and the URL policy reference.

More documentation

  • Image guide: inline mode, popovers, resizing, file handling and node views.
  • Clipboard destinations: cooperating with a custom image node.
  • Localization: imageMessages and optional @domternal/extension-image/locales/de catalogs. Authored alt text is never translated.

License

MIT.

版本与发布记录

@domternal/extension-image 共发布 47 个版本,首次发布于 2026/03/28;过去 12 个月发布了 47 个版本。

版本发布日期距今
1.8.1latest2026/11/085 天前
1.8.02026/10/2123 天前
1.7.02026/10/2024 天前
1.6.02026/10/1925 天前
1.5.12026/10/1628 天前
1.5.02026/10/1628 天前

关于 @domternal/extension-image 的常见问题

@domternal/extension-image 是什么?

Image node extension for Domternal editor

如何安装 @domternal/extension-image?

在项目目录运行 npm install @domternal/extension-image,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@domternal/pm(>=1.8.0 <2.0.0)、@domternal/core(>=1.8.0 <2.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@domternal/extension-image 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@domternal/extension-image 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@domternal/extension-image 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@domternal/extension-image 可以商用吗?

@domternal/extension-image 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@domternal/extension-image 的下载量有多少?

根据 npm 官方下载统计,@domternal/extension-image 在 2026/10/13 – 2026/11/11 这 30 天内被下载 2,425 次,日均约 81 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@domternal/extension-image 还在维护吗?

最新版本 1.8.1 发布于 2026/11/08(5 天前);至今共发布 47 个版本,其中过去 12 个月发布了 47 个;首次发布于 2026/03/28。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。