-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnode_css.module
365 lines (324 loc) · 11.9 KB
/
node_css.module
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
<?php
/**
* Implements hook_menu().
*/
function node_css_menu() {
$items = [];
// Define the settings page.
$items['admin/config/content/node_css'] = [
'title' => 'Node CSS Settings',
'description' => 'Settings for custom CSS on nodes.',
'page callback' => 'backdrop_get_form',
'page arguments' => ['node_css_settings'],
'file' => 'node_css.admin.inc',
'access arguments' => ['administer site configuration'],
];
return $items;
}
/**
* Implements hook_form_FORM_ID_alter() to add a CSS field to node forms
* with CodeMirror CSS editor support and a "Copy code" feature.
*/
function node_css_form_node_form_alter(&$form, &$form_state) {
// Load existing configuration.
$config = config('node_css.settings');
$enabled_content_types = $config->get('enabled_content_types');
$content_type = $form['#node']->type;
// If specific content types are selected, apply Node CSS only to those types.
if (!empty($enabled_content_types) && !in_array($content_type, $enabled_content_types)) {
return;
}
// Determine the default CSS value for this node.
$default_value = $config->get('node-' . $form['#node']->nid)
?? $config->get('default_css_' . $content_type)
?? $config->get('default');
// Get the configured height for the textarea, defaulting to 10 rows.
$textarea_height = $config->get('css_textarea_height') ?: 10;
// Get the configured position for the CSS editor.
$position = $config->get('css_text_position') ?: 'bottom'; // Default to bottom if not set.
// Define the "Copy code" link and editor wrapper.
$copy_link = [
'#type' => 'markup',
'#markup' => '<a href="#" id="copy-css-code" class="copy-code-link">Copy code</a>',
];
// Structure the form based on the chosen position.
if ($position === 'top') {
// Place the editor at the top.
$form['css_text_wrapper'] = [
'#type' => 'container',
'#weight' => -100,
'#attributes' => ['class' => ['codemirror-editor-wrapper']],
];
} elseif ($position === 'vertical_tab') {
// Place the editor in a vertical tab.
$form['css_text_fieldset'] = [
'#type' => 'fieldset',
'#title' => t('Node CSS'),
'#group' => 'additional_settings',
'#description' => t('Add custom CSS for this node. This CSS will apply only to this specific node.'),
];
$form['css_text_fieldset']['css_text_wrapper'] = [
'#type' => 'container',
'#attributes' => ['class' => ['codemirror-editor-wrapper']],
];
} else {
// Default to placing the editor at the bottom.
$form['css_text_wrapper'] = [
'#type' => 'container',
'#weight' => 0,
'#attributes' => ['class' => ['codemirror-editor-wrapper']],
];
}
// Add the "Copy code" link and the `CodeMirror` editor to the appropriate wrapper.
if ($position === 'vertical_tab') {
$form['css_text_fieldset']['css_text_wrapper']['copy_link'] = $copy_link;
$form['css_text_fieldset']['css_text_wrapper']['css_text'] = [
'#type' => 'textarea',
'#title' => t('Node CSS'),
'#rows' => $textarea_height,
'#default_value' => $default_value,
'#attributes' => [
'id' => 'css-text-editor',
'class' => ['codemirror-css-editor']
],
];
} else {
$form['css_text_wrapper']['copy_link'] = $copy_link;
$form['css_text_wrapper']['css_text'] = [
'#type' => 'textarea',
'#title' => t('Node CSS'),
'#rows' => $textarea_height,
'#default_value' => $default_value,
'#attributes' => [
'id' => 'css-text-editor',
'class' => ['codemirror-css-editor']
],
];
}
// Attach CodeMirror using the helper function.
node_css_attach_codemirror($form);
// Add custom CSS to style the "Copy code" link within the CodeMirror container.
$form['#attached']['css'][] = [
'type' => 'inline',
'data' => '
.codemirror-editor-wrapper {
position: relative;
display: inline-block;
width: 100%;
}
.copy-code-link {
position: absolute;
top: 60px;
right: 8px;
z-index: 10;
background: #f8f9fa;
padding: 2px 6px;
font-size: 12px;
border-radius: 4px;
text-decoration: none;
color: #007bff;
transition: background 0.2s;
}
.copy-code-link:hover {
background: #e2e6ea;
}
',
];
// Attach JavaScript for the "Copy code" feature.
$form['#attached']['js'][] = [
'type' => 'inline',
'data' => "
document.addEventListener('DOMContentLoaded', function() {
var copyButton = document.getElementById('copy-css-code');
copyButton.addEventListener('click', function(e) {
e.preventDefault();
var editorElement = document.getElementById('css-text-editor');
var editorInstance = window.codeMirrorEditors[editorElement.id];
if (editorInstance) {
var cssCode = editorInstance.getValue();
navigator.clipboard.writeText(cssCode).then(function() {
alert('CSS code copied to clipboard!');
}).catch(function(err) {
alert('Failed to copy CSS code: ' + err);
});
} else {
alert('CodeMirror instance not found.');
}
});
});
",
];
}
/**
* Implement hook_node_insert().
*/
function node_css_node_insert(Node $node) {
config_set('node_css.settings', 'node-' . $node->nid, $node->css_text);
}
/**
* Implement hook_node_update().
*/
function node_css_node_update(Node $node) {
config_set('node_css.settings', 'node-' . $node->nid, $node->css_text);
}
/**
* Implements hook_node_view() to add custom CSS to the node if enabled for its content type.
*/
function node_css_node_view($node, $view_mode) {
$config = config('node_css.settings');
$enabled_content_types = $config->get('enabled_content_types');
// If specific content types are selected, apply only to those types.
if (!empty($enabled_content_types) && !in_array($node->type, $enabled_content_types)) {
return;
}
// Check for node-specific CSS.
if ($node_css = $config->get('node-' . $node->nid)) {
$custom_css = '<style media="all">' . $node_css . '</style>' . PHP_EOL;
backdrop_add_html_head([
'#type' => 'markup',
'#markup' => $custom_css,
'#weight' => 100,
], 'node_css_' . $node->nid);
}
}
/**
* Helper function to attach CodeMirror to a form.
*/
function node_css_attach_codemirror(&$form, $textarea_selector = '.codemirror-css-editor') {
// Load existing configuration.
$config = config('node_css.settings');
$selected_theme = $config->get('codemirror_theme') ?: 'default';
$textarea_height = $config->get('css_textarea_height') ?: 10; // Default to 10 rows if not set.
// Calculate the height in pixels based on an estimated row height.
$height_in_pixels = $textarea_height * 20;
// Attach the CodeMirror library and chosen theme from CDN.
$form['#attached']['js'][] = [
'type' => 'file',
'data' => backdrop_get_path('module', 'node_css') . '/codemirror/js/codemirror.min.js',
];
$form['#attached']['js'][] = [
'type' => 'file',
'data' => backdrop_get_path('module', 'node_css') . '/codemirror/js/css.min.js',
];
$form['#attached']['css'][] = [
'type' => 'file',
'data' => backdrop_get_path('module', 'node_css') . '/codemirror/css/codemirror.min.css',
];
// CSS property value autocompletion.
$form['#attached']['js'][] = [
'type' => 'file',
'data' => backdrop_get_path('module', 'node_css') . '/codemirror/js/show-hint.min.js',
];
$form['#attached']['js'][] = [
'type' => 'file',
'data' => backdrop_get_path('module', 'node_css') . '/codemirror/js/css-hint.min.js',
];
$form['#attached']['css'][] = [
'type' => 'file',
'data' => backdrop_get_path('module', 'node_css') . '/codemirror/css/show-hint.min.css',
];
$form['#attached']['css'][] = [
'type' => 'inline',
'data' => '
.CodeMirror {
font-size: 12px;
line-height: 1.4;
height: ' . $height_in_pixels . 'px;
resize: both;
border: 1px #bbb solid;
}
.CodeMirror::after {
content: \'\';
position: absolute;
left: 80ch;
top: 0;
bottom: 0;
border-left: 1px dashed #ccc;
pointer-events: none;
}
',
];
// Add theme-specific CSS file based on the selected theme.
if ($selected_theme !== 'default') {
$form['#attached']['css'][] = [
'type' => 'external',
'data' => "https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.5/theme/{$selected_theme}.min.css",
];
}
$base_url = url('', ['absolute' => TRUE]);
$css_suggestions_url = $base_url . backdrop_get_path('module', 'node_css') . '/codemirror/css-suggestions.json';
// Custom inline JavaScript to initialize CodeMirror and store each instance in a global array.
$form['#attached']['js'][] = [
'type' => 'inline',
'data' => "document.addEventListener('DOMContentLoaded', function() {
var cssSuggestions = {};
window.codeMirrorEditors = {}; // Global object to hold each CodeMirror instance
// Fetch CSS suggestions from the local JSON file
fetch('{$css_suggestions_url}')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
cssSuggestions = data;
})
.catch(error => console.error('Error fetching CSS suggestions:', error));
var editors = document.querySelectorAll('{$textarea_selector}');
editors.forEach(function(textarea) {
var wrapper = textarea.closest('.codemirror-editor-wrapper');
if (!textarea.id) {
textarea.id = 'css-editor-' + Math.random().toString(36).substr(2, 9);
}
var editorInstance = CodeMirror.fromTextArea(textarea, {
mode: 'css',
lineNumbers: true,
lineWrapping: true,
theme: '{$selected_theme}',
extraKeys: {
'Space': function(cm) {
cm.replaceSelection(' ');
var hintOptions = customCssHint(cm);
if (hintOptions.list && hintOptions.list.length > 0) {
CodeMirror.showHint(cm, function(cmInstance) {
return hintOptions;
}, { completeSingle: false });
}
}
},
hintOptions: {
hint: customCssHint,
completeSingle: false
}
});
window.codeMirrorEditors[textarea.id] = editorInstance;
});
function customCssHint(editor) {
var cur = editor.getCursor();
var token = editor.getTokenAt(cur);
var line = editor.getLine(cur.line);
var property = line.slice(0, line.indexOf(':')).trim().toLowerCase();
var list = cssSuggestions[property] || [];
var start = token.start;
var end = token.end;
if (line.includes(':')) {
start = line.indexOf(':') + 1;
if (line.includes(';')) {
end = line.indexOf(';');
}
}
return {
list: list.map(function(item) {
return {
text: ' ' + item + ';\\n ',
displayText: item,
};
}),
from: CodeMirror.Pos(cur.line, start),
to: CodeMirror.Pos(cur.line, end)
};
}
});"
];
}