drupal-image-style-generator 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,12 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <module type="WEB_MODULE" version="4">
3
+ <component name="NewModuleRootManager">
4
+ <content url="file://$MODULE_DIR$">
5
+ <excludeFolder url="file://$MODULE_DIR$/temp" />
6
+ <excludeFolder url="file://$MODULE_DIR$/.tmp" />
7
+ <excludeFolder url="file://$MODULE_DIR$/tmp" />
8
+ </content>
9
+ <orderEntry type="inheritedJdk" />
10
+ <orderEntry type="sourceFolder" forTests="false" />
11
+ </component>
12
+ </module>
@@ -0,0 +1,6 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="JavaScriptLibraryMappings">
4
+ <includedPredefinedLibrary name="Node.js Core" />
5
+ </component>
6
+ </project>
package/.idea/misc.xml ADDED
@@ -0,0 +1,6 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="IntellijSFCCDeploymentSettings">
4
+ <option name="json" value="{&#10; &quot;isFullCodeVersionCleanup&quot;: false,&#10; &quot;tasks&quot;: [],&#10; &quot;isWebDavActionAllowed&quot;: true&#10;}" />
5
+ </component>
6
+ </project>
@@ -0,0 +1,8 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="ProjectModuleManager">
4
+ <modules>
5
+ <module fileurl="file://$PROJECT_DIR$/.idea/drupal-image-style-generator.iml" filepath="$PROJECT_DIR$/.idea/drupal-image-style-generator.iml" />
6
+ </modules>
7
+ </component>
8
+ </project>
package/.idea/vcs.xml ADDED
@@ -0,0 +1,6 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="VcsDirectoryMappings">
4
+ <mapping directory="$PROJECT_DIR$" vcs="Git" />
5
+ </component>
6
+ </project>
package/Gruntfile.js ADDED
@@ -0,0 +1,96 @@
1
+ 'use strict';
2
+
3
+ const semver = require('semver');
4
+
5
+ module.exports = function(grunt) {
6
+
7
+ const pkg = grunt.file.readJSON('package.json');
8
+ const currentVersion = pkg.version;
9
+
10
+ // Project configuration.
11
+ grunt.initConfig({
12
+ pkg: pkg,
13
+
14
+ bump: {
15
+ options: {
16
+ files: ['package.json'],
17
+ commitFiles: ['-a'],
18
+ pushTo: 'origin',
19
+ globalReplace: true,
20
+ // regExp: /(['|"]?version['|"]?[ ]*:[ ]*['|"]?|^framework:[\S\s]*?assets:[\s]*version:[ ]*)(\d+\.\d+\.\d+(-false\.\d+)?(-\d+)?)[\d||A-a|.|-]*(['|"]?)/gmi
21
+ }
22
+ },
23
+ prompt: {
24
+ bump: {
25
+ options: {
26
+ questions: [
27
+ {
28
+ config: 'bump.options.setVersion',
29
+ type: 'list',
30
+ message: 'Bump version from ' + '<%= pkg.version %>' + ' to:',
31
+ choices: [
32
+ {
33
+ value: semver.inc(currentVersion, 'patch'),
34
+ name: 'Patch: ' + semver.inc(currentVersion, 'patch') + ' Backwards-compatible bug fixes.'
35
+ },
36
+ {
37
+ value: semver.inc(currentVersion, 'minor'),
38
+ name: 'Minor: ' + semver.inc(currentVersion, 'minor') + ' Add functionality in a backwards-compatible manner.'
39
+ },
40
+ {
41
+ value: semver.inc(currentVersion, 'major'),
42
+ name: 'Major: ' + semver.inc(currentVersion, 'major') + ' Incompatible API changes.'
43
+ },
44
+ {
45
+ value: 'custom',
46
+ name: 'Custom: ?.?.? Specify version...'
47
+ }
48
+ ]
49
+ },
50
+ {
51
+ config: 'bump.options.setVersion',
52
+ type: 'input',
53
+ message: 'What specific version would you like',
54
+ when: function (answers) {
55
+ return answers['bump.options.setVersion'] === 'custom';
56
+ },
57
+ validate: function (value) {
58
+ var valid = semver.valid(value);
59
+ return !!valid || 'Must be a valid semver, such as 1.2.3-rc1. See http://semver.org/ for more details.';
60
+ }
61
+ }
62
+ ]
63
+ }
64
+ }
65
+ },
66
+
67
+ shell: {
68
+ publish_npm: {
69
+ command: [
70
+ // 'npmrc public', // well, this is at the moment hardcoded to my personal public registry name
71
+ 'npm publish'
72
+ ].join('&&')
73
+ },
74
+ merge: {
75
+ command: [
76
+ 'git checkout develop',
77
+ 'git pull origin develop',
78
+ 'git merge master',
79
+ 'git push',
80
+ 'git checkout master' // back to master
81
+ ].join('&&')
82
+ }
83
+ }
84
+
85
+ });
86
+
87
+ // These plugins provide necessary tasks.
88
+ grunt.loadNpmTasks('grunt-prompt');
89
+ grunt.loadNpmTasks('grunt-bump');
90
+ grunt.loadNpmTasks('grunt-shell');
91
+
92
+ grunt.registerTask('build', 'Production Build', function() {
93
+ grunt.task.run('prompt', 'bump', 'shell:publish_npm', 'shell:merge');
94
+ });
95
+
96
+ };
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Andreas Schönefeldt
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,24 @@
1
+ # Drupal Image Style Generator
2
+ Drupal Image Style Generator
3
+
4
+ Allows to generate drupal image styles, based on the `theme.breakpoints.yml` in the theme.
5
+
6
+
7
+ configure the width and spect ratio of styles per breakpoint: .xs .sm .md .lg .xl
8
+
9
+ ```
10
+ imageStyles:
11
+ header_location:
12
+ label: 'Header Standort'
13
+ aspectRatio: 0.59
14
+ width: 545
15
+ ```
16
+
17
+
18
+ ```
19
+ col_8:
20
+ label: 'Col 8'
21
+ aspectRatio: 0.48
22
+ width: 545
23
+ ```
24
+
package/index.js ADDED
@@ -0,0 +1,249 @@
1
+ import log from "fancy-log";
2
+
3
+ const REQUIRED_OPTIONS = ['themePath', 'themeName', 'syncFolder']
4
+
5
+ /**
6
+ * @param {{themePath: string, themeName: string, syncFolder: string, gridSize?: number}} options
7
+ */
8
+ export default function (options) {
9
+
10
+ REQUIRED_OPTIONS.forEach((option) => {
11
+ if (!options[option]) {
12
+ throw new Error(`please configure the required option ${option}.`);
13
+ }
14
+ })
15
+
16
+ const themePath = options.themePath;
17
+ const themeName = options.themeName;
18
+ const syncFolder = options.syncFolder;
19
+ const IMAGE_STYLE_GRID_SIZE = options.gridSize || 0; // this means, every style will be rounded up to the next divisible number of this
20
+
21
+ const { v4 } = require("uuid");
22
+ const yaml = require('js-yaml');
23
+ const fs = require('fs');
24
+ const breakpointsFile = themePath + '/' + themeName + '.breakpoints.yml';
25
+ const imageStyles = {};
26
+ const usedStyleConfigs = {};
27
+
28
+ if (!fs.existsSync(breakpointsFile)) {
29
+ throw new Error(`Your configured theme has no ${breakpointsFile} theme breakpoints file. Please read the documentation and double check your options.`);
30
+ }
31
+
32
+ // read the breakpoints file
33
+ const bpConf = yaml.load(fs.readFileSync(breakpointsFile, 'utf8'));
34
+
35
+ Object.keys(bpConf).forEach((bpName) => {
36
+ const bp = bpConf[bpName];
37
+ let regex = /max-width:\s+(\d+)px/gmi;
38
+
39
+ let m = regex.exec(bp.mediaQuery);
40
+ let parsedWidth = m ? parseInt(m[1], 10) : null;
41
+
42
+ if (!parsedWidth) {
43
+ regex = /min-width:\s+(\d+)px/gmi;
44
+ m = regex.exec(bp.mediaQuery);
45
+ parsedWidth = m ? parseInt(m[1], 10) : null;
46
+ }
47
+
48
+ // update all available image styles
49
+ if (bp.imageStyles) {
50
+ Object.keys(bp.imageStyles).forEach((styleId) => {
51
+ if (!imageStyles[styleId]) {
52
+ imageStyles[styleId] = bp.imageStyles[styleId];
53
+ imageStyles[styleId].image_style_mappings = [];
54
+
55
+ imageStyles[styleId].widths = {};
56
+ }
57
+
58
+ // adjust the aspect ratio, if a new is set
59
+ if (bp.imageStyles[styleId].aspectRatio) {
60
+ imageStyles[styleId].aspectRatio = bp.imageStyles[styleId].aspectRatio;
61
+ }
62
+
63
+ let width = bp.imageStyles[styleId].width || parsedWidth;
64
+
65
+ // adjust the width to the grid, so we save a couple of image styles
66
+ width = Math.ceil(width / IMAGE_STYLE_GRID_SIZE) * IMAGE_STYLE_GRID_SIZE;
67
+
68
+ // set the new width
69
+ imageStyles[styleId].width = width;
70
+ imageStyles[styleId].widths[bpName] = imageStyles[styleId].width;
71
+ });
72
+ }
73
+
74
+ // loop over all the image styles
75
+ Object.keys(imageStyles).forEach((styleId) => {
76
+ bp.multipliers.forEach((multiplier) => {
77
+
78
+ const multiplyNum = parseFloat(multiplier);
79
+ const styleWidth = (imageStyles[styleId].widths[bpName] || parsedWidth) * multiplyNum;
80
+ const aspectRatio = imageStyles[styleId].aspectRatio;
81
+
82
+ const uniqueId = v4();
83
+
84
+ let styleHeight;
85
+ let styleLabel;
86
+ let concreteStyleId;
87
+ let styleFileName;
88
+ let styleFilePath;
89
+
90
+ if (aspectRatio) {
91
+ styleHeight = imageStyles[styleId].height ? imageStyles[styleId].height * multiplyNum : Math.round(styleWidth * aspectRatio);
92
+
93
+ // generate the filename
94
+ styleLabel = `Scale and Crop ${styleWidth} x ${styleHeight}`;
95
+ concreteStyleId = `sc_${styleWidth}x${styleHeight}`;
96
+ styleFileName = `image.style.${concreteStyleId}.yml`;
97
+ styleFilePath = `${syncFolder}/${styleFileName}`;
98
+
99
+ usedStyleConfigs[styleFileName] = true;
100
+
101
+ const styleYml = fs.existsSync(styleFilePath) ?
102
+ yaml.load(fs.readFileSync(styleFilePath, 'utf8')) :
103
+ {
104
+ uuid: uniqueId,
105
+ langcode: 'de',
106
+ status: true,
107
+ dependencies: {
108
+ module: ['focal_point'] // @todo - parse the module config and check, if focal point is enabled
109
+ },
110
+ name: concreteStyleId,
111
+ label: styleLabel,
112
+ effects: {}
113
+ }
114
+ ;
115
+
116
+ const hasChanges = Object.values(styleYml.effects).length === 0 || Object.values(styleYml.effects).some((effectConf) => {
117
+ return (effectConf.data.width !== styleWidth || effectConf.data.height !== styleHeight); // the width has changed
118
+ });
119
+
120
+ if (hasChanges) {
121
+ const effectId = v4();
122
+
123
+ styleYml.effects = {};
124
+ styleYml.effects[effectId] = {
125
+ uuid: effectId,
126
+ id: 'focal_point_scale_and_crop',
127
+ weight: 1,
128
+ data: {
129
+ width: styleWidth,
130
+ height: imageStyles[styleId].height ? imageStyles[styleId].height * multiplyNum : Math.round(styleWidth * imageStyles[styleId].aspectRatio),
131
+ crop_type: 'focal_point'
132
+ }
133
+ };
134
+
135
+ // write the file
136
+ fs.writeFileSync(styleFilePath, yaml.dump(styleYml));
137
+ log('Created ' + styleFilePath);
138
+ } else {
139
+ log('skipping ' + styleFileName + ' - it already exists and there are no changes.');
140
+ }
141
+
142
+ } else {
143
+
144
+ // generate the filename
145
+ styleLabel = `Scale ${styleWidth}`;
146
+ concreteStyleId = `s_${styleWidth}`;
147
+ styleFileName = `image.style.${concreteStyleId}.yml`;
148
+ styleFilePath = `${syncFolder}/${styleFileName}`;
149
+
150
+ usedStyleConfigs[styleFileName] = true;
151
+
152
+ const styleYml = fs.existsSync(styleFilePath) ?
153
+ yaml.load(fs.readFileSync(styleFilePath, 'utf8')) :
154
+ {
155
+ uuid: uniqueId,
156
+ langcode: 'de',
157
+ status: true,
158
+ dependencies: {},
159
+ name: concreteStyleId,
160
+ label: styleLabel,
161
+ effects: {}
162
+ }
163
+ ;
164
+
165
+ const hasChanges = Object.values(styleYml.effects).length === 0 || Object.values(styleYml.effects).some((effectConf) => {
166
+ return effectConf.data.width !== styleWidth; // the width has changed
167
+ });
168
+
169
+ if (hasChanges) {
170
+ const effectId = v4();
171
+
172
+ styleYml.effects = {};
173
+ styleYml.effects[effectId] = {
174
+ uuid: effectId,
175
+ id: 'image_scale',
176
+ weight: 1,
177
+ data: {
178
+ width: styleWidth,
179
+ height: null,
180
+ upscale: false
181
+ }
182
+ };
183
+
184
+ // write the file
185
+ fs.writeFileSync(styleFilePath, yaml.dump(styleYml));
186
+ log('Created ' + styleFilePath);
187
+ } else {
188
+ log('skipping ' + styleFileName + ' - it already exists and there are no changes.');
189
+ }
190
+
191
+ }
192
+
193
+ imageStyles[styleId].image_style_mappings.push({
194
+ breakpoint_id: bpName,
195
+ multiplier: multiplier,
196
+ image_mapping_type: 'image_style',
197
+ image_mapping: concreteStyleId
198
+ });
199
+
200
+ });
201
+ });
202
+ });
203
+
204
+ // write the actual responsive config files
205
+ Object.keys(imageStyles).forEach((styleId) => {
206
+ const responsiveImagePath = `${syncFolder}/responsive_image.styles.${styleId}.yml`;
207
+ const uniqueId = v4();
208
+ const responsiveConfig = fs.existsSync(responsiveImagePath) ?
209
+ yaml.load(fs.readFileSync(responsiveImagePath, 'utf8')) :
210
+ {
211
+ uuid: uniqueId,
212
+ langcode: 'de',
213
+ status: true,
214
+ dependencies: {
215
+ config: [],
216
+ theme: [themeName]
217
+ },
218
+ id: styleId,
219
+ label: imageStyles[styleId].label,
220
+ image_style_mappings: [],
221
+ breakpoint_group: themeName
222
+ }
223
+ ;
224
+
225
+ const mappings = imageStyles[styleId].image_style_mappings;
226
+
227
+ responsiveConfig.dependencies.config = mappings.map((mapping) => {
228
+ return 'image.style.' + mapping.image_mapping;
229
+ });
230
+
231
+ responsiveConfig.image_style_mappings = mappings;
232
+ responsiveConfig.fallback_image_style = mappings[0].image_mapping;
233
+
234
+ fs.writeFileSync(responsiveImagePath, yaml.dump(responsiveConfig));
235
+ log('Created ' + responsiveImagePath);
236
+ });
237
+
238
+ // cleanup the unused files
239
+ const configFiles = fs.readdirSync(syncFolder);
240
+
241
+ configFiles.forEach(file => {
242
+ if ((file.indexOf('image.style.sc_') === 0 || file.indexOf('image.style.s_') === 0) && !usedStyleConfigs[file]) {
243
+ fs.rmSync(`${syncFolder}/${file}`);
244
+ console.log('%o is unused and was removed.', file);
245
+ }
246
+ });
247
+
248
+ log('Generated %d image styles for %d responsive sizes', Object.keys(usedStyleConfigs).length, Object.keys(imageStyles).length);
249
+ }
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "drupal-image-style-generator",
3
+ "version": "0.1.0",
4
+ "description": "A helper tool to automatically geenrate drupal 8+ responsive image styles",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "test": "echo \"Error: no test specified\" && exit 1"
8
+ },
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/Andreas-Schoenefeldt/drupal-image-style-generator.git"
12
+ },
13
+ "keywords": [
14
+ "drupal"
15
+ ],
16
+ "author": "Andreas Schönefeldt",
17
+ "license": "MIT",
18
+ "bugs": {
19
+ "url": "https://github.com/Andreas-Schoenefeldt/drupal-image-style-generator/issues"
20
+ },
21
+ "homepage": "https://github.com/Andreas-Schoenefeldt/drupal-image-style-generator#readme",
22
+ "devDependencies": {
23
+ "grunt": "^1.6.1",
24
+ "grunt-bump": "^0.8.0",
25
+ "grunt-prompt": "^1.3.3",
26
+ "grunt-shell": "^4.0.0",
27
+ "semver": "^7.3.8"
28
+ },
29
+ "dependencies": {
30
+ "fancy-log": "^2.0.0",
31
+ "js-yaml": "^4.1.0",
32
+ "uuid": "^9.0.0"
33
+ }
34
+ }