Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: new plugin configuration method #191

Merged
merged 2 commits into from
Dec 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions admin/custom.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,8 @@ declare global {
strapi: {
backendURL: string;
};
SH_CKE: {
IS_UPLOAD_RESPONSIVE: boolean;
};
}
}
2 changes: 1 addition & 1 deletion admin/src/components/CKEReact.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ export function CKEReact() {
uploadUrl: `${backendURL}/upload`,
backendUrl: backendURL,
headers: { Authorization: `Bearer ${token}` },
responsive: window.SH_CKE_UPLOAD_ADAPTER_IS_RESPONSIVE,
responsive: window.SH_CKE.IS_UPLOAD_RESPONSIVE,
};

StrapiUploadAdapterPlugin.initAdapter(config);
Expand Down
24 changes: 21 additions & 3 deletions admin/src/components/EditorProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
import type { InputProps } from '@strapi/strapi/admin';

import { type Preset, getClonedPreset, setUpLanguage } from '../config';
import { type Preset, setUpLanguage, getPluginConfig } from '../config';
import type { WordCountPluginStats } from './CKEReact';

type EditorProviderBaseProps = Pick<
Expand Down Expand Up @@ -54,8 +54,8 @@ export function EditorProvider({

useEffect(() => {
(async () => {
const currentPreset = getClonedPreset(presetName);

const { presets } = getPluginConfig();
const currentPreset = clonePreset(presets[presetName]);
await setUpLanguage(currentPreset.editorConfig, isFieldLocalized);

if (placeholder) {
Expand Down Expand Up @@ -132,3 +132,21 @@ export function EditorProvider({

return <EditorContext.Provider value={EditorContextValue}>{children}</EditorContext.Provider>;
}

function clonePreset(preset: Preset): Preset {
const clonedPreset = {
...preset,
editorConfig: {
...preset.editorConfig,
},
};

Object.entries(clonedPreset.editorConfig).forEach(([key, val]) => {
if (val && typeof val === 'object' && Object.getPrototypeOf(val) === Object.prototype) {
// @ts-ignore
clonedPreset.editorConfig[key] = { ...val };
}
});

return clonedPreset;
}
2 changes: 1 addition & 1 deletion admin/src/components/Field.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React from 'react';
import { type InputProps, type FieldValue } from '@strapi/strapi/admin';
import type { InputProps, FieldValue } from '@strapi/strapi/admin';

import { Editor } from './Editor';
import { EditorProvider } from './EditorProvider';
Expand Down
7 changes: 2 additions & 5 deletions admin/src/components/GlobalStyling.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import React from 'react';
import { createGlobalStyle, css } from 'styled-components';

import { defaultTheme } from '../theme';
import { getProfileTheme } from '../utils';
import type { Theme, Styles } from '../config';
import { type Theme, type Styles, getPluginConfig } from '../config';

const GlobalStyle = createGlobalStyle<{
$editortTheme?: Theme;
Expand All @@ -23,11 +22,9 @@ const getSystemColorScheme = (): 'light' | 'dark' =>
window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';

function GlobalStyling() {
const { theme: userTheme, dontMergeTheme } = window.SH_CKE_CONFIG || {};

const { theme } = getPluginConfig();
const profileTheme = getProfileTheme();
const variant = profileTheme && profileTheme !== 'system' ? profileTheme : getSystemColorScheme();
const theme = dontMergeTheme ? userTheme : { ...defaultTheme, ...userTheme };

return <GlobalStyle $editortTheme={theme} $variant={variant} />;
}
Expand Down
2 changes: 1 addition & 1 deletion admin/src/components/MediaLib.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ function MediaLib({ isOpen = false, toggle, handleChangeAssets }: MediaLibProps)

assets.forEach(({ name, url, alt, formats, mime, width, height }: any) => {
if (mime.includes('image')) {
if (formats && window.SH_CKE_UPLOAD_ADAPTER_IS_RESPONSIVE) {
if (formats && window.SH_CKE.IS_UPLOAD_RESPONSIVE) {
const set = formSet(formats);
newElems += `<img src="${url}" alt="${alt}" width="${width}" height="${height}" srcset="${set}" />`;
} else {
Expand Down
19 changes: 0 additions & 19 deletions admin/src/config/expToGlobal.ts

This file was deleted.

2 changes: 0 additions & 2 deletions admin/src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,3 @@ export * from './language';
export * from './pluginConfig';
export * from './colors';
export * from './defaultPreset';
export * from './presets';
export * from './expToGlobal';
43 changes: 24 additions & 19 deletions admin/src/config/pluginConfig.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,32 @@
import { defaultTheme } from '../theme';
import { defaultPreset } from './defaultPreset';
import type { PluginConfig } from './types';
import { PLUGIN_ID } from '../utils';

export async function getPluginConfig(): Promise<PluginConfig | null> {
const config = await loadConfig().catch(error => console.error('CKEditor: ', error));
const PLUGIN_CONFIG: PluginConfig = {
presets: {
default: defaultPreset,
},
theme: defaultTheme,
};

return config || null;
export function setPluginConfig(userConfig: Partial<PluginConfig>): void {
const { presets = PLUGIN_CONFIG.presets, theme = PLUGIN_CONFIG.theme } = userConfig;
PLUGIN_CONFIG.presets = presets;
PLUGIN_CONFIG.theme = theme;
deepFreeze(PLUGIN_CONFIG);
}

async function loadConfig(): Promise<PluginConfig | null> {
return new Promise((resolve, reject) => {
const { backendURL } = window.strapi;
const url =
backendURL !== '/'
? `${backendURL}/${PLUGIN_ID}/config/ckeditor`
: `/${PLUGIN_ID}/config/ckeditor`;

const script = document.createElement('script');
script.id = 'ckeditor-config';
script.src = url;

script.onload = () => resolve(window.SH_CKE_CONFIG);
script.onerror = () => reject(new Error('Failed loading config script'));
export function getPluginConfig(): PluginConfig {
if (!Object.isFrozen(PLUGIN_CONFIG)) deepFreeze(PLUGIN_CONFIG);
return PLUGIN_CONFIG;
}

document.body.appendChild(script);
function deepFreeze(obj: Object): Readonly<Object> {
(Object.keys(obj) as (keyof typeof obj)[]).forEach(p => {
if (typeof obj[p] === 'object' && obj[p] !== null && !Object.isFrozen(obj[p])) {
deepFreeze(obj[p]);
}
});

return Object.freeze(obj);
}
57 changes: 0 additions & 57 deletions admin/src/config/presets.ts

This file was deleted.

42 changes: 5 additions & 37 deletions admin/src/config/types.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,10 @@
import type { EditorConfig as CKE5EditorConfig } from 'ckeditor5';
import type { Interpolation } from 'styled-components';
import type { ExportToGlobal } from './expToGlobal';

export type PluginConfig =
| {
dontMergePresets: true;
presets: Record<string, Preset>;
dontMergeTheme?: boolean;
theme?: Theme;
}
| {
dontMergePresets?: false;
presets?: {
default: Partial<Preset>;
/**
* New presets must use Preset type.
* Partial is included only for compatibility
* with previous versions and should not be used.
*/
[k: string]: Preset | PartialIsNotAllowedForNewPresets;
};
dontMergeTheme?: boolean;
theme?: Theme;
};
export type PluginConfig = {
presets: Record<string, Preset>;
theme: Theme;
};

export type Theme = {
common?: Styles;
Expand All @@ -34,13 +16,7 @@ export type Theme = {
export type Preset = {
field: Field;
styles?: Styles;
editorConfig: Partial<EditorConfig>;
};

export type PartialIsNotAllowedForNewPresets = {
field?: Field;
styles?: Styles;
editorConfig?: Partial<EditorConfig>;
editorConfig: EditorConfig;
};

export type EditorConfig = CKE5EditorConfig;
Expand All @@ -64,11 +40,3 @@ export type IntlLabel = {
};

export type Styles = string | Interpolation<object>[];

declare global {
interface Window {
SH_CKE: ExportToGlobal;
SH_CKE_CONFIG: PluginConfig | null;
SH_CKE_UPLOAD_ADAPTER_IS_RESPONSIVE: boolean;
}
}
3 changes: 2 additions & 1 deletion admin/src/exports.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export type * from './config/types';
export { defaultPreset } from './config';
export { setPluginConfig, defaultPreset, materialColors } from './config';
export { StrapiMediaLib, StrapiUploadAdapter } from './plugins';
31 changes: 26 additions & 5 deletions admin/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,36 @@
import * as yup from 'yup';

import { PLUGIN_ID } from './utils';
import { getPresetsFields, getPluginConfig, exportToGlobal } from './config';
import { getPluginConfig, type Field } from './config';
import { CKEditorIcon } from './components/CKEditorIcon';

export * from './exports';

const AVAILABLE_OPTIONS: Field[] = [];

function fillUpOptions(): void {
const { presets } = getPluginConfig();
Object.values(presets).forEach(({ field }) => AVAILABLE_OPTIONS.push(field));
}

async function setUpGlobal() {
const { backendURL } = window.strapi;
const route = 'config/is-responsive-dimensions';
const url = backendURL !== '/' ? `${backendURL}/${PLUGIN_ID}/${route}` : `/${PLUGIN_ID}/${route}`;
const { isResponsiveDimensions } = await fetch(url).then(res => res.json());

window.SH_CKE = {
IS_UPLOAD_RESPONSIVE: isResponsiveDimensions,
};
}

// eslint-disable-next-line import/no-default-export
export default {
bootstrap() {
fillUpOptions();
},
async register(app: any): Promise<void> {
exportToGlobal();
const pluginConfig = await getPluginConfig();
const optionsPreset = getPresetsFields(pluginConfig);
await setUpGlobal();

app.customFields.register({
name: 'CKEditor',
Expand Down Expand Up @@ -43,7 +64,7 @@ export default {
},
name: 'options.preset',
type: 'select',
options: optionsPreset,
options: AVAILABLE_OPTIONS,
},
],
advanced: [
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@
"exports": {
"./package.json": "./package.json",
".": {
"types": "./dist/admin/src/exports.d.ts",
"source": "./admin/src/exports.ts",
"types": "./dist/admin/src/index.d.ts",
"source": "./admin/src/index.ts",
"import": "./dist/admin/index.mjs",
"require": "./dist/admin/index.js",
"default": "./dist/admin/index.js"
Expand Down
11 changes: 4 additions & 7 deletions server/src/controllers/configController.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,16 @@
import type { Core } from '@strapi/strapi';
import PLUGIN_ID from '../utils/pluginId';

export default function configController({ strapi }: { strapi: Core.Strapi }): Core.Controller {
return {
async getConfig(ctx): Promise<void> {
async isResponsiveDimensions(ctx): Promise<void> {
const { responsiveDimensions = false } = await strapi
.plugin('upload')
.service('upload')
.getSettings();

let config = await strapi.plugin(PLUGIN_ID).service('configService').readConfig();
config += `window.SH_CKE_UPLOAD_ADAPTER_IS_RESPONSIVE = ${responsiveDimensions}\n`;

ctx.type = 'application/javascript';
ctx.send(config);
ctx.send({
isResponsiveDimensions: responsiveDimensions,
});
},
};
}
2 changes: 0 additions & 2 deletions server/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import register from './register';
import controllers from './controllers';
import routes from './routes';
import services from './services';

export default {
register,
controllers,
routes,
services,
};
Loading