Skip to content

Commit

Permalink
feat: added custom image upload adapter
Browse files Browse the repository at this point in the history
  • Loading branch information
ctfdavis committed Mar 30, 2023
1 parent f569a0d commit 4565050
Show file tree
Hide file tree
Showing 23 changed files with 16,160 additions and 1 deletion.
4 changes: 4 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# tests
test/*.ts
e2e/**/*.ts
e2e/**/*.js
22 changes: 22 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"parser": "@typescript-eslint/parser",
"parserOptions": {
"project": "tsconfig.json",
"sourceType": "module"
},
"plugins": ["@typescript-eslint/eslint-plugin"],
"extends": ["plugin:@typescript-eslint/eslint-recommended", "plugin:@typescript-eslint/recommended", "prettier"],
"root": true,
"env": {
"jest": true
},
"rules": {
"@typescript-eslint/interface-name-prefix": "off",
"@typescript-eslint/explicit-function-return-type": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-use-before-define": "off",
"@typescript-eslint/no-unused-vars": "off",
"@typescript-eslint/explicit-module-boundary-types": "off",
"@typescript-eslint/ban-types": "off"
}
}
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

# tests
coverage
e2e/src
e2e/src/index.js

# dist
dist
Expand Down
4 changes: 4 additions & 0 deletions .husky/pre-commit
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

npx --no lint-staged
12 changes: 12 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# source
src/
test/
e2e/
ckeditor5/
tsconfig.json
jest.config.js
.*

# misc
LICENSE
README.md
11 changes: 11 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"singleQuote": true,
"printWidth": 200,
"proseWrap": "always",
"tabWidth": 4,
"useTabs": false,
"trailingComma": "none",
"bracketSpacing": true,
"jsxBracketSameLine": false,
"semi": true
}
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Davis Chan

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
62 changes: 62 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# CKEditor5 Custom Image Upload Adapter

A custom image upload adapter for CKEditor 5, allowing you to integrate your own file upload handler with additional options and callbacks.

## Installation

```bash
# npm
npm install --save ckeditor5-custom-image-upload-adapter

# yarn
yarn add ckeditor5-custom-image-upload-adapter

# pnpm
pnpm add ckeditor5-custom-image-upload-adapter
```

## Usage

First, import the `createCustomImageUploadAdapter` function:

```javascript
import { createCustomImageUploadAdapter } from 'ckeditor5-custom-image-upload-adapter';
```

Then, use the function to configure the image upload adapter for your CKEditor instance:

```typescript
extraPlugins: [
createCustomImageUploadAdapter(async function onSendRequest(file: File) {
// send file to server
// then return a url of the image
return 'https://picsum.photos/200/300'
})
]
```

## Explanation

The `createCustomImageUploadAdapter` function takes two parameters: `onSendRequest` and `options`. The `onSendRequest` parameter is a required callback function that handles the image upload request to the server and returns a Promise that resolves with the URL of the uploaded image. The options parameter is an optional object that can be used to configure the behavior of the custom image upload adapter.

The options parameter has the following properties:

- `defaultErrorMessageFactory`: A function that takes a file name as a parameter and returns a string that represents the default error message if the image upload fails. This property is optional.
- `onSendRequestFailure`: A callback function that takes an error object as a parameter and is called if the onSendRequest function throws an error. This property is optional.
- `onUpload`: A callback function that takes a File object as a parameter and is called when the file upload starts. This property is optional.

## Testing

The package is tested with both unit tests (`/test`) and e2e tests (`/e2e`).

To run the e2e tests, you must first build the e2e src:

```bash
npm run build:e2e
```

Then, run the e2e tests:

```bash
npm run test:e2e
```
15 changes: 15 additions & 0 deletions e2e/build/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// @ts-ignore
import ClassicEditor from '@ckeditor/ckeditor5-build-classic';
import { createCustomImageUploadAdapter } from '../../src'; // Import your package's function

const customImageUploadAdapter = createCustomImageUploadAdapter(onSendRequest);

ClassicEditor.create(document.querySelector('#editor'), {
extraPlugins: [customImageUploadAdapter]
}).catch((error: unknown) => {
console.error(error);
});

async function onSendRequest(file: File): Promise<string> {
return 'https://example.com/image.png';
}
49 changes: 49 additions & 0 deletions e2e/index.e2e-spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { Browser, Page } from 'puppeteer';

const puppeteer = require('puppeteer');
const path = require('path');

describe('File upload test', () => {
let browser: Browser;
let page: Page;

beforeAll(async () => {
browser = await puppeteer.launch({ headless: false });
page = await browser.newPage();
// Load the HTML containing the editor
await page.goto('file://' + path.join(__dirname, 'src', 'index.html'));
}, 20000);

afterAll(async () => {
await browser.close();
});

it('should upload the file and create an img element', async () => {
// Click the element with class ck-file-dialog-button
await page.click('.ck-file-dialog-button');

// Set up an input event listener to intercept the file selection
await page.evaluate(() => {
const inputElement = document.querySelector('input[type="file"]');
inputElement?.addEventListener('input', (event) => {
// Simulate a change event after setting the file
const changeEvent = new Event('change');
inputElement.dispatchEvent(changeEvent);
});
});

// Inject the test.png file and simulate a file selection event
const inputElement = await page.$('input[type="file"]');
const testImagePath = path.join(__dirname, 'test.png');
await inputElement?.uploadFile(testImagePath);

// Wait for the img element to be created with the expected src attribute
await page.waitForSelector('img[src="https://example.com/image.png"]', {
timeout: 5000
});

// Check if the img element is present in the page
const imgElement = await page.$('img[src="https://example.com/image.png"]');
expect(imgElement).toBeTruthy();
});
});
10 changes: 10 additions & 0 deletions e2e/jest-e2e.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"preset": "jest-puppeteer",
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testRegex": ".e2e-spec.ts$",
"verbose": true,
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}
12 changes: 12 additions & 0 deletions e2e/src/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CKEditor E2E Test</title>
</head>
<body>
<div id="editor"></div>
<script src="index.js"></script>
</body>
</html>
Empty file added e2e/test.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
22 changes: 22 additions & 0 deletions e2e/webpack-e2e.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const path = require('path');

module.exports = {
entry: path.resolve(__dirname, 'build', 'index.ts'),
mode: 'development',
output: {
filename: 'index.js',
path: path.resolve(__dirname, 'src')
},
resolve: {
extensions: ['.ts', '.js']
},
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
}
};
5 changes: 5 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom'
};
Loading

0 comments on commit 4565050

Please sign in to comment.