├── .gitignore
├── LICENSE
├── README.md
├── index.html
├── package-lock.json
├── package.json
├── src
└── index.ts
└── tsconfig.json
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | private/
3 | /locale
4 | node_modules/
5 | *.log
6 | _index.html
7 | dist/
8 | .npmrc
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License Copyright (c) 2020-current Grapesjs Style Bg
2 |
3 | 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:
4 |
5 | The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software.
6 |
7 | 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.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Grapesjs Style Bg
2 |
3 | Full-stack background style property type for GrapesJS, with the possibility to add images, colors, and gradients.
4 |
5 | > Requires GrapesJS v0.20.1 or higher
6 |
7 | 
8 |
9 | [DEMO](https://codepen.io/artf/pen/GRGXdYe)
10 |
11 | ## Summary
12 |
13 | * Plugin name: `grapesjs-style-bg`
14 | * This plugin updates the built-in `background` style property.
15 |
16 |
17 |
18 | ## Options
19 |
20 | | Option | Description | Default |
21 | |-|-|-
22 | | `styleGradientOpts` | Options for the `grapesjs-style-gradient` plugin | `{}` |
23 | | `propExtender` | Extend single style property definition of the `background` property. | `prop => prop` |
24 |
25 |
26 |
27 | ## Download
28 |
29 | * CDN
30 | * `https://unpkg.com/grapesjs-style-bg`
31 | * NPM
32 | * `npm i grapesjs-style-bg`
33 | * GIT
34 | * `git clone https://github.com/GrapesJS/style-bg.git`
35 |
36 |
37 |
38 | ## Usage
39 |
40 | Directly in the browser (remember to include the [Grapick](https://github.com/artf/grapick) CSS)
41 | ```html
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
59 | ```
60 |
61 | Modern javascript
62 | ```js
63 | import grapesjs from 'grapesjs';
64 | import plugin from 'grapesjs-style-bg';
65 | import 'grapesjs/dist/css/grapes.min.css';
66 | import 'grapick/dist/grapick.min.css';
67 |
68 | const editor = grapesjs.init({
69 | container : '#gjs',
70 | // ...
71 | plugins: [plugin],
72 | pluginsOpts: {
73 | [plugin]: { /* options */ }
74 | }
75 | // or
76 | plugins: [
77 | editor => plugin(editor, { /* options */ }),
78 | ],
79 | });
80 | ```
81 |
82 |
83 |
84 | ## Development
85 |
86 | Clone the repository
87 |
88 | ```sh
89 | $ git clone https://github.com/GrapesJS/style-bg.git
90 | $ cd grapesjs-style-bg
91 | ```
92 |
93 | Install dependencies
94 |
95 | ```sh
96 | $ npm i
97 | ```
98 |
99 | Start the dev server
100 |
101 | ```sh
102 | $ npm start
103 | ```
104 |
105 | Build the source
106 |
107 | ```sh
108 | $ npm run build
109 | ```
110 |
111 |
112 |
113 | ## License
114 |
115 | MIT
116 |
--------------------------------------------------------------------------------
/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Grapesjs Style Bg
6 |
7 |
8 |
9 |
10 |
17 |
18 |
19 |
20 |
21 |
22 |
23 | This is a demo content from _index.html. You can use this template file for
24 | development purpose. It won't be stored in your git repository
25 |
26 |
27 |
40 |
41 |
42 |
43 |
80 |
81 |
82 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "grapesjs-style-bg",
3 | "version": "2.0.2",
4 | "description": "Full-stack background style property type for GrapesJS, with the possibility to add images, colors, and gradients",
5 | "author": "Artur Arseniev",
6 | "main": "dist/index.js",
7 | "files": [
8 | "dist/"
9 | ],
10 | "repository": {
11 | "type": "git",
12 | "url": "https://github.com/GrapesJS/style-bg.git"
13 | },
14 | "scripts": {
15 | "start": "grapesjs-cli serve",
16 | "build": "grapesjs-cli build"
17 | },
18 | "keywords": [
19 | "grapesjs",
20 | "plugin"
21 | ],
22 | "devDependencies": {
23 | "grapesjs": "^0.21.2",
24 | "grapesjs-cli": "^4.1.1"
25 | },
26 | "license": "MIT",
27 | "dependencies": {
28 | "grapesjs-style-gradient": "^3.0.1"
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/index.ts:
--------------------------------------------------------------------------------
1 | import type { Plugin } from 'grapesjs';
2 | import styleGradient, { GRAD_DIRS, GRAD_TYPES, PluginOptions as StyleGradientOptions, getValidDir, parseGradient, toGradient } from 'grapesjs-style-gradient';
3 |
4 | export interface PluginOptions {
5 | /**
6 | * Options for the `grapesjs-style-gradient` plugin.
7 | * @default {}
8 | */
9 | styleGradientOpts?: StyleGradientOptions,
10 |
11 | /**
12 | * Extend single style property definition of the plugin.
13 | * You can, for example, change the default gradient color.
14 | */
15 | propExtender?: (prop: any) => any,
16 | };
17 |
18 | export enum BackgroundType {
19 | Image = 'image',
20 | Color = 'color',
21 | Grad = 'grad',
22 | };
23 |
24 | const getOptions = (items: string[]) => items.map(item => ({ id: item }));
25 |
26 | const capitalize = (str: string) => {
27 | return str && str.charAt(0).toUpperCase() + str.substring(1);
28 | };
29 |
30 | const getLayerFromBgImage = (imagePart: string) => {
31 | const result: Record = {
32 | [PROPERTY_BG_TYPE]: BackgroundType.Image,
33 | };
34 |
35 | if (imagePart.indexOf('url(') > -1) {
36 | // Background is Image
37 | result[PROPERTY_BG_IMAGE] = imagePart;
38 | } else if (imagePart.indexOf('gradient(') > -1) {
39 | const parsed = parseGradient(imagePart);
40 | const { stops } = parsed;
41 |
42 | if (
43 | stops.length === 2
44 | && parsed.type === 'linear'
45 | && (stops[0].color === stops[1].color)
46 | ) {
47 | // Background is Color
48 | result[PROPERTY_BG_TYPE] = BackgroundType.Color;
49 | result[PROPERTY_BG_COLOR] = stops[0].color;
50 | } else {
51 | // Background is Gradient
52 | const gradDir = getValidDir(parsed.direction) || GRAD_DIRS[0];
53 | const gradType = parsed.type || GRAD_TYPES[0];
54 | result[PROPERTY_BG_TYPE] = BackgroundType.Grad;
55 | result[PROPERTY_BG_GRAD] = toGradient(gradType, gradDir, parsed.colors);
56 | result[PROPERTY_BG_GRAD_TYPE] = gradType;
57 | result[PROPERTY_BG_GRAD_DIR] = gradDir;
58 | }
59 | }
60 | return result;
61 | };
62 |
63 | const bgTypeIconAttrs = 'style="max-height: 16px; display: block; margin: 0 auto" viewBox="0 0 24 24"';
64 | const PROPERTY_IMAGE = 'background-image';
65 | const PROPERTY_BG_TYPE = '__background-type';
66 | const PROPERTY_BG_IMAGE = PROPERTY_IMAGE;
67 | const PROPERTY_BG_COLOR = `${PROPERTY_BG_IMAGE}-color`;
68 | const PROPERTY_BG_GRAD = `${PROPERTY_BG_IMAGE}-gradient`;
69 | const PROPERTY_BG_GRAD_DIR = `${PROPERTY_BG_GRAD}-dir`;
70 | const PROPERTY_BG_GRAD_TYPE = `${PROPERTY_BG_GRAD}-type`;
71 |
72 |
73 | const DEFAULT_IMAGE = 'none';
74 |
75 | const plugin: Plugin = (editor, opts = {}) => {
76 | const options: PluginOptions = {
77 | styleGradientOpts: {},
78 | propExtender: p => p,
79 | ...opts,
80 | };
81 |
82 | styleGradient(editor, {
83 | colorPicker: 'default',
84 | ...options.styleGradientOpts,
85 | });
86 |
87 | const onBgTypeChange = ({ property, to }: any) => {
88 | const newTypeValue = to.value;
89 |
90 | // Hide style properties based on selected type
91 | if (newTypeValue) {
92 | property.getParent().getProperties().forEach((prop: any) => {
93 | const propName = prop.getName();
94 | let visible = false;
95 | // Background type is always visible
96 | if (propName === PROPERTY_BG_TYPE) return;
97 |
98 | if (
99 | (
100 | newTypeValue === BackgroundType.Image &&
101 | [PROPERTY_BG_COLOR, PROPERTY_BG_GRAD, PROPERTY_BG_GRAD_DIR, PROPERTY_BG_GRAD_TYPE].indexOf(propName) < 0
102 | )
103 | || (
104 | newTypeValue === BackgroundType.Color && propName === PROPERTY_BG_COLOR
105 | )
106 | || (
107 | newTypeValue === BackgroundType.Grad &&
108 | [PROPERTY_BG_GRAD, PROPERTY_BG_GRAD_DIR, PROPERTY_BG_GRAD_TYPE].indexOf(propName) >= 0
109 | )
110 | ) {
111 | visible = true;
112 | }
113 |
114 | prop.up({ visible });
115 | });
116 | }
117 | };
118 |
119 | editor.Styles.addBuiltIn('background', {
120 | type: 'stack',
121 | // @ts-ignore
122 | layerSeparator: /(? {
126 | const opt = property.getProperty(PROPERTY_BG_TYPE).getOption(values[PROPERTY_BG_TYPE]);
127 | return opt?.title ? `${capitalize(opt.title)}` : '';
128 | },
129 | fromStyle(style: Record, { property, name }: any) {
130 | const sep = property.getLayerSeparator();
131 | const props = property.getProperties();
132 | let layers: any = [];
133 |
134 | if (style[PROPERTY_IMAGE]) {
135 | // Get layers from the `background-image` property
136 | layers = property.__splitStyleName(style, PROPERTY_IMAGE, sep).map(getLayerFromBgImage);
137 |
138 | // Update layers by inner properties
139 | props.forEach((prop: any) => {
140 | const id = prop.getId();
141 | const propName = prop.getName();
142 | if (propName === PROPERTY_IMAGE) return;
143 | property.__splitStyleName(style, propName, sep)
144 | .map((value: string) => ({ [id]: value || prop.getDefaultValue() }))
145 | .forEach((inLayer: any, i: number) => {
146 | layers[i] = layers[i] ? { ...layers[i], ...inLayer } : inLayer;
147 | });
148 | });
149 | } else if (style[name]) {
150 | // Partial support for the `background` property
151 | layers = property.__splitStyleName(style, name, /(?![^)(]*\([^)(]*?\)\)),(?![^\(]*\))/)
152 | .map((value: string) => value.substring(0, value.lastIndexOf(')') + 1))
153 | .map(getLayerFromBgImage);
154 | }
155 |
156 | return layers;
157 | },
158 | toStyle(newValues: Record) {
159 | const values = { ...newValues };
160 | const type = values[PROPERTY_BG_TYPE];
161 | let image = values[PROPERTY_BG_IMAGE];
162 |
163 | if (type === BackgroundType.Color) {
164 | const bgColor = values[PROPERTY_BG_COLOR];
165 | image = bgColor === DEFAULT_IMAGE ? DEFAULT_IMAGE : `linear-gradient(${bgColor} 0%, ${bgColor} 100%)`;
166 | } else if (type === BackgroundType.Grad) {
167 | const parsed = parseGradient(values[PROPERTY_BG_GRAD] || '');
168 | image = toGradient(
169 | values[PROPERTY_BG_GRAD_TYPE] || GRAD_TYPES[0],
170 | values[PROPERTY_BG_GRAD_DIR] || GRAD_DIRS[0],
171 | parsed.colors
172 | );
173 | }
174 |
175 | delete values[PROPERTY_BG_IMAGE];
176 | delete values[PROPERTY_BG_COLOR];
177 | delete values[PROPERTY_BG_GRAD];
178 | delete values[PROPERTY_BG_GRAD_DIR];
179 | delete values[PROPERTY_BG_GRAD_TYPE];
180 |
181 | return {
182 | ...values,
183 | 'background-image': image || DEFAULT_IMAGE,
184 | };
185 | },
186 | properties: [
187 | {
188 | label: ' ',
189 | property: PROPERTY_BG_TYPE,
190 | type: 'radio',
191 | default: BackgroundType.Image,
192 | onChange: onBgTypeChange,
193 | options: [
194 | {
195 | id: BackgroundType.Image,
196 | title: 'Image',
197 | label: ` `,
198 | },
199 | {
200 | id: BackgroundType.Color,
201 | title: 'Color',
202 | label: ` `,
203 | },
204 | {
205 | id: BackgroundType.Grad,
206 | title: 'Gradient',
207 | label: ` `,
208 | },
209 | ],
210 | },
211 | {
212 | label: 'Image',
213 | property: PROPERTY_BG_IMAGE,
214 | default: 'none',
215 | functionName: 'url',
216 | type: 'file',
217 | full: true,
218 | },
219 | {
220 | property: 'background-repeat',
221 | default: 'repeat',
222 | type: 'select',
223 | options: [
224 | { id: 'repeat', label: 'Repeat' },
225 | { id: 'repeat-x', label: 'Repeat x' },
226 | { id: 'repeat-y', label: 'Repeat y' },
227 | { id: 'no-repeat', label: 'No repeat' },
228 | { id: 'space', label: 'Space' },
229 | { id: 'round', label: 'Round' },
230 | ]
231 | },
232 | {
233 | property: 'background-position',
234 | default: 'left top',
235 | type: 'select',
236 | options: getOptions([
237 | 'left top',
238 | 'left center',
239 | 'left bottom',
240 | 'right top',
241 | 'right center',
242 | 'right bottom',
243 | 'center top',
244 | 'center center',
245 | 'center bottom',
246 | ]),
247 | },
248 | {
249 | property: 'background-attachment',
250 | default: 'scroll',
251 | type: 'select',
252 | options: getOptions(['scroll', 'fixed', 'local']),
253 | },
254 | {
255 | type: 'select',
256 | default: 'auto',
257 | property: 'background-size',
258 | options: getOptions(['auto', 'cover', 'contain']),
259 | },
260 | {
261 | label: 'Color',
262 | property: PROPERTY_BG_COLOR,
263 | default: 'none',
264 | type: 'color',
265 | full: true,
266 | },
267 | {
268 | label: 'Gradient',
269 | property: PROPERTY_BG_GRAD,
270 | default: 'linear-gradient(right, black 0%, white 100%)',
271 | type: 'gradient',
272 | full: true,
273 | },
274 | {
275 | name: 'Direction',
276 | property: PROPERTY_BG_GRAD_DIR,
277 | type: 'select',
278 | default: 'right',
279 | options: getOptions(GRAD_DIRS),
280 | },
281 | {
282 | name: 'Type',
283 | property: PROPERTY_BG_GRAD_TYPE,
284 | default: 'linear',
285 | type: 'select',
286 | options: getOptions(GRAD_TYPES),
287 | }
288 | ].map(prop => options.propExtender?.(prop) || prop)
289 | });
290 | };
291 |
292 | export default plugin;
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "./node_modules/grapesjs-cli/dist/template/tsconfig.json",
3 | "include": ["src"]
4 | }
--------------------------------------------------------------------------------