This repository has been archived by the owner on Nov 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathstylesLoader.ts
94 lines (73 loc) · 2.4 KB
/
stylesLoader.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/**
* @license Copyright (c) 2003-2023, CKSource Holding sp. z o.o. All rights reserved.
* For licensing, see LICENSE.md.
*/
import * as fs from 'node:fs';
import * as path from 'node:path';
import * as util from 'node:util';
const readFile = util.promisify( fs.readFile );
import { normalizePath, type Plugin } from 'vite';
import type { CKEditor5PluginOptions } from '../index';
import postcss, { type AcceptedPlugin } from 'postcss';
import postcssNesting from 'postcss-nesting';
import postcssMixins from 'postcss-mixins';
import postcssImport from 'postcss-import';
const postcssOptions = {
plugins: [
postcssNesting(),
postcssMixins(),
postcssImport()
]
} as unknown as Array<AcceptedPlugin>;
const stylesLoader = ( theme: CKEditor5PluginOptions['theme'] ): Plugin => {
return {
name: 'vite-ckeditor5-styles-loader',
enforce: 'pre',
async transform( code, id ) {
if ( !id.includes( 'ckeditor5-' ) || !id.endsWith( '.css' ) ) {
return;
}
const themeStyles = await loadThemeStyles( id, theme );
const stylesToLoad = code + themeStyles.code;
return loadPostcssFile( stylesToLoad, id );
}
};
};
export default stylesLoader;
async function loadThemeStyles( id: string, theme: string ) {
const themeFilePath = getThemeFilePath( id, theme );
if ( themeFilePath && fs.existsSync( themeFilePath ) ) {
const css = await readFile( themeFilePath );
const result = await postcss( postcssOptions ).process( css, { from: themeFilePath, map: { absolute: true, inline: true } } );
return { code: result.css.toString() };
}
return { code: '' };
}
async function loadPostcssFile( code: string, id: string ) {
const result = await postcss( postcssOptions ).process( code, { from: id, map: { absolute: true, inline: true } } );
return {
code: result.css.toString()
};
}
function getThemeFilePath( inputFilePath: string, theme: CKEditor5PluginOptions['theme'] ) {
const themeDir = path.dirname( theme );
const packageName = getPackageName( inputFilePath );
if ( !packageName ) {
return;
}
const inputFileName = inputFilePath.split(
normalizePath( path.join( packageName, 'theme', path.sep ) )
)[ 1 ];
if ( !inputFileName ) {
return;
}
return path.resolve( themeDir, packageName, inputFileName );
}
function getPackageName( inputFilePath: string ) {
const match = inputFilePath.match( /^.+[/\\](ckeditor5-[^/\\]+)/ );
if ( match ) {
return match.pop();
} else {
return null;
}
}