-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathWidget Sizes.js
356 lines (325 loc) · 10 KB
/
Widget Sizes.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
// Variables used by Scriptable.
// These must be at the very top of the file. Do not edit.
// icon-color: blue; icon-glyph: object-group;
/**
* @version 1.0.1
* @author Honye
*/
/**
* @file Scriptable WebView JSBridge native SDK
* @version 1.0.3
* @author Honye
*/
/**
* @typedef Options
* @property {Record<string, () => void>} methods
*/
const sendResult = (() => {
let sending = false;
/** @type {{ code: string; data: any }[]} */
const list = [];
/**
* @param {WebView} webView
* @param {string} code
* @param {any} data
*/
return async (webView, code, data) => {
if (sending) return
sending = true;
list.push({ code, data });
const arr = list.splice(0, list.length);
for (const { code, data } of arr) {
const eventName = `ScriptableBridge_${code}_Result`;
const res = data instanceof Error ? { err: data.message } : data;
await webView.evaluateJavaScript(
`window.dispatchEvent(
new CustomEvent(
'${eventName}',
{ detail: ${JSON.stringify(res)} }
)
)`
);
}
if (list.length) {
const { code, data } = list.shift();
sendResult(webView, code, data);
} else {
sending = false;
}
}
})();
/**
* @param {WebView} webView
* @param {Options} options
*/
const inject = async (webView, options) => {
const js =
`(() => {
const queue = window.__scriptable_bridge_queue
if (queue && queue.length) {
completion(queue)
}
window.__scriptable_bridge_queue = null
if (!window.ScriptableBridge) {
window.ScriptableBridge = {
invoke(name, data, callback) {
const detail = { code: name, data }
const eventName = \`ScriptableBridge_\${name}_Result\`
const controller = new AbortController()
window.addEventListener(
eventName,
(e) => {
callback && callback(e.detail)
controller.abort()
},
{ signal: controller.signal }
)
if (window.__scriptable_bridge_queue) {
window.__scriptable_bridge_queue.push(detail)
completion()
} else {
completion(detail)
window.__scriptable_bridge_queue = []
}
}
}
window.dispatchEvent(
new CustomEvent('ScriptableBridgeReady')
)
}
})()`;
const res = await webView.evaluateJavaScript(js, true);
if (!res) return inject(webView, options)
const methods = options.methods || {};
const events = Array.isArray(res) ? res : [res];
// 同时执行多次 webView.evaluateJavaScript Scriptable 存在问题
// 可能是因为 JavaScript 是单线程导致的
const sendTasks = events.map(({ code, data }) => {
return (() => {
try {
return Promise.resolve(methods[code](data))
} catch (e) {
return Promise.reject(e)
}
})()
.then((res) => sendResult(webView, code, res))
.catch((e) => {
console.error(e);
sendResult(webView, code, e instanceof Error ? e : new Error(e));
})
});
await Promise.all(sendTasks);
inject(webView, options);
};
/**
* @param {WebView} webView
* @param {object} args
* @param {string} args.html
* @param {string} [args.baseURL]
* @param {Options} options
*/
const loadHTML = async (webView, args, options = {}) => {
const { html, baseURL } = args;
await webView.loadHTML(html, baseURL);
inject(webView, options).catch((err) => console.error(err));
};
if (config.runsInWidget) {
const widget = new ListWidget();
widget.backgroundColor = new Color('#fff');
Script.setWidget(widget);
Script.complete();
}
const style =
`.flex {
display: flex;
}
body {
font-size: 14px;
color: #232323;
}
ol {
padding-inline-start: 2em;
line-height: 1.6;
}
li + li {
margin-top: 1em;
}
.mockup img,
.mockup svg {
width: 120px;
height: auto;
}
@media (prefers-color-scheme: dark) {
:root {
--divider-color: rgba(84,84,88,0.65);
--card-background: #1c1c1e;
--list-header-color: rgba(235,235,245,0.6);
}
body {
background: #000;
color: #fff;
}
}`;
const html =
`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>小组件尺寸计算</title>
<style>${style}</style>
</head>
<body>
<main>
<div class="flex">
<div class="mockup">
<img src="https://scriptore.imarkr.com/imgs/screen.png" />
</div>
<div>
<ol>
<li>桌面壁纸使用不含白色的背景,可以是纯色背景</li>
<li>长按桌面添加一屏</li>
<li>按顺序添加此组件的中号组件和大号组件</li>
<li>截图刚刚新建的一屏后选择截图</li>
</ol>
</div>
</div>
<input type="file" accept="image/*" placeholder="选择屏幕截图" />
<div><samp style="color:red"></samp></div>
<pre></pre>
</main>
<script module>
const input = document.querySelector("input");
const pre = document.querySelector('pre');
const appendItem = (text) => {
const div = document.createElement('div')
div.innerText = text
pre.appendChild(div)
return div
}
input.addEventListener("input", (e) => {
const file = e.target.files[0];
const image = new Image();
image.onload = () => {
const width = image.width;
const height = image.height;
if (!(screen.width * devicePixelRatio === width && screen.height * devicePixelRatio === height)) {
document.querySelector('samp').innerText = '不同机型设备像素比不同,应使用截图的设备运行此脚本';
}
appendItem(\`屏幕分辨率:\${width}x\${height}px\`);
let ctx;
if (window.OffscreenCanvas) {
ctx = new OffscreenCanvas(width, height).getContext('2d');
} else {
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext('2d');
}
ctx.drawImage(image, 0, 0);
const imageData = ctx.getImageData(0, 0, width, height);
const pixels = imageData.data;
/**
* @param {number} index
*/
const isWhite = (index) => {
const r = pixels[index];
const g = pixels[index + 1];
const b = pixels[index + 2];
const a = pixels[index + 3];
return r === 255 && g === 255 && b === 255 && a === 255;
};
let minX = 0;
let maxX = width;
const arr = [];
const visited = new Array(width * height).fill(false);
const dfs = (x, y) => {
const stack = [[x, y]];
let minX = x,
maxX = x,
minY = y,
maxY = y;
while (stack.length) {
const [cx, cy] = stack.pop();
const index = (cy * width + cx) * 4;
if (visited[cy * width + cx] || !isWhite(index)) {
continue;
}
visited[cy * width + cx] = true;
if (cx < minX) minX = cx;
if (cx > maxX) maxX = cx;
if (cy < minY) minY = cy;
if (cy > maxY) maxY = cy;
const neighbors = [
[cx + 1, cy],
[cx - 1, cy],
[cx, cy + 1],
[cx, cy - 1],
];
for (const [nx, ny] of neighbors) {
if (nx > 0 && nx < width && ny > 0 && ny < height) {
stack.push([nx, ny]);
}
}
}
return { minX, minY, maxX, maxY };
};
const boxies = [];
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const last = boxies.slice(-1)[0];
if (last && y <= last.maxY) continue;
const index = (y * width + x) * 4;
if (
isWhite(index) &&
x > 4 &&
x < width - 4 &&
!visited[y * width + x]
) {
const box = dfs(x, y);
if ((box.maxX - box.minX + 1 > 64) && (box.maxY - box.minY + 1) > 64) {
// if: 排除文字和图标
boxies.push(box);
}
if (boxies.length > 1) break;
}
}
if (boxies.length > 1) break;
}
const [mediumBox, largeBox] = boxies;
const small = mediumBox.maxY - mediumBox.minY + 1;
const medium = mediumBox.maxX - mediumBox.minX + 1;
const large = largeBox.maxY - largeBox.minY + 1;
const left = mediumBox.minX;
const right = width - left - small;
const top = mediumBox.minY;
const middle = largeBox.minY;
const bottom = top + (largeBox.minY - mediumBox.minY) * 2;
pre.appendChild(document.createElement('br'));
appendItem(\`小号尺寸:\${small}x\${small}px \${small / devicePixelRatio}x\${small / devicePixelRatio}pt\`)
appendItem(\`中号尺寸:\${medium}x\${small}px \${medium / devicePixelRatio}x\${small / devicePixelRatio}pt\`)
appendItem(\`大号尺寸:\${medium}x\${large}px \${medium / devicePixelRatio}x\${large / devicePixelRatio}pt\`)
pre.appendChild(document.createElement('br'));
const code = document.createElement('code')
code.innerText = JSON.stringify(
{ small, medium, large, left, right, top, middle, bottom },
null,
4
).replace(/"/g, '')
pre.appendChild(code)
};
const reader = new FileReader();
reader.onload = (e) => {
image.src = e.target.result;
};
reader.readAsDataURL(file);
});
</script>
</body>
</html>
`;
if (config.runsInApp) {
const webView = new WebView();
await loadHTML(webView, { html });
webView.present(false);
}