-
-
Notifications
You must be signed in to change notification settings - Fork 159
/
Copy pathmain.js
359 lines (334 loc) · 12.9 KB
/
main.js
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
/*
* Typist
* Author: Giovanni De Andre aka Gio
* https://github.com/gioalo
* License: MIT
*
*/
const {Artboard, Color, Text, Rectangle } = require("scenegraph");
const {alert,error,warning} = require("./lib/dialogs.js");
const h = require("./lib/h.js");
const Typist = require("./lib/typist.js");
const typist = new Typist();
let selectedArtboard = null;
/**
* Creates Artboard and make selection
* @param {*} selection
* @param {*} root
*/
async function createNewArtboard(selection, root) {
let len = root.children.length;
let last = len === 0 ? len : len - 1;
let nodes = [];
let newArtboard = new Artboard();
newArtboard.name = "Typist";
newArtboard.width = 1920;
newArtboard.height = 1080;
newArtboard.fill = new Color("white");
if(root.children.length > 0) {
root.children.forEach((node, index) => {
nodes.push(node);
});
const lastNode = {
x: nodes[last].globalBounds.x,
y: nodes[last].globalBounds.y,
h: nodes[last].height,
w: nodes[last].width,
spacing: 100,
getNode(){
return nodes[last];
},
getYpos(){
return this.y + (this.h + this.spacing);
}
};
newArtboard.moveInParentCoordinates(lastNode.x, lastNode.getYpos());
await root.addChildAfter(newArtboard, lastNode.getNode());
} else {
newArtboard.moveInParentCoordinates(0,0);
await root.addChild(newArtboard);
}
selection.items = [newArtboard];
}
/**
* Create plugin
* @param {*} selection
*/
async function initPlugin(selection, root){
selectedArtboard = selection;
if(selectedArtboard.hasArtboards && selectedArtboard.items.length === 1 && selectedArtboard.items[0].children.length === 0 && selectedArtboard.items[0].width === 1920 && selectedArtboard.items[0].height === 1080) {
try {
// Form
const $dialog = document.querySelector("#typistDialog");
const $form = document.querySelector("#typistDialog #form");
const $submitBtn = document.querySelector("#typistDialog #submitBtn");
const $closeBtn = document.querySelector("#typistDialog #closeBtn");
const $customRatioInput = document.querySelector("#typistDialog #customRatio");
// Inputs
const $ratio = document.querySelector("#typistDialog select[name=ratio]");
const $newRatio = document.querySelector("#typistDialog input[name=custom_ratio]");
const $base = document.querySelector("#typistDialog input[name=base]");
const $notes = document.querySelector("#typistDialog input[name=notes]");
// error
const $notesError = document.querySelector("#typistDialog #notesError");
const $baseError = document.querySelector("#typistDialog #baseError");
const $customRatioError = document.querySelector("#typistDialog #customRatioError");
const $formError = document.querySelector("#typistDialog #formError");
$form.addEventListener("submit",(evt)=>{
evt.preventDefault();
resetFormInputs();
evt.target.reset();
});
// Resets form
function resetFormInputs() {
if($ratio.value === "") {
$customRatioInput.style.visibility = "visible";
} else {
$customRatioInput.style.visibility = "hidden";
}
if($formError.style.visibility === "visible") {
$formError.style.visibility = "hidden";
}
}
function deletesArtboardIfCancel() {
selectedArtboard.items[0].removeFromParent();
}
$base.addEventListener("keyup",(evt)=>{
evt.preventDefault();
showInputError(
typist.validateFontSize(Math.max(evt.target.value)),
$baseError,
$submitBtn
);
});
$notes.addEventListener("keyup",(evt)=>{
evt.preventDefault();
showInputError(
typist.validateNumberOfNotes(Math.max(evt.target.value)),
$notesError,
$submitBtn
);
});
$newRatio.addEventListener("keyup",(evt)=>{
evt.preventDefault();
showInputError(
typist.validateRatio(Math.max(evt.target.value)),
$customRatioError,
$submitBtn
);
});
$closeBtn.addEventListener("click", ()=>{
deletesArtboardIfCancel();
resetFormInputs();
$dialog.close();
});
$ratio.addEventListener("change", (evt)=>{
if(evt.target.value !== "") {
$customRatioInput.style.visibility = "hidden";
} else {
$customRatioInput.style.visibility = "visible";
}
});
// form submit
$submitBtn.addEventListener("click", (evt)=>{
evt.preventDefault();
const inputValues = {
ratio: ($ratio.value !== "" ? Math.max($ratio.value) : Math.max($newRatio.value)),
fontSize: Math.max($base.value),
notes: Math.max($notes.value)
}
$dialog.close(inputValues);
resetFormInputs();
});
await $dialog.showModal().then((resolve) => {
if(resolve != "" && resolve != "reasonCanceled") {
typist.typographyScale(resolve.ratio, resolve.notes, resolve.fontSize).then((res) =>{
// console.log(res);
typistSpec(selectedArtboard, res.reverse());
}).catch(res => {
deletesArtboardIfCancel();
console.log("[USER] Invalid values make sure is a positive number.");
return res;
});
}
});
} catch (error) {
typist.alertUserIfItBroken();
deletesArtboardIfCancel();
console.error("[DEVELOPER] Oops something is broken.", error);
}
} else {
alertUserToSelectArtboard();
}
}
/**
* Returns error for invalid values
* @param {string} id
* @param {number} value
*/
async function valueError(id,value) {
if(typist.checkNumberValidity(value)) {
id.style.visibility = "hidden";
} else {
id.style.visibility = "visible";
}
}
/**
* Return error
* @param {boolean} valid
* @param {HTMLElement} id target element id
*/
async function showInputError(valid, id, btnId){
const formError = document.querySelector("#typistDialog #formError");
if (valid) {
id.style.visibility = "hidden";
btnId.removeAttribute("disabled");
formError.style.visibility = "hidden";
} else {
id.style.visibility = "visible";
btnId.setAttribute("disabled","disabled");
formError.style.visibility = "visible";
}
}
/**
* Draw Header headline
* @param {*} selection
* @param {*} config
*/
async function heading(selection, config) {
// headline text
const headlineNode = new Text();
headlineNode.text = "Typography Spec";
headlineNode.styleRanges = [{
length: headlineNode.text.length,
fontSize: 72,
fill: new Color(config.colorBlack),
fontStyle: "Bold"
}];
headlineNode.moveInParentCoordinates(config.xpos, config.ypos);
selection.insertionParent.addChild(headlineNode);
}
/**
* Draw Header typist settings
* @param {*} selection
* @param {*} config
*/
async function settings(selection, config) {
// settings text
const settingsNode = new Text();
settingsNode.text = `Settings: Body Font Size = ${config.base}px, Baseline Ratio = ${config.ratio}, Optimal Line Length Width = ${config.width}px (Approx. 75 C.P.L)`;
settingsNode.styleRanges =[{
length: settingsNode.text.length,
fontSize: 24,
fill: new Color(config.colorBlack)
}];
settingsNode.moveInParentCoordinates(config.xpos, config.ypos + 72);
selection.insertionParent.addChild(settingsNode);
}
/**
* Draw Rectangle for header
* @param {*} selection
*/
async function header(selection) {
let rectangle = new Rectangle();
rectangle.width = selection.items[0].width;
rectangle.height = 230;
rectangle.fill = new Color("#F5F5F5");
selection.insertionParent.addChild(rectangle);
rectangle.moveInParentCoordinates(0, 0);
}
/**
* Draws typist artwork
* @param {*} selectedArtboard current selection
* @param {object[]} data typography settings
*/
async function typistSpec(selectedArtboard, data) {
let baseline = data[data.length - 2];
if(selectedArtboard.items.length > 0 && data.length > 0) {
// setup type settings
const config = {
id: baseline.leading,
base:baseline.px,
ratio:baseline.leading,
width:baseline.maxwidth,
colorBlack: "#212121",
colorWhite: "#FFFFFF",
ypos:100,
xpos:100
};
// Rename/tag selected artboard
selectedArtboard.items[0].name = `Typography Spec-${config.id}`;
// Header
header(selectedArtboard);
heading(selectedArtboard, config);
settings(selectedArtboard, config);
// Type scales nodes
data.forEach((item, i) => {
const node = new Text();
node.text = `The quick brown fox jumps over the lazy dog (${item.em}em).`;
node.styleRanges = [{
length: node.text.length,
fontSize: item.px,
fill: new Color(config.colorBlack)
}];
node.moveInParentCoordinates(config.xpos, (config.ypos * 2.5) + (100 * (i + 1)));
selectedArtboard.insertionParent.addChild(node);
});
}
}
/**
* Alert user to select artboard
*/
async function alertUserToSelectArtboard() {
console.log("[USER] Alert! No Artboard selection, Not an empty Artboard or Too many selections. Select at least one Artboard.");
await alert("⚠️ Required Artboard.","* Make sure you have selected at least one Empty Artboard. Required Artboard size Web 1920 (1920x1080).","* Can't select multiple Artboards.","* Please close and try again!");
}
// Create form dialog
let typistFormDialog = h("dialog", {id:"typistDialog"},
h("form", { style: { width: 600 }, method:"dialog", id:"form"},
h("h1", "Typist"),
h("hr"),
h("p", "Please fill out form to generate modular typography."),
h("div",
{style:{ display:"flex", flexDirection: "row", justifyContent:"space-between"
}},
h("label",
h("span", "Baseline font size (Body)"),
h("input", {type: "number", name:"base", placeholder:"14-24", style:{width: 100}}),
h("span",{id:"baseError",style:{color:"red",fontSize:"12px", visibility:"hidden"}},"⚠️Invalid number.")
),
h("label",
h("span", "Number of headings"),
h("input", {type: "number", name:"notes", placeholder:"2-4", style:{width: 100}}),
h("span",{id:"notesError",style:{color:"red",fontSize:"12px", visibility:"hidden"}},"⚠️Invalid number.")
)
),
h("div",{style:{ display:"flex", flexDirection: "row",justifyContent:"space-between"}},
h("label",
h("span", "Select a Ratio"),
h("select", { style: { width: 250 }, name:"ratio", autofocus:'autofocus'},
...typist.getRatios().map(([name, value]) =>
h("option", {value: value, style:{ textTransform:"capitalize" }}, `${name} - ${value}`))
)
),
h("label",{id:"customRatio",style:{visibility:"hidden",width: 100}},
h("span", "Enter Ratio"),
h("input", {type: "number", name:"custom_ratio", placeholder:"1.125-4", style:{width: 100}}),
h("span",{id:"customRatioError",style:{color:"red",fontSize:"12px", visibility:"hidden"}},"⚠️Invalid number.")
)
),
h("footer",{style:{display:"flex", flexDirection:"row", alignItems:"center"}},
h("span",{id:"formError", style:{visibility:"hidden", fontSize:"14px", fontWeight:"bold", color:"red"}},"Sorry! You must fill out all fields."),
h("button", {uxpVariant: "primary", id:"closeBtn"}, "Cancel"),
h("button", {uxpVariant: "cta", id:"submitBtn"}, "Submit")
)
)
);
// Append form dialog
document.body.appendChild(typistFormDialog);
/**
* Initialize plugin commands
*/
module.exports = {
commands: {initPlugin}
};