diff --git a/README.md b/README.md
index 6805deb..8337181 100644
--- a/README.md
+++ b/README.md
@@ -1,3 +1,5 @@
+### [中文文档](https://github.com/xkerwin/Weather-Cal/blob/main/README_cn.md)
+
# Weather Cal
This is a Scriptable widget that allows you to display, position, and format multiple elements, including the date, a greeting, your upcoming events, the current weather, and future weather. You can even create your own elements by writing a function that has a single WidgetStack as an argument (representing a column).
diff --git a/README_cn.md b/README_cn.md
new file mode 100644
index 0000000..c417822
--- /dev/null
+++ b/README_cn.md
@@ -0,0 +1,156 @@
+# Weather Cal
+
+这是一个Scriptable的小部件,可让您显示和设置多个格式的元素,包括【日期】【问候语】【日程事件】,【当前天气】【未来天气】【日出/落时间】和【电池电量】。您甚至可以通过编写一个具有单个WidgetStack作为参数的函数(representing a column)来创建自己要显示的元素。
+
+## 如何设置
+
+在开始之前,您可能需要对`weather-cal.js`文件进行一些编辑。您可以在计算机上进行编辑并转移到iOS,也可以仅在Scriptable中进行编辑。
+
+1. 到[free OpenWeather API key](http://openweathermap.org/api)注册一个账号,获得API key,然后粘贴到 `apiKey = ""`的引号内,请注意,这个API可能需要一段时间才生效!
+2. 基础设置:编辑`weather-cal.js`的【小部件设置】部分来进行一些基础设置(注意看注释)
+3. 运行脚本。它会提示您获取定位信息和选择背景图片(如果启用)。最后,它会在Scriptable中显示预览。
+4. 在桌面上添加Scriptable的Widget,长按选择`weather-cal`即可。
+
+如果你需要在这个小部件脚本上使用透明背景,请先使用这个 [Transparent Widgets.js](https://github.com/xkerwin/Weather-Cal/blob/main/Transparent%20Widgets%20Export.js)来制作,在最后,选择导出到相册,然后再次运行`weather-cal`选择刚刚制作好的背景图即可
+
+关于其他调整与设置,参见:[FAQ](https://github.com/xkerwin/Weather-Cal/blob/main/README_cn.md#faq)
+
+## 布局调整
+
+要进行布局,请找到` LAYOUT`部分的标题。您将看到两个带有项目列表的区域:一个用于左列,一个用于右列。您可以在每个列表中添加和删除项目。不要更改此区域中其他部分的代码(列宽除外)。并且,请确保每个项目都以逗号(英文符号)结尾,如下所示:
+
+```
+row,
+
+ column,
+ date,
+ battery,
+ sunrise,
+ space,
+
+ column(100),
+ current,
+ future,
+
+row,
+
+ column,
+ events,
+```
+
+### 向小部件添加项目
+
+- __widget item添加__ 每个单词后以逗号结束。您可以在小部件中添加以下项目:_`日期`,`问候`,`事件`,`电池`,`当前`和`未来天气`,`日出(显示日出和日落)`_,以及_`文本文字`_,确保每个项目始终将其放在`column`项目的下面。
+
+- 如果你想更改项目的显示方式,请到` ITEM SETTINGS`部分。大多数项目允许您调整它们的显示方式。
+
+- `row/行`和`column/列`项用于创建小部件的布局结构。在上面的代码中,小部件的一行包含两列,另一行只含一列。您可以添加或删除行和列,您只需知道每一行下面至少要添加一个列。默认情况下,行和列的大小匹配。您还可以使用括号指定其大小,例如:` row(50)`或` column(100)`。
+
+- 默认情况下,小部件中的所有项目均为居左对齐。您可以在列表中的任意位置添加对齐` left`,` right`或` center`),会将对齐方式应用于这个列下的所有内容。
+
+- 添加`space`将添加一个空间,该空间会自动扩展以填充小部件中的可用空间。此空间上方的所有内容都将与顶部对齐,此空间下方的所有内容都将与底部对齐。
+
+## 细节说明
+
+用户可以在`LAYOUT`部分的`items`数组中添加和删除项目,以选择小部件中显示的内容。项目要么是函数对象`events`,要么是函数调用` space(50)`,它们返回一个函数对象。无论哪种方式,小部件构造代码都希望每个项目都是一个带有单个` column`参数的函数。
+
+当脚本运行时,它仅调用`items`数组中的每个函数并传递到当前列。由于大多数窗口小部件项目都需要执行`async`工作,因此脚本在调用函数时会使用`await`表达式。
+
+上面讨论的布局项的特殊之处在于,它们使用并继承了全局的`currentRow`,`currentColumn`和`currentAlignment`变量,以便创建行和列或调整对齐方式。
+
+### 如何创建一个小部件项目
+
+如果要创建自己的窗口小部件项目,请参考以下必需/可选条件:
+
+* __必需条件:__ 具有小部件项目名称的函数,例如:`function date(column)`。函数的名称是用户在`LAYOUT`部分中输入的名称。该函数需要有一个`column`参数,该函数代表将其添加到WidgetStack的元素。对于元素周围的填充/内边距,请使用全局`padding`变量作为`baseline`。
+* __遵从条件:__ 如果小部件项目需要显示文本,则应使用`provideText`函数以及`textFormat`对象中的值。如果你愿意,可以使用现有值,也可以增加其他值。
+* __遵从条件:__ 如果小部件项目需要显示诸如标签之类的预定义字符串,则必须在`localizedText`对象中定义它们。这可以让用户轻松地将文本翻译成他们喜欢的语言。
+* __可选条件:__ 允许用户选择窗口小部件项目的显示方式来设置对象。使用标题注释和解释每个设置或设置组的注释来匹配` ITEM SETTINGS`部分中的现有格式。经过深思熟虑且功能强大的设置当然是最好的。
+* __可选条件:__ 用于存储项目所需的结构化数据的变量。名称应为一个单词,后接`Data`。例如:`weatherData`。与其他数据变量(`eventData`,`locationData`等)一起声明。确保没有重复于现有的数据变量包含项所需的信息。
+* __遵从条件:__ 如果小部件项目使用数据变量,则需要设置功能。名称应为` setup`,后接一个单词。例如:`setupWeather`。如果您使用的是设置功能,则项目函数应检查数据是否为空,如果是,则运行设置功能。例如:`if (!weatherData) { await setupWeather() }`。如果需要,这是允许其他窗口小部件项目使用提供的数据。例如,`current`和`future`天气项目都使用` weatherData`,因此它们都检查此变量并在需要时运行该设置。
+
+## FAQ
+
+__使用须知:__ 无论是Github链接还是js文本,都必须导入到app(scriptable)中,Gituhub可以直接找到js文件格式后进行复制粘贴。
+
+* __使用前必要条件:__ 请确认是否给Scriptable获取定位信息的权限,如果之前有禁止的,请在 _系统-设置-隐私-定位服务-Scriptable_ 重新授权。
+
+* __首次运行出错:__ 请检查你的API是否填写,并是否填写格式正确。
+
+* __透明背景:__ 先使用制作“透明背景”的脚本,选择你的屏幕空白页的截图来制作,需要小号就选择小号的,中号就选择中号的,然后选择位置,是你接下来想放置widget的位置,上、中、下,不要搞错了,不然就会出现背景图对不上,不能“透明”的问题,然后脚本运行到最后选择【导出到相册】,然后重新运行需要使用“透明”背景的脚本(script)选择刚刚制作好的“透明”背景图(其他widget脚本方法类似)
+
+* __怎么更换背景图:__ 在`Weather- Cal.js` 文件中,打开编辑它,找到`const forceImageUpdate = false`这一行,更改为`true`,如果不想下次运行重新选择背景图,则再次编辑更改为`false`,代码中有注释的,麻烦仔细看看!
+
+* __刷新频率:__ 觉得有点耗电,是否能修改刷新频次来解决,答案是,__不能__。
+
+* __天气显示不正确:__ 解决方法:[点击这里](https://openweathermap.org/ )注册账户,并且邮箱认证成功后,网站上的API密钥可直接生效使用。找到脚本中的 [API key]( https://home.openweathermap.org/api_keys) / [City ID]( https://openweathermap.org/city)
+
+ ```js
+ const apiKey = "API KEY 填入引号内!!!!"
+ ```
+
+- __怎么添加/删除显示的内容:__
+
+ ```js
+ |-----------------------------|
+ | greeting | 100 |
+ | date | current |
+ | battery | sunrise |
+ |-----------------------------|
+ | events | future |
+ |-----------------------------|
+
+ const items = [
+
+ row,//这个是第一行
+
+ column,//这个是列,这列归属于第一行
+ greeting, //这个是问候语内容
+ date,//这个是日期内容
+ battery,//这个是电池内容
+
+ column(100),//这个是列,这列归属于第一行,(100)代表列宽
+ right,//这个代表向右对齐,不设置则默认向左对齐
+ current,//这个是当前天气内容
+ sunrise,//这个是日出/落内容
+
+ row,//这个是第二行
+
+ column,//这个是列,归属于第二行
+ left,//这个是向左对齐
+ events,//这个是日程事件内容
+
+ column(100),//这个是列,这列归属于第二行,(100)代表列宽
+ right,//这代表向右对齐,不设置则默认向左对齐
+ future,//这个是未来天气
+
+ ]
+ ```
+
+- __间距不正确:__ 找到相对应的`padding`进行修改
+
+ ```js
+ |-----------------------------|
+ | greeting | 100 |
+ | date | current |
+ | battery | sunrise |
+ |-----------------------------|
+ | events | future |
+ |-----------------------------|
+
+ 例如:问候语与日期之间的间距太大了,则可以修改"greetingStack"的下内边距
+
+ "greetingStack.setPadding(padding, padding, padding, padding)"
+
+ 一个"padding=5"的间距(默认),四个padding值依次是"上,左,下,右",要修改"greetingStack"的下内边距则修改第三个padding——"greetingStack.setPadding(padding, padding, padding/2, padding)",可以直接除以2,或者直接填了一个数值。
+
+ 同样,如果觉得修改到最小0,还是觉得间距太大了,则可以修改日期的上内边距,同样找到"dateStack"修改第一个padding。
+ ```
+
+- __天气小组件延伸脚本-诗词获取:__,***左列增加诗词获取*** 可直接下载脚本,重新运行脚本即可。
+
+ 链接:https://pan.baidu.com/s/1_zQIUtiRj9yCQSNuVvcNbg
+
+ 提取码:6vyL
+
+ 感谢群友@阿哲,提供。
diff --git a/Transparent Widgets_BG.js b/Transparent Widgets_BG.js
new file mode 100644
index 0000000..b388377
--- /dev/null
+++ b/Transparent Widgets_BG.js
@@ -0,0 +1,268 @@
+// Variables used by Scriptable.
+// These must be at the very top of the file. Do not edit.
+// icon-color: light-brown; icon-glyph: magic;
+
+// Variables used by Scriptable.
+// These must be at the very top of the file. Do not edit.
+// icon-color: deep-purple; icon-glyph: image;
+
+// This widget was created by Max Zeryck @mzeryck
+
+// Widgets are unique based on the name of the script.
+const filename = Script.name() + ".jpg";
+const files = FileManager.local();
+const path = files.joinPath(files.documentsDirectory(), filename);
+
+if (config.runsInWidget) {
+ let widget = new ListWidget();
+ widget.backgroundImage = files.readImage(path);
+
+ // You can your own code here to add additional items to the "invisible" background of the widget.
+
+ Script.setWidget(widget);
+ Script.complete();
+
+ /*
+ * The code below this comment is used to set up the invisible widget.
+ * ===================================================================
+ */
+} else {
+ // Determine if user has taken the screenshot.
+ var message;
+ message =
+ "以下是【透明背景】生成步骤,如果你没有屏幕截图请退出,并返回主屏幕长按进入编辑模式。滑动到最右边的空白页截图。然后重新运行!";
+ let exitOptions = ["继续(已有截图)", "退出(没有截图)"];
+ let shouldExit = await generateAlert(message, exitOptions);
+ if (shouldExit) return;
+
+ // Get screenshot and determine phone size.
+ let img = await Photos.fromLibrary();
+ let height = img.size.height;
+ let phone = phoneSizes()[height];
+ if (!phone) {
+ message = "您似乎选择了非iPhone屏幕截图的图像,或者不支持您的iPhone。请使用其他图像再试一次!";
+ await generateAlert(message, ["好的!我现在去截图"]);
+ return;
+ }
+
+ // Prompt for widget size and position.
+ message = "您想要创建什么尺寸的小部件?";
+ let sizes = ["小号", "中号", "大号"];
+ let size = await generateAlert(message, sizes);
+ let widgetSize = sizes[size];
+
+ message = "您想它在什么位置?";
+ message += height == 1136 ? " (请注意,您的设备仅支持两行小部件,因此中间和底部选项相同。)" : "";
+
+ // Determine image crop based on phone size.
+ let crop = { w: "", h: "", x: "", y: "" };
+ if (widgetSize == "小号") {
+ crop.w = phone.小号;
+ crop.h = phone.小号;
+ let positions = ["顶部 左边", "顶部 右边", "中间 左边", "中间 右边", "底部 左边", "底部 右边"];
+ let position = await generateAlert(message, positions);
+
+ // Convert the two words into two keys for the phone size dictionary.
+ let keys = positions[position].toLowerCase().split(" ");
+ crop.y = phone[keys[0]];
+ crop.x = phone[keys[1]];
+ } else if (widgetSize == "中号") {
+ crop.w = phone.中号;
+ crop.h = phone.小号;
+
+ // Medium and large widgets have a fixed x-value.
+ crop.x = phone.左边;
+ let positions = ["顶部", "中间", "底部"];
+ let position = await generateAlert(message, positions);
+ let key = positions[position].toLowerCase();
+ crop.y = phone[key];
+ } else if (widgetSize == "大号") {
+ crop.w = phone.中号;
+ crop.h = phone.大号;
+ crop.x = phone.左边;
+ let positions = ["顶部", "底部"];
+ let position = await generateAlert(message, positions);
+
+ // Large widgets at the bottom have the "middle" y-value.
+ crop.y = position ? phone.中间 : phone.顶部;
+ }
+
+ // Crop image and finalize the widget.
+ let imgCrop = cropImage(img, new Rect(crop.x, crop.y, crop.w, crop.h));
+
+ message = "您的小部件背景已准备就绪。您想在Scriptable的小部件中使用它还是导出图像?";
+ const exportPhotoOptions = ["在小部件中使用", "导出到相册"];
+ const exportPhoto = await generateAlert(message, exportPhotoOptions);
+
+ if (exportPhoto) {
+ Photos.save(imgCrop);
+ } else {
+ files.writeImage(path, imgCrop);
+ }
+
+ Script.complete();
+}
+
+// Generate an alert with the provided array of options.
+async function generateAlert(message, options) {
+ let alert = new Alert();
+ alert.message = message;
+
+ for (const option of options) {
+ alert.addAction(option);
+ }
+
+ let response = await alert.presentAlert();
+ return response;
+}
+
+// Crop an image into the specified rect.
+function cropImage(img, rect) {
+ let draw = new DrawContext();
+ draw.size = new Size(rect.width, rect.height);
+
+ draw.drawImageAtPoint(img, new Point(-rect.x, -rect.y));
+ return draw.getImage();
+}
+
+// Pixel sizes and positions for widgets on all supported phones.
+function phoneSizes() {
+ let phones = {
+ // 11 Pro Max,Xs Max
+ 2688: {
+ 小号: 507,
+ 中号: 1080,
+ 大号: 1137,
+ 左边: 81,
+ 右边: 654,
+ 顶部: 228,
+ 中间: 858,
+ 底部: 1488,
+ },
+ // 11,XR
+ 1792: {
+ 小号: 338,
+ 中号: 720,
+ 大号: 758,
+ 左边: 54,
+ 右边: 436,
+ 顶部: 160,
+ 中间: 580,
+ 底部: 1000,
+ },
+ // 11 Pro,Xs,X
+ 2436: {
+ 小号: 465,
+ 中号: 987,
+ 大号: 1035,
+ 左边: 69,
+ 右边: 591,
+ 顶部: 213,
+ 中间: 783,
+ 底部: 1353,
+ },
+ // Plus Phones
+ 2208: {
+ 小号: 471,
+ 中号: 1044,
+ 大号: 1071,
+ 左边: 99,
+ 右边: 672,
+ 顶部: 114,
+ 中间: 696,
+ 底部: 1278,
+ },
+ //SE2 and 6/6s/7/8
+ 1334: {
+ 小号: 296,
+ 中号: 642,
+ 大号: 648,
+ 左边: 54,
+ 右边: 400,
+ 顶部: 60,
+ 中间: 412,
+ 底部: 764,
+ },
+ //SE1
+ 1136: {
+ 小号: 282,
+ 中号: 584,
+ 大号: 622,
+ 左边: 30,
+ 右边: 332,
+ 顶部: 59,
+ 中间: 399,
+ 底部: 399,
+ },
+ // 12 and 12 Pro
+ 2532: {
+ 小号: 474,
+ 中号: 1014,
+ 大号: 1062,
+ 左边: 78,
+ 右边: 618,
+ 顶部: 231,
+ 中间: 819,
+ 底部: 1407,
+ },
+ // 12 Mini
+ 2340: {
+ 小号: 436,
+ 中号: 936,
+ 大号: 980,
+ 左边: 72,
+ 右边: 570,
+ 顶部: 212,
+ 中间: 756,
+ 底部: 1300,
+ },
+ // 12 Pro max
+ 2778: {
+ 小号: 518,
+ 中号: 1114,
+ 大号: 1162,
+ 左边: 86,
+ 右边: 678,
+ 顶部: 252,
+ 中间: 898,
+ 底部: 1544,
+ },
+ // 11 and XR in Display Zoom mode
+ 1624: {
+ 小号: 310,
+ 中号: 658,
+ 大号: 690,
+ 左边: 46,
+ 右边: 394,
+ 顶部: 142,
+ 中间: 522,
+ 底部: 902,
+ },
+ //Plus in Display Zoom mode
+ 2001: {
+ 小号: 444,
+ 中号: 963,
+ 大号: 972,
+ 左边: 81,
+ 右边: 600,
+ 顶部: 90,
+ 中间: 618,
+ 底部: 1146,
+ },
+ // iPad Air 4
+ 2360: {
+ 小号: 310,
+ 中号: 658,
+ 大号: 658,
+ 左边: 132,
+ 右边: 480,
+ 顶部: 160,
+ 中间: 508,
+ 底部: 856,
+ },
+
+
+
+ };
+ return phones;
+}
diff --git a/Weather-Cal/CONTRIBUTING.md b/Weather-Cal/CONTRIBUTING.md
new file mode 100644
index 0000000..40effb5
--- /dev/null
+++ b/Weather-Cal/CONTRIBUTING.md
@@ -0,0 +1,29 @@
+# Contributing
+I created Weather Cal because I wanted to see if it was possible to build a widget layout engine on top of Scriptable's already excellent widget APIs. I honestly never expected anyone to contribute, and so I am grateful to those who have. I'm documenting the guidelines for the base branch, which are the ones I follow in my own code. I know this may be a bit overboard for a small project, but I'm using this as a chance to learn and practice these project maintenance skills.
+
+## When to open a pull request
+Bug fixes and tweaks or additions to existing features are always welcome. For new features, consider what a broad audience would find useful. I would love to see forks with more esoteric or niche widget items, but I'd like to keep the base branch not too cluttered.
+
+For any pull request, please follow the conventions listed below and try to match the existing style.
+
+## Conventions
+* Indent using two spaces.
+* Add spaces in lists and between operators for readability.
+* Variables use camelCase and describe their purpose in descriptive but concise English.
+* Functions have some predefined naming conventions, like the `setup` prefix for data setup functions. Functions that provide an asset begin with `provide`, and functions that use a DrawContext begin with `draw`.
+* Comments use the following formats:
+```javascript
+/*
+ * SECTION HEADER
+ * Short description of section.
+ * =============================
+ */
+
+// ITEM SETTINGS HEADER
+// ====================
+
+// Briefly describe what key pieces of code are doing.
+```
+* Use comments to clearly explain what code is doing. It's better to over-explain than to under-explain.
+* Prioritize readbility and explainability in general. If a single line of code is too convoluted, or if it's impossible to explain in a concise comment, consider changing it. For example, rather than adding several ternary operators into one huge string concatenation, create well-named individual constants and concatenate them at the end.
+* Keep the number of settings minimal. Instead of always offering a setting, make good choices on behalf of the user. And when a setting is exposed, make it powerful. For example, the single `showCalendarColor` setting for events determines not only whether calendar colors are shown, but also how they are displayed.
diff --git a/Weather-Cal/README.md b/Weather-Cal/README.md
new file mode 100644
index 0000000..8535e35
--- /dev/null
+++ b/Weather-Cal/README.md
@@ -0,0 +1,70 @@
+# Weather Cal
+This is a Scriptable widget that lets you display, position, and format multiple elements, including dates and events, weather information, battery level, and more. If you want to write code to make your own custom widget item, head to "Technical details". Happy scripting!
+
+## Setup
+Setting up Weather Cal is easy. Add the code in weather-cal.js to Scriptable on your device by downloading the file into the Scriptable folder in iCloud Drive or copying and pasting the code into a new Scriptable script. When you run the script, it will walk you through each step of the setup process.
+
+If you want a transparent or translucent blurred widget, use [the Widget Blur script](https://github.com/mzeryck/Widget-Blur/blob/main/widget-blur.js) before you start. At the end of that script, select "Export to Photos", and then use the photo in the Weather Cal setup.
+
+## Customization
+Changing the items that appear on your widget is easy. Scroll to the section of the code that looks like this:
+
+```
+row
+ column
+ date
+ sunset
+ battery
+ space
+ events
+
+ column(90)
+ current
+ future
+```
+
+Each word is a __widget item__. You can add the following items to your widget: `battery`, `date`, `events`, `greeting`, `reminders`, your own custom `text`, `sunrise` (shows sunrise and sunset), and multiple weather items, including the `current` conditions, `future` weather (next hour or next day), and a customizable multi-day `forecast`. If you want to change how an item looks, scroll down to the `ITEM SETTINGS` section. Most items allow you to adjust how they display.
+
+### Layout
+You can change the layout of the widget using the following __layout items__:
+
+* The `row` and `column` items create the structure of the widget. You can add or remove rows and columns, just remember that you __always__ need at least one row and one column, and every row has to start with a column. If you want to specify the size of a row or column, use parentheses: `row(50)` or `column(100)`.
+
+* You can add an alignment item (`left`, `right`, or `center`) anywhere in the layout, and it will align everything after it.
+
+* Using `space` will add a space that automatically expands to fill the vertical space, pushing the items above and below it. You can make fixed-sized spaces using parentheses, like this: `space(50)`.
+
+### ASCII
+If you want to [draw your widget using ASCII](https://twitter.com/mzeryck/status/1316614631868166144), delete all of the items and draw your widget like this:
+```
+ -------------------
+ |date | 90 |
+ |battery |current |
+ |sunrise |future |
+ | | |
+ -------------------
+ | events|
+ -------------------
+ ```
+A full line of `-` (dashes) starts and ends the widget, or makes a new row. Put `|` (pipes) around each column. The spaces around each element name will determine the alignment (left, right, or center). For example, `events` are aligned to the right in the example above. Adding a row with nothing in it will add a flexible space. Starting a column with a number will set it to that width. (The right-hand column in the example above has a width of 90.)
+
+## Technical details
+Weather Cal consists of two scripts: the Weather Cal widget (weather-cal.js) and the Weather Cal code (weather-cal-code.js). When a user first runs the widget script, it downloads the code and saves it as a Scriptable script. It then imports that code as a module and runs it. The widget script is essentially a container for the widget settings, while the code script does the heavy lifting.
+
+### Widget construction
+Users add and remove items from the `layout` string in the `settings` object to determine what is shown in the widget. When the script runs, it parses this string and isolates each item, using the `provideFunction` function to get the corresponding widget item function. If an argument was provided using parentheses, the provided parameter is passed to the function, which acts as a generator. Finally, the item function is passed the current column (a WidgetStack) so it can run.
+
+### Creating a widget item
+Each widget item has the following required and optional elements:
+
+* __Required:__ A function with the name of the widget item, for example: `function date(column)`. The name of the function is what gets entered by the user in the `LAYOUT` section. This function needs to have a single `column` argument, representing the WidgetStack that the function will be adding elements to. For padding around the element, use the global `padding` variable as a baseline.
+
+* __Required:__ Add a value to the `provideFunction` function so the parser knows it exists.
+
+* __Optional:__ A settings object that lets the user choose how the widget item is displayed. Match the existing format in the `ITEM SETTINGS` section using a comment header and comments explaining each setting or group of settings. A small number of well-considered, powerful settings is best.
+
+### Getting data
+Many widget items need to perform asynchronous work to get the data they will display, like the user's location or weather information. The standard way of doing this is creating a setup function that stores data in the shared `data` variable. For example, `setupWeather` stores several data points in `data.weather`. In the `current` and `future` weather items, they begin by checking to see if the data exists: `if (!data.weather) { await setupWeather() }`.
+
+### Displaying text
+To display text, the `provideText` function takes a string, a stack, and a value in the `textFormat` object. If you need to display predefined strings like labels, they must be defined in the `localizedText` object. This allows users to easily translate text into their preferred language.
diff --git a/Weather-Cal/weather-cal-code.js b/Weather-Cal/weather-cal-code.js
new file mode 100644
index 0000000..add8126
--- /dev/null
+++ b/Weather-Cal/weather-cal-code.js
@@ -0,0 +1,1985 @@
+// Variables used by Scriptable.
+// These must be at the very top of the file. Do not edit.
+// icon-color: deep-purple; icon-glyph: calendar;
+
+/*
+
+~
+
+This is the Weather Cal code script.
+Don't delete it or change its name.
+
+To update, run a Weather Cal widget script.
+In the popup, tap "Update code".
+It will update to the newest version.
+
+~
+
+*/
+
+// Warn the user if this script is added to a widget.
+if (config.runsInWidget) {
+ let infoWidget = new ListWidget()
+ infoWidget.addText('"Weather-cal-code" 不作为小部件使用. 请使用"Weather Cal"脚本设置为小部件')
+ Script.setWidget(infoWidget)
+ Script.complete()
+}
+
+// Set up the widget.
+module.exports.runSetup = async (name, iCloudInUse, codeFilename, gitHubUrl) => {
+ return await setup(name, iCloudInUse, codeFilename, gitHubUrl)
+}
+
+// Return the widget.
+module.exports.createWidget = async (settings, name, iCloudInUse) => {
+ return await makeWidget(settings, name, iCloudInUse)
+}
+
+async function setup(name, iCloudInUse, codeFilename, gitHubUrl) {
+
+ const fm = iCloudInUse ? FileManager.iCloud() : FileManager.local()
+ const widgetUrl = "https://raw.githubusercontent.com/KerwinKwong/Weather-Cal/main/Weather-Cal/weather-cal.js"
+
+ // If no setup file exists, this is the initial Weather Cal setup.
+ const setupPath = fm.joinPath(fm.libraryDirectory(), "weather-cal-setup")
+ if (!fm.fileExists(setupPath)) { return await initialSetup() }
+
+ // If a settings file exists for this widget, we're editing settings.
+ const widgetpath = fm.joinPath(fm.libraryDirectory(), "weather-cal-" + name)
+ if (fm.fileExists(widgetpath)) { return await editSettings() }
+
+ // Otherwise, we're setting up this particular widget.
+ await generateAlert("Weather Cal已设置,但是您需要为此小部件选择背景。",["Continue"])
+ return await setWidgetBackground()
+
+ // Run the initial setup.
+ async function initialSetup() {
+
+ // Welcome the user and make sure they like the script name.
+ let message = "欢迎使用Weather Cal。在开始之前,请确保脚本具有所需的名称。"
+ let options = ['我喜欢"' + name + '"这个名字', "我要更改"]
+ let shouldExit = await generateAlert(message,options)
+ if (shouldExit) return
+
+ // Welcome the user and check for permissions.
+ message = "接下来,需要检查您是否已授予Scriptable应用程序权限。 这可能需要几秒钟。"
+ options = ["检查权限"]
+ await generateAlert(message,options)
+
+ let errors = []
+ try { await Location.current() } catch { errors.push("location") }
+ try { await CalendarEvent.today() } catch { errors.push("calendar") }
+ try { await Reminder.all() } catch { errors.push("reminders") }
+
+ let issues
+ if (errors.length > 0) { issues = errors[0] }
+ if (errors.length == 2) { issues += " and " + errors[1] }
+ if (errors.length == 3) { issues += ", " + errors[1] + ", and " + errors[2] }
+
+ if (issues) {
+ message = "Scriptable没有权限" + issues + "。 如果未在“设置”中启用某些功能,则可能无法使用。"
+ options = ["仍然继续设置", "退出设置"]
+ } else {
+ message = "您的权限已启用。"
+ options = ["继续设置"]
+ }
+ shouldExit = await generateAlert(message,options)
+ if (shouldExit) return
+
+ // Set up the weather integration.
+ message = "要在小部件上显示天气,您需要一个OpenWeather API密钥。"
+ options = ["我已有一个密钥", "我需要一个密钥", "我不想显示天气信息"]
+ const weather = await generateAlert(message,options)
+
+ // Show a web view to claim the API key.
+ if (weather == 1) {
+ message = "在下一个窗口中,注册OpenWeather。 找到API密钥,将其复制,然后关闭Web视图。 然后将提示您粘贴密钥。"
+ options = ["继续"]
+ let weather = await generateAlert(message,options)
+
+ let webView = new WebView()
+ webView.loadURL("https://openweathermap.org/home/sign_up")
+ await webView.present()
+ }
+
+ // We need the API key if we're showing weather.
+ if (weather < 2) {
+ const response = await getWeatherKey(true)
+ if (!response) return
+ }
+
+ // Set up background image.
+ await setWidgetBackground()
+
+ // Record setup completion.
+ writePreference("weather-cal-setup", "true")
+
+ message = "您的小部件已准备就绪! 现在,您可以查看预览。 您可以在脚本代码中调整更多设置。 准备好后,将Scriptable小部件添加到主屏幕,然后选择此Weather-cal脚本。"
+ options = ["显示预览"]
+ await generateAlert(message,options)
+
+ // Return and show the preview.
+ return true
+
+ }
+
+ // Edit the widget settings.
+ async function editSettings() {
+ let message = "编辑您的小部件设置。"
+ let options = ["显示预览", "更改背景", "重置API", "更新代码", "重置widget", "退出设置"]
+ const response = await generateAlert(message,options)
+
+ // Return true to show the widget preview.
+ if (response == 0) return true
+
+ // Set the background and show a preview.
+ if (response == 1) {
+ await setWidgetBackground()
+ return true
+ }
+
+ // Set the API key.
+ if (response == 2) {
+ await getWeatherKey()
+ return
+ }
+
+ if (response == 3) {
+ // Prompt the user for updates.
+ message = "您想更新Weather Cal代码吗? 您的小部件将不受影响。"
+ options = ["更新", "退出"]
+ const updateResponse = await generateAlert(message,options)
+
+ // Exit if the user didn't want to update.
+ if (updateResponse) return
+
+ // Try updating the code.
+ const success = await downloadCode(codeFilename, gitHubUrl)
+ message = success ? "代码更新已完成。" : "更新失败,请稍后再试。"
+ options = ["OK"]
+
+ await generateAlert(message,options)
+ return
+ }
+
+ if (response == 4) {
+ const alert = new Alert()
+ alert.message = "您确定要完全重置此小部件吗?"
+ alert.addDestructiveAction("重置")
+ alert.addAction("取消")
+
+ const cancelReset = await alert.present()
+ if (cancelReset === 0) {
+ const success = await downloadCode(name, widgetUrl)
+ message = success ? "脚本已被重置。 关闭脚本,然后重新打开以使更改生效。" : "重置失败"
+ options = ["OK"]
+ await generateAlert(message,options)
+ }
+ return
+ }
+
+ // If response was Exit, just return.
+ return
+ }
+
+ // Get the weather key, optionally determining if it's the first run.
+ async function getWeatherKey(firstRun = false) {
+
+ // Prompt for the key.
+ const apiKey = await promptForText("在下面的输入框中粘贴您的API密钥。", "82c29fdbgd6aebbb595d402f8a65fabf")
+
+ let message, options
+ if (!apiKey || apiKey == "" || apiKey == null) {
+ message = "没有输入API密钥。 尝试再次复制密钥,然后重新运行此脚本。"
+ options = ["退出"]
+ await generateAlert(message,options)
+ return false
+ }
+
+ // Save the key.
+ writePreference("weather-cal-api-key", apiKey)
+
+ // Test to see if the key works.
+ const req = new Request("https://api.openweathermap.org/data/2.5/onecall?lat=37.332280&lon=-122.010980&appid=" + apiKey)
+
+ let val = {}
+ try { val = await req.loadJSON() } catch { val.current = false }
+
+ // Warn the user if it didn't work.
+ if (!val.current) {
+ message = firstRun ? "新的OpenWeather API密钥可能需要几个小时才能激活。 您的小部件一旦启用,将开始显示天气信息。" : "您输入的密钥," + apiKey + ", 没用。 如果是新密钥,则可能需要几个小时才能激活。"
+ options = [firstRun ? "继续" : "OK"]
+ await generateAlert(message,options)
+
+ // Otherwise, confirm that it was saved.
+ } else if (val.current && !firstRun) {
+ message = "新密钥可用并被保存。"
+ options = ["OK"]
+ await generateAlert(message,options)
+ }
+
+ // If we made it this far, we did it.
+ return true
+ }
+
+ // Set the background of the widget.
+ async function setWidgetBackground() {
+
+ // Prompt for the widget background.
+ let message = "您希望小部件使用哪种背景?"
+ let options = ["纯色背景", "自动渐变", "自定义渐变", "选择图片"]
+ let backgroundType = await generateAlert(message,options)
+
+ let background = {}
+ if (backgroundType == 0) {
+ background.type = "color"
+ background.color = await promptForText("输入所需背景颜色的十六进制值。","#007030")
+
+ } else if (backgroundType == 1) {
+ background.type = "auto"
+
+ } else if (backgroundType == 2) {
+ background.type = "gradient"
+ background.initialColor = await promptForText("输入第一个渐变颜色的十六进制值。","#007030")
+ background.finalColor = await promptForText("输入第二个渐变颜色的十六进制值。","#007030")
+
+ } else if (backgroundType == 3) {
+ background.type = "image"
+
+ // Create the Weather Cal directory if it doesn't already exist.
+ const dirPath = fm.joinPath(fm.documentsDirectory(), "Weather Cal")
+ if (!fm.fileExists(dirPath) || !fm.isDirectory(dirPath)) {
+ fm.createDirectory(dirPath)
+ }
+
+ // Determine if a dupe already exists.
+ const dupePath = fm.joinPath(dirPath, name + " 2.jpg")
+ const dupeAlreadyExists = fm.fileExists(dupePath)
+
+ // Get the image and write it to disk.
+ const img = await Photos.fromLibrary()
+ const path = fm.joinPath(dirPath, name + ".jpg")
+ fm.writeImage(path, img)
+
+ // If we just created a dupe, alert the user.
+ if (!dupeAlreadyExists && fm.fileExists(dupePath)) {
+ message = "Weather Cal检测到重复的图像。 请打开“文件”应用,“Scriptable”>“Weather-cal”,并确保文件名为" + name + ".jpg 是正确的。"
+ options = ["OK"]
+ const response = generateAlert(message,options)
+ }
+ }
+
+ writePreference("weather-cal-" + name, background)
+ return true
+ }
+
+ // Download a Scriptable script.
+ async function downloadCode(filename, url) {
+ const pathToCode = fm.joinPath(fm.documentsDirectory(), filename + ".js")
+ const req = new Request(url)
+
+ try {
+ const codeString = await req.loadString()
+ fm.writeString(pathToCode, codeString)
+ return true
+ } catch {
+ return false
+ }
+ }
+
+ // Generate an alert with the provided array of options.
+ async function generateAlert(message,options) {
+
+ const alert = new Alert()
+ alert.message = message
+
+ for (const option of options) {
+ alert.addAction(option)
+ }
+
+ const response = await alert.presentAlert()
+ return response
+ }
+
+ // Prompt for a single text field value.
+ async function promptForText(message,placeholder) {
+ const alert = new Alert()
+ alert.message = message
+ alert.addTextField(placeholder)
+ alert.addAction("OK")
+ await alert.present()
+ return alert.textFieldValue(0)
+ }
+
+ // Write the value of a preference to disk.
+ function writePreference(filename, value) {
+ const path = fm.joinPath(fm.libraryDirectory(), filename)
+
+ if (typeof value === "string") {
+ fm.writeString(path, value)
+ } else {
+ fm.writeString(path, JSON.stringify(value))
+ }
+ }
+}
+
+async function makeWidget(settings, name, iCloudInUse) {
+
+ // All widget items must be documented here.
+ function provideFunction(name) {
+ const functions = {
+ battery() { return battery },
+ center() { return center },
+ column() { return column },
+ covid() { return covid },
+ current() { return current },
+ date() { return date },
+ events() { return events },
+ forecast() { return forecast },
+ future() { return future },
+ greeting() { return greeting },
+ left() { return left },
+ reminders() { return reminders },
+ right() { return right },
+ row() { return row },
+ space() { return space },
+ sunrise() { return sunrise },
+ sunset() { return sunset },
+ text() { return text },
+ }
+ return functions[name]()
+ }
+
+ // Get often-used values from the settings object.
+ let locale = settings.widget.locale
+ const padding = settings.widget.padding
+ const tintIcons = settings.widget.tintIcons
+ const localizedText = settings.localization
+ const textFormat = settings.font
+
+ // Create the other shared variables.
+ var data = {}
+ const currentDate = new Date()
+ const files = iCloudInUse ? FileManager.iCloud() : FileManager.local()
+
+ // Make sure we have a locale value.
+ if (!locale || locale == "" || locale == null) { locale = Device.locale() }
+
+ // Set up the widget with padding.
+ const widget = new ListWidget()
+ const horizontalPad = padding < 10 ? 10 - padding : 10
+ const verticalPad = padding < 15 ? 15 - padding : 15
+ widget.setPadding(horizontalPad, verticalPad, horizontalPad, verticalPad)
+ widget.spacing = 0
+
+ /*
+ * BACKGROUND DISPLAY
+ * ==================
+ */
+
+ // Read the background information from disk.
+ const backgroundPath = files.joinPath(files.libraryDirectory(), "weather-cal-" + name)
+ const backgroundRaw = files.readString(backgroundPath)
+ const background = JSON.parse(backgroundRaw)
+
+ if (background.type == "color") {
+ widget.backgroundColor = new Color(background.color)
+
+ } else if (background.type == "auto") {
+ const gradient = new LinearGradient()
+ const gradientSettings = await setupGradient()
+
+ gradient.colors = gradientSettings.color()
+ gradient.locations = gradientSettings.position()
+
+ widget.backgroundGradient = gradient
+
+ } else if (background.type == "gradient") {
+ const gradient = new LinearGradient()
+ const initialColor = new Color(background.initialColor)
+ const finalColor = new Color(background.finalColor)
+
+ gradient.colors = [initialColor, finalColor]
+ gradient.locations = [0, 1]
+
+ widget.backgroundGradient = gradient
+
+ } else if (background.type == "image") {
+
+ // Determine if our image exists.
+ const dirPath = files.joinPath(files.documentsDirectory(), "Weather Cal")
+ const path = files.joinPath(dirPath, name + ".jpg")
+ const exists = files.fileExists(path)
+
+ // If it exists, load from file.
+ if (exists) {
+ if (iCloudInUse) { await files.downloadFileFromiCloud(path) }
+ widget.backgroundImage = files.readImage(path)
+
+ // If it's missing when running in the widget, use a gray background.
+ } else if (!exists && config.runsInWidget) {
+ widget.backgroundColor = Color.gray()
+
+ // But if we're running in app, prompt the user for the image.
+ } else {
+ const img = await Photos.fromLibrary()
+ widget.backgroundImage = img
+ files.writeImage(path, img)
+ }
+ }
+
+ /*
+ * CONSTRUCTION
+ * ============
+ */
+
+ // Set up the layout variables.
+ var currentRow = {}
+ var currentColumn = {}
+
+ // Set up the initial alignment.
+ var currentAlignment = alignLeft
+
+ // Set up the global ASCII variables.
+ var foundASCII, usingASCII
+ var currentColumns = []
+ var rowNeedsSetup = false
+
+ // Process the layout.
+ for (line of settings.layout.split(/\r?\n/)) {
+ await processLine(line)
+ }
+
+ // Finish the widget and return.
+ return widget
+
+ /*
+ * CONSTRUCTION FUNCTIONS
+ * Processing the layout input.
+ * ============================
+ */
+
+ async function processLine(lineInput) {
+
+ // Trim the input.
+ const line = lineInput.trim()
+
+ // If it's blank, return.
+ if (line == '') { return }
+
+ // If we have a row, we're not using ASCII.
+ if (!foundASCII && line.includes('row')) {
+ foundASCII = true
+ usingASCII = false
+
+ // If we have a row of dashes, we're using ASCII.
+ } else if (!foundASCII && line[0] == '-' && line[line.length-1] == '-') {
+ foundASCII = true
+ usingASCII = true
+ }
+
+ if (usingASCII) { await processASCIILine(line) }
+ else { await processRegularLine(line) }
+
+ }
+
+ // Process a single line of regular layout.
+ async function processRegularLine(lineInput) {
+
+ let line = lineInput
+
+ // If it's using the old style, remove the comma.
+ if (line[line.length-1] == ',') {
+ line = line.slice(0, -1)
+ }
+
+ // If there are no parentheses, run the function.
+ let item = line.split('(')
+ if (!item[1]) {
+ const func = provideFunction(item[0])
+ await func(currentColumn)
+ return
+ }
+
+ // Otherwise, pass the parameter.
+ const param = item[1].slice(0, -1)
+ const func = provideFunction(item[0])(parseInt(param) || param)
+ await func(currentColumn)
+ }
+
+ // Processes a single line of ASCII.
+ async function processASCIILine(lineInput) {
+
+ const line = lineInput.replace(/\.+/g,'')
+
+ // If it's a line, enumerate previous columns (if any) and set up the new row.
+ if (line[0] == '-' && line[line.length-1] == '-') {
+ if (currentColumns.length > 0) { await enumerateColumns() }
+ rowNeedsSetup = true
+ return
+ }
+
+ // If it's the first content row, finish the row setup.
+ if (rowNeedsSetup) {
+ row(currentColumn)
+ rowNeedsSetup = false
+ }
+
+ // If there's a number, this is a setup row.
+ const setupRow = line.match(/\d+/)
+
+ // Otherwise, it has columns.
+ const items = line.split('|')
+
+ // Iterate through each item.
+ for (var i=1; i < items.length-1; i++) {
+
+ // If the current column doesn't exist, make it.
+ if (!currentColumns[i]) { currentColumns[i] = { items: [] } }
+
+ // Now we have a column to add the items to.
+ const column = currentColumns[i].items
+
+ // Get the current item and its trimmed version.
+ const item = items[i]
+ const trim = item.trim()
+
+ // If it's not a function, figure out spacing.
+ if (!provideFunction(trim)) {
+
+ // If it's a setup row, whether or not we find the number, we keep going.
+ if (setupRow) {
+ const value = parseInt(trim, 10)
+ if (value) { currentColumns[i].width = value }
+ continue
+ }
+
+ // If it's blank and we haven't already added a space, add one.
+ const prevItem = column[column.length-1]
+ if (trim == '' && (!prevItem || (prevItem && !prevItem.startsWith("space")))) {
+ column.push("space")
+ }
+
+ // Either way, we're done.
+ continue
+
+ }
+
+ // Determine the alignment.
+ const index = item.indexOf(trim)
+ const length = item.slice(index,item.length).length
+
+ let align
+ if (index > 0 && length > trim.length) { align = "center" }
+ else if (index > 0) { align = "right" }
+ else { align = "left" }
+
+ // Add the items to the column.
+ column.push(align)
+ column.push(trim)
+ }
+ }
+
+ // Runs the function names in each column.
+ async function enumerateColumns() {
+ if (currentColumns.length > 0) {
+ for (col of currentColumns) {
+
+ // If it's null, go to the next one.
+ if (!col) { continue }
+
+ // If there's a width, use the width function.
+ if (col.width) {
+ column(col.width)(currentColumn)
+
+ // Otherwise, create the column normally.
+ } else {
+ column(currentColumn)
+ }
+ for (item of col.items) {
+ const func = provideFunction(item)
+ await func(currentColumn)
+ }
+ }
+ currentColumns = []
+ }
+ }
+
+ /*
+ * LAYOUT FUNCTIONS
+ * These functions manage spacing and alignment.
+ * =============================================
+ */
+
+ // Makes a new row on the widget.
+ function row(input = null) {
+
+ function makeRow() {
+ currentRow = widget.addStack()
+ currentRow.layoutHorizontally()
+ currentRow.setPadding(0, 0, 0, 0)
+ currentColumn.spacing = 0
+
+ // If input was given, make a row of that size.
+ if (input > 0) { currentRow.size = new Size(0,input) }
+ }
+
+ // If there's no input or it's a number, it's being called in the layout declaration.
+ if (!input || typeof input == "number") { return makeRow }
+
+ // Otherwise, it's being called in the generator.
+ else { makeRow() }
+ }
+
+ // Makes a new column on the widget.
+ function column(input = null) {
+
+ function makeColumn() {
+ currentColumn = currentRow.addStack()
+ currentColumn.layoutVertically()
+ currentColumn.setPadding(0, 0, 0, 0)
+ currentColumn.spacing = 0
+
+ // If input was given, make a column of that size.
+ if (input > 0) { currentColumn.size = new Size(input,0) }
+ }
+
+ // If there's no input or it's a number, it's being called in the layout declaration.
+ if (!input || typeof input == "number" || typeof input == "string" ) {
+ return makeColumn
+
+ }
+
+ // Otherwise, it's being called in the generator.
+ else { makeColumn() }
+ }
+
+ // Create an aligned stack to add content to.
+ function align(column) {
+
+ // Add the containing stack to the column.
+ let alignmentStack = column.addStack()
+ alignmentStack.layoutHorizontally()
+
+ // Get the correct stack from the alignment function.
+ let returnStack = currentAlignment(alignmentStack)
+ returnStack.layoutVertically()
+ return returnStack
+ }
+
+ // Create a right-aligned stack.
+ function alignRight(alignmentStack) {
+ alignmentStack.addSpacer()
+ let returnStack = alignmentStack.addStack()
+ return returnStack
+ }
+
+ // Create a left-aligned stack.
+ function alignLeft(alignmentStack) {
+ let returnStack = alignmentStack.addStack()
+ alignmentStack.addSpacer()
+ return returnStack
+ }
+
+ // Create a center-aligned stack.
+ function alignCenter(alignmentStack) {
+ alignmentStack.addSpacer()
+ let returnStack = alignmentStack.addStack()
+ alignmentStack.addSpacer()
+ return returnStack
+ }
+
+ // This function adds a space, with an optional amount.
+ function space(input = null) {
+
+ // This function adds a spacer with the input width.
+ function spacer(column) {
+
+ // If the input is null or zero, add a flexible spacer.
+ if (!input || input == 0) { column.addSpacer() }
+
+ // Otherwise, add a space with the specified length.
+ else { column.addSpacer(input) }
+ }
+
+ // If there's no input or it's a number, it's being called in the column declaration.
+ if (!input || typeof input == "number") { return spacer }
+
+ // Otherwise, it's being called in the column generator.
+ else { input.addSpacer() }
+ }
+
+ // Change the current alignment to right.
+ function right(x) { currentAlignment = alignRight }
+
+ // Change the current alignment to left.
+ function left(x) { currentAlignment = alignLeft }
+
+ // Change the current alignment to center.
+ function center(x) { currentAlignment = alignCenter }
+
+ /*
+ * SETUP FUNCTIONS
+ * These functions prepare data needed for items.
+ * ==============================================
+ */
+
+ // Set up the data.events object.
+ async function setupEvents() {
+
+ data.events = {}
+ const eventSettings = settings.events
+ const calendars = eventSettings.selectCalendars
+ const numberOfEvents = eventSettings.numberOfEvents
+
+ // Function to determine if an event should be shown.
+ function shouldShowEvent(event) {
+
+ // If events are filtered and the calendar isn't in the selected calendars, return false.
+ if (calendars.length && !calendars.includes(event.calendar.title)) { return false }
+
+ // Hack to remove canceled Office 365 events.
+ if (event.title.startsWith("Canceled:")) { return false }
+
+ // If it's an all-day event, only show if the setting is active.
+ if (event.isAllDay) { return eventSettings.showAllDay }
+
+ // Otherwise, return the event if it's in the future or recently started.
+ const minutesAfter = eventSettings.minutesAfter * 60000 || 0
+ return (event.startDate.getTime() + minutesAfter > currentDate.getTime())
+ }
+
+ // Determine which events to show, and how many.
+ const todayEvents = await CalendarEvent.today([])
+ let shownEvents = 0
+ let futureEvents = []
+
+ for (const event of todayEvents) {
+ if (shownEvents == numberOfEvents) { break }
+ if (shouldShowEvent(event)) {
+ futureEvents.push(event)
+ shownEvents++
+ }
+ }
+
+ // If there's room and we need to, show tomorrow's events.
+ let multipleTomorrowEvents = false
+ let showTomorrow = eventSettings.showTomorrow
+
+ // Determine if we're specifying an hour to show.
+ if (typeof showTomorrow == "number") {
+ showTomorrow = (currentDate.getHours() > showTomorrow)
+ }
+
+ if (showTomorrow && shownEvents < numberOfEvents) {
+
+ const tomorrowEvents = await CalendarEvent.tomorrow([])
+ for (const event of tomorrowEvents) {
+ if (shownEvents == numberOfEvents) { break }
+ if (shouldShowEvent(event)) {
+
+ // Add the tomorrow label prior to the first tomorrow event.
+ if (!multipleTomorrowEvents) {
+
+ // The tomorrow label is pretending to be an event.
+ futureEvents.push({ title: localizedText.tomorrowLabel.toUpperCase(), isLabel: true })
+ multipleTomorrowEvents = true
+ }
+
+ // Show the tomorrow event and increment the counter.
+ futureEvents.push(event)
+ shownEvents++
+ }
+ }
+ }
+
+ // Store the future events, and whether or not any events are displayed.
+ data.events.futureEvents = futureEvents
+ data.events.eventsAreVisible = (futureEvents.length > 0) && (eventSettings.numberOfEvents > 0)
+ }
+
+ // Set up the data.reminders object.
+ async function setupReminders() {
+
+ data.reminders = {}
+ const reminderSettings = settings.reminders
+ const lists = reminderSettings.selectLists
+ const numberOfReminders = reminderSettings.numberOfReminders
+ const showWithoutDueDate = reminderSettings.showWithoutDueDate
+ const showOverdue = reminderSettings.showOverdue
+
+ // Function to determine if an event should be shown.
+ function shouldShowReminder(reminder) {
+
+ // If reminders are filtered and the list isn't in the selected lists, return false.
+ if (lists.length && !lists.includes(reminder.calendar.title)) { return false }
+
+ // If there's no due date, use the setting.
+ if (!reminder.dueDate) { return showWithoutDueDate }
+
+ // If it's overdue, use the setting.
+ if (reminder.isOverdue) { return showOverdue }
+
+ // If we only want today and overdue, use the setting.
+ if (reminderSettings.todayOnly) {
+ return sameDay(reminder.dueDate, currentDate)
+ }
+
+ // Otherwise, return true.
+ return true
+ }
+
+ // Determine which reminders to show.
+ let reminders = await Reminder.allIncomplete()
+ reminders = reminders.filter(shouldShowReminder).slice(0,numberOfReminders)
+
+ // Sort in order of due date.
+ reminders.sort(function(a, b) {
+
+ // Due dates are always picked first.
+ if (!a.dueDate && b.dueDate) return 1
+ if (a.dueDate && !b.dueDate) return -1
+ if (!a.dueDate && !b.dueDate) return 0
+
+ // Otherwise, earlier due dates go first.
+ const aTime = a.dueDate.getTime()
+ const bTime = b.dueDate.getTime()
+
+ if (aTime > bTime) return 1
+ if (aTime < bTime) return -1
+ return 0
+ })
+
+ // Store the data.
+ data.reminders.all = reminders
+ }
+
+ // Set up the gradient for the widget background.
+ async function setupGradient() {
+
+ // Requirements: sunrise
+ if (!data.sun) { await setupSunrise() }
+
+ let gradient = {
+ dawn: {
+ color() { return [new Color("142C52"), new Color("1B416F"), new Color("62668B")] },
+ position() { return [0, 0.5, 1] },
+ },
+
+ sunrise: {
+ color() { return [new Color("274875"), new Color("766f8d"), new Color("f0b35e")] },
+ position() { return [0, 0.8, 1.5] },
+ },
+
+ midday: {
+ color() { return [new Color("3a8cc1"), new Color("90c0df")] },
+ position() { return [0, 1] },
+ },
+
+ noon: {
+ color() { return [new Color("b2d0e1"), new Color("80B5DB"), new Color("3a8cc1")] },
+ position() { return [-0.2, 0.2, 1.5] },
+ },
+
+ sunset: {
+ color() { return [new Color("32327A"), new Color("662E55"), new Color("7C2F43")] },
+ position() { return [0.1, 0.9, 1.2] },
+ },
+
+ twilight: {
+ color() { return [new Color("021033"), new Color("16296b"), new Color("414791")] },
+ position() { return [0, 0.5, 1] },
+ },
+
+ night: {
+ color() { return [new Color("16296b"), new Color("021033"), new Color("021033"), new Color("113245")] },
+ position() { return [-0.5, 0.2, 0.5, 1] },
+ },
+ }
+
+ const sunrise = data.sun.sunrise
+ const sunset = data.sun.sunset
+
+ // Use sunrise or sunset if we're within 30min of it.
+ if (closeTo(sunrise)<=15) { return gradient.sunrise }
+ if (closeTo(sunset)<=15) { return gradient.sunset }
+
+ // In the 30min before/after, use dawn/twilight.
+ if (closeTo(sunrise)<=45 && currentDate.getTime() < sunrise) { return gradient.dawn }
+ if (closeTo(sunset)<=45 && currentDate.getTime() > sunset) { return gradient.twilight }
+
+ // Otherwise, if it's night, return night.
+ if (isNight(currentDate)) { return gradient.night }
+
+ // If it's around noon, the sun is high in the sky.
+ if (currentDate.getHours() == 12) { return gradient.noon }
+
+ // Otherwise, return the "typical" theme.
+ return gradient.midday
+ }
+
+ // Set up the location data object.
+ async function setupLocation() {
+
+ // Get the cached location info if it exists.
+ const locationPath = files.joinPath(files.libraryDirectory(), "weather-cal-location")
+ const locationExists = files.fileExists(locationPath)
+ let cachedLocation
+ if (locationExists) {
+ cachedLocation = JSON.parse(files.readString(locationPath))
+ }
+
+ // If it's been more than an hour, ask iOS for location.
+ let location, geocode
+ const timeToCache = 60 * 60 * 1000
+ const locationDate = locationExists ? files.modificationDate(locationPath).getTime() : -(timeToCache+1)
+ const locationDataOld = (currentDate.getTime() - locationDate) > timeToCache
+ if (locationDataOld) {
+ try {
+ location = await Location.current()
+ geocode = location ? await Location.reverseGeocode(location.latitude, location.longitude, locale) : false
+ } catch {}
+ }
+
+ // Store the possible location values in the data object.
+ data.location = {}
+
+ if (location) {
+ data.location.latitude = location.latitude
+ data.location.longitude = location.longitude
+ } else {
+ data.location.latitude = cachedLocation.latitude
+ data.location.longitude = cachedLocation.longitude
+ }
+
+ if (geocode) {
+ data.location.locality = (geocode[0].locality || geocode[0].postalAddress.city) || geocode[0].administrativeArea
+ } else {
+ data.location.locality = cachedLocation.locality
+ }
+
+ // If we have old location data, save it to disk.
+ if (locationDataOld) {
+ files.writeString(locationPath, JSON.stringify(data.location))
+ }
+ }
+
+ // Set up the sun data object.
+ async function setupSunrise() {
+
+ // Requirements: location
+ if (!data.location) { await setupLocation() }
+
+ async function getSunData(date) {
+ const req = "https://api.sunrise-sunset.org/json?lat=" + data.location.latitude + "&lng=" + data.location.longitude + "&formatted=0&date=" + date.getFullYear() + "-" + (date.getMonth()+1) + "-" + date.getDate()
+ const sunData = await new Request(req).loadJSON()
+ return sunData
+ }
+
+ // Set up the sunrise/sunset cache.
+ const sunCachePath = files.joinPath(files.libraryDirectory(), "weather-cal-sunrise")
+ const sunCacheExists = files.fileExists(sunCachePath)
+ const sunCacheDate = sunCacheExists ? files.modificationDate(sunCachePath) : 0
+ let sunDataRaw
+
+ // If cache exists and was created today, use cached data.
+ if (sunCacheExists && sameDay(currentDate, sunCacheDate)) {
+ const sunCache = files.readString(sunCachePath)
+ sunDataRaw = JSON.parse(sunCache)
+ }
+
+ // Otherwise, get the data from the server.
+ else {
+
+ sunDataRaw = await getSunData(currentDate)
+
+ // Calculate tomorrow's date and get tomorrow's data.
+ let tomorrowDate = new Date()
+ tomorrowDate.setDate(currentDate.getDate() + 1)
+ const tomorrowData = await getSunData(tomorrowDate)
+ sunDataRaw.results.tomorrow = tomorrowData.results.sunrise
+
+ // Cache the file.
+ files.writeString(sunCachePath, JSON.stringify(sunDataRaw))
+ }
+
+ // Store the timing values.
+ data.sun = {}
+ data.sun.sunrise = new Date(sunDataRaw.results.sunrise).getTime()
+ data.sun.sunset = new Date(sunDataRaw.results.sunset).getTime()
+ data.sun.tomorrow = new Date(sunDataRaw.results.tomorrow).getTime()
+ }
+
+ // Set up the weather data object.
+ async function setupWeather() {
+
+ // Get the weather settings.
+ const weatherSettings = settings.weather
+
+ // Requirements: location
+ if (!data.location) { await setupLocation() }
+
+ // Set up the cache.
+ const cachePath = files.joinPath(files.libraryDirectory(), "weather-cal-cache")
+ const cacheExists = files.fileExists(cachePath)
+ const cacheDate = cacheExists ? files.modificationDate(cachePath) : 0
+ let weatherDataRaw
+
+ // If cache exists and it's been less than 60 seconds since last request, use cached data.
+ if (cacheExists && (currentDate.getTime() - cacheDate.getTime()) < 60000) {
+ const cache = files.readString(cachePath)
+ weatherDataRaw = JSON.parse(cache)
+
+ // Otherwise, use the API to get new weather data.
+ } else {
+
+ // OpenWeather only supports a subset of language codes.
+ const openWeatherLang = ["af","al","ar","az","bg","ca","cz","da","de","el","en","eu","fa","fi","fr","gl","he","hi","hr","hu","id","it","ja","kr","la","lt","mk","no","nl","pl","pt","pt_br","ro","ru","sv","se","sk","sl","sp","es","sr","th","tr","ua","uk","vi","zh_cn","zh_tw","zu"]
+ var lang
+
+ // Find all possible language matches.
+ const languages = [locale, locale.split("_")[0], Device.locale(), Device.locale().split("_")[0]]
+
+ for (item of languages) {
+ // If it matches, use the value and stop the loop.
+ if (openWeatherLang.includes(item)) {
+ lang = "&lang=" + item
+ break
+ }
+ }
+
+ const apiKeyPath = files.joinPath(files.libraryDirectory(), "weather-cal-api-key")
+ const apiKey = files.readString(apiKeyPath)
+
+ const weatherReq = "https://api.openweathermap.org/data/2.5/onecall?lat=" + data.location.latitude + "&lon=" + data.location.longitude + "&exclude=minutely,alerts&units=" + settings.widget.units + lang + "&appid=" + apiKey
+ weatherDataRaw = await new Request(weatherReq).loadJSON()
+ files.writeString(cachePath, JSON.stringify(weatherDataRaw))
+ }
+
+ // English continues using the "main" weather description.
+ const english = (locale.split("_")[0] == "en")
+
+ // Store the weather values.
+ data.weather = {}
+ data.weather.currentTemp = weatherDataRaw.current.temp || "--"
+ data.weather.currentCondition = weatherDataRaw.current.weather[0].id || 100
+ data.weather.currentDescription = (english ? weatherDataRaw.current.weather[0].main : weatherDataRaw.current.weather[0].description) || "--"
+ data.weather.todayHigh = weatherDataRaw.daily[0].temp.max || "-"
+ data.weather.todayLow = weatherDataRaw.daily[0].temp.min || "-"
+ data.weather.forecast = [];
+
+ for (let i=0; i <= 7; i++) {
+ data.weather.forecast[i] = {High: weatherDataRaw.daily[i].temp.max || "-", Low: weatherDataRaw.daily[i].temp.min || "-", Condition: weatherDataRaw.daily[i].weather[0].id || 100}
+ }
+ data.weather.tomorrowRain = weatherDataRaw.daily[1].pop
+
+ data.weather.nextHourTemp = weatherDataRaw.hourly[1].temp || "--"
+ data.weather.nextHourCondition = weatherDataRaw.hourly[1].weather[0].id || 100
+ data.weather.nextHourRain = weatherDataRaw.hourly[1].pop
+ }
+
+ // Set up the COVID data object.
+ async function setupCovid() {
+
+ // Set up the COVID cache.
+ const cacheCovidPath = files.joinPath(files.documentsDirectory(), "weather-cal-covid")
+ const cacheCovidExists = files.fileExists(cacheCovidPath)
+ const cacheCovidDate = cacheCovidExists ? files.modificationDate(cacheCovidPath) : 0
+ let covidDataRaw
+
+ // If cache exists and it's been less than 900 seconds (15min) since last request, use cached data.
+ if (cacheCovidExists && (currentDate.getTime() - cacheCovidDate.getTime()) < 900000) {
+ const cacheCovid = files.readString(cacheCovidPath)
+ covidDataRaw = JSON.parse(cacheCovid)
+
+ // Otherwise, use the API to get new data.
+ } else {
+ const covidReq = "https://coronavirus-19-api.herokuapp.com/countries/" + settings.covid.country
+ covidDataRaw = await new Request(covidReq).loadJSON()
+ files.writeString(cacheCovidPath, JSON.stringify(covidDataRaw))
+ }
+
+ data.covid = covidDataRaw
+
+ }
+
+ /*
+ * WIDGET ITEMS
+ * These functions display items on the widget.
+ * ============================================
+ */
+
+ // Display the date on the widget.
+ async function date(column) {
+
+ // Get the settings.
+ const dateSettings = settings.date
+
+ // Requirements: events (if dynamicDateSize is enabled)
+ if (!data.events && dateSettings.dynamicDateSize) { await setupEvents() }
+
+ // Set up the date formatter and set its locale.
+ let df = new DateFormatter()
+ df.locale = locale
+
+ // Show small if it's hard coded, or if it's dynamic and events are visible.
+ if (dateSettings.dynamicDateSize ? data.events.eventsAreVisible : dateSettings.staticDateSize == "small") {
+ let dateStack = align(column)
+ dateStack.setPadding(padding, padding, padding, padding)
+
+ df.dateFormat = dateSettings.smallDateFormat
+ let dateText = provideText(df.string(currentDate), dateStack, textFormat.smallDate)
+
+ // Otherwise, show the large date.
+ } else {
+ let dateOneStack = align(column)
+ df.dateFormat = dateSettings.largeDateLineOne
+ let dateOne = provideText(df.string(currentDate), dateOneStack, textFormat.largeDate1)
+ dateOneStack.setPadding(padding/2, padding, 0, padding)
+
+ let dateTwoStack = align(column)
+ df.dateFormat = dateSettings.largeDateLineTwo
+ let dateTwo = provideText(df.string(currentDate), dateTwoStack, textFormat.largeDate2)
+ dateTwoStack.setPadding(0, padding, padding, padding)
+ }
+ }
+
+ // Display a time-based greeting on the widget.
+ async function greeting(column) {
+
+ // This function makes a greeting based on the time of day.
+ function makeGreeting() {
+ const hour = currentDate.getHours()
+ if (hour < 5) { return localizedText.nightGreeting }
+ if (hour < 12) { return localizedText.morningGreeting }
+ if (hour-12 < 5) { return localizedText.afternoonGreeting }
+ if (hour-12 < 10) { return localizedText.eveningGreeting }
+ return localizedText.nightGreeting
+ }
+
+ // Set up the greeting.
+ let greetingStack = align(column)
+ let greeting = provideText(makeGreeting(), greetingStack, textFormat.greeting)
+ greetingStack.setPadding(padding, padding, padding, padding)
+ }
+
+ // Display events on the widget.
+ async function events(column) {
+
+ // Get the event settings.
+ const eventSettings = settings.events
+
+ // Requirements: events
+ if (!data.events) { await setupEvents() }
+
+ // If no events are visible, figure out what to do.
+ if (!data.events.eventsAreVisible) {
+ const display = eventSettings.noEventBehavior
+
+ // If it's a greeting, let the greeting function handle it.
+ if (display == "greeting") { return await greeting(column) }
+
+ // If it's a message, get the localized text.
+ if (display == "message" && localizedText.noEventMessage.length) {
+ const messageStack = align(column)
+ messageStack.setPadding(padding, padding, padding, padding)
+ provideText(localizedText.noEventMessage, messageStack, textFormat.noEvents)
+ }
+
+ // Whether or not we displayed something, return here.
+ return
+ }
+
+ // Set up the event stack.
+ let eventStack = column.addStack()
+ eventStack.layoutVertically()
+ const todaySeconds = Math.floor(currentDate.getTime() / 1000) - 978307200
+ eventStack.url = 'calshow:' + todaySeconds
+
+ // If there are no events and we have a message, show it and return.
+ if (!data.events.eventsAreVisible && localizedText.noEventMessage.length) {
+ let message = provideText(localizedText.noEventMessage, eventStack, textFormat.noEvents)
+ eventStack.setPadding(padding, padding, padding, padding)
+ return
+ }
+
+ // If we're not showing the message, don't pad the event stack.
+ eventStack.setPadding(0, 0, 0, 0)
+
+ // Add each event to the stack.
+ var currentStack = eventStack
+ const futureEvents = data.events.futureEvents
+ const showCalendarColor = eventSettings.showCalendarColor
+ const colorShape = showCalendarColor.includes("circle") ? "circle" : "rectangle"
+
+ for (let i = 0; i < futureEvents.length; i++) {
+
+ const event = futureEvents[i]
+ const bottomPadding = (padding-10 < 0) ? 0 : padding-10
+
+ // If it's the tomorrow label, change to the tomorrow stack.
+ if (event.isLabel) {
+ let tomorrowStack = column.addStack()
+ tomorrowStack.layoutVertically()
+ const tomorrowSeconds = Math.floor(currentDate.getTime() / 1000) - 978220800
+ tomorrowStack.url = 'calshow:' + tomorrowSeconds
+ currentStack = tomorrowStack
+
+ // Mimic the formatting of an event title, mostly.
+ const eventLabelStack = align(currentStack)
+ const eventLabel = provideText(event.title, eventLabelStack, textFormat.eventLabel)
+ eventLabelStack.setPadding(padding, padding, padding, padding)
+ continue
+ }
+
+ const titleStack = align(currentStack)
+ titleStack.layoutHorizontally()
+
+ // If we're showing a color, and it's not shown on the right, add it to the left.
+ if (showCalendarColor.length && !showCalendarColor.includes("right")) {
+ let colorItemText = provideTextSymbol(colorShape) + " "
+ let colorItem = provideText(colorItemText, titleStack, textFormat.eventTitle)
+ colorItem.textColor = event.calendar.color
+ }
+
+ const title = provideText(event.title.trim(), titleStack, textFormat.eventTitle)
+ titleStack.setPadding(padding, padding, event.isAllDay ? padding : padding/5, padding)
+
+ // If we're showing a color on the right, show it.
+ if (showCalendarColor.length && showCalendarColor.includes("right")) {
+ let colorItemText = " " + provideTextSymbol(colorShape)
+ let colorItem = provideText(colorItemText, titleStack, textFormat.eventTitle)
+ colorItem.textColor = event.calendar.color
+ }
+
+ // If there are too many events, limit the line height.
+ if (futureEvents.length >= 3) { title.lineLimit = 1 }
+
+ // If it's an all-day event, we don't need a time.
+ if (event.isAllDay) { continue }
+
+ // Format the time information.
+ let timeText = formatTime(event.startDate)
+
+ // If we show the length as time, add an en dash and the time.
+ if (eventSettings.showEventLength == "time") {
+ timeText += "–" + formatTime(event.endDate)
+
+ // If we should it as a duration, add the minutes.
+ } else if (eventSettings.showEventLength == "duration") {
+ const duration = (event.endDate.getTime() - event.startDate.getTime()) / (1000*60)
+ const hours = Math.floor(duration/60)
+ const minutes = Math.floor(duration % 60)
+ const hourText = hours>0 ? hours + localizedText.durationHour : ""
+ const minuteText = minutes>0 ? minutes + localizedText.durationMinute : ""
+ const showSpace = hourText.length && minuteText.length
+ timeText += " \u2022 " + hourText + (showSpace ? " " : "") + minuteText
+ }
+
+ const timeStack = align(currentStack)
+ const time = provideText(timeText, timeStack, textFormat.eventTime)
+ timeStack.setPadding(0, padding, padding, padding)
+ }
+ }
+
+ // Display reminders on the widget.
+ async function reminders(column) {
+
+ // Requirements: reminders
+ if (!data.reminders) { await setupReminders() }
+ const reminderSettings = settings.reminders
+
+ // Set up the reminders stack.
+ let reminderStack = column.addStack()
+ reminderStack.layoutVertically()
+ reminderStack.setPadding(0, 0, 0, 0)
+
+ // Add each reminder to the stack.
+ const reminders = data.reminders.all
+ const showListColor = reminderSettings.showListColor
+ const colorShape = showListColor.includes("circle") ? "circle" : "rectangle"
+
+ for (let i = 0; i < reminders.length; i++) {
+
+ const reminder = reminders[i]
+ const bottomPadding = (padding-10 < 0) ? 0 : padding-10
+
+ const titleStack = align(reminderStack)
+ titleStack.layoutHorizontally()
+ const showCalendarColor = reminderSettings.showListColor
+ const colorShape = showListColor.includes("circle") ? "circle" : "rectangle"
+
+ // If we're showing a color, and it's not shown on the right, add it to the left.
+ if (showListColor.length && !showListColor.includes("right")) {
+ let colorItemText = provideTextSymbol(colorShape) + " "
+ let colorItem = provideText(colorItemText, titleStack, textFormat.eventTitle)
+ colorItem.textColor = reminder.calendar.color
+ }
+
+ const title = provideText(reminder.title.trim(), titleStack, textFormat.eventTitle)
+ titleStack.setPadding(padding, padding, padding/5, padding)
+
+ // If we're showing a color on the right, show it.
+ if (showListColor.length && showListColor.includes("right")) {
+ let colorItemText = " " + provideTextSymbol(colorShape)
+ let colorItem = provideText(colorItemText, titleStack, textFormat.eventTitle)
+ colorItem.textColor = reminder.calendar.color
+ }
+
+ // If it doesn't have a due date, keep going.
+ if (!reminder.dueDate) { continue }
+
+ // If it's overdue, display in red without a time.
+ if (reminder.isOverdue) {
+ title.textColor = Color.red()
+ continue
+ }
+
+ // Format with the relative style if set.
+ let timeText
+ if (reminderSettings.useRelativeDueDate) {
+ let rdf = new RelativeDateTimeFormatter()
+ rdf.locale = locale
+ rdf.useNamedDateTimeStyle()
+ timeText = rdf.string(reminder.dueDate, currentDate)
+
+ // Otherwise, use a normal date, time, or datetime format.
+ } else {
+ let df = new DateFormatter()
+ df.locale = locale
+
+ // If it's due today and it has a time, don't show the date.
+ if (sameDay(reminder.dueDate, currentDate) && reminder.dueDateIncludesTime) {
+ df.useNoDateStyle()
+ } else {
+ df.useShortDateStyle()
+ }
+
+ // Only show the time if it's available.
+ if (reminder.dueDateIncludesTime) {
+ df.useShortTimeStyle()
+ } else {
+ df.useNoTimeStyle()
+ }
+
+ timeText = df.string(reminder.dueDate)
+ }
+
+ const timeStack = align(reminderStack)
+ const time = provideText(timeText, timeStack, textFormat.eventTime)
+ timeStack.setPadding(0, padding, padding, padding)
+ }
+ }
+
+ // Display the current weather.
+ async function current(column) {
+
+ // Get the weather settings.
+ const weatherSettings = settings.weather
+
+ // Requirements: weather and sunrise
+ if (!data.weather) { await setupWeather() }
+ if (!data.sun) { await setupSunrise() }
+
+ // Set up the current weather stack.
+ let currentWeatherStack = column.addStack()
+ currentWeatherStack.layoutVertically()
+ currentWeatherStack.setPadding(0, 0, 0, 0)
+ currentWeatherStack.url = "https://weather.com/weather/today/l/" + data.location.latitude + "," + data.location.longitude
+
+ // If we're showing the location, add it.
+ if (weatherSettings.showLocation) {
+ let locationTextStack = align(currentWeatherStack)
+ let locationText = provideText(data.location.locality, locationTextStack, textFormat.smallTemp)
+ locationTextStack.setPadding(padding, padding, padding, padding)
+ }
+
+ // Show the current condition symbol.
+ let mainConditionStack = align(currentWeatherStack)
+ let mainCondition = mainConditionStack.addImage(provideConditionSymbol(data.weather.currentCondition,isNight(currentDate)))
+ mainCondition.imageSize = new Size(22,22)
+ tintIcon(mainCondition, textFormat.largeTemp)
+ mainConditionStack.setPadding(weatherSettings.showLocation ? 0 : padding, padding, 0, padding)
+
+ // Add the temp horizontally if enabled.
+ if (weatherSettings.horizontalCondition) {
+ mainConditionStack.addSpacer(5)
+ mainConditionStack.layoutHorizontally()
+ mainConditionStack.centerAlignContent()
+ const tempText = Math.round(data.weather.currentTemp) + "°"
+ const temp = provideText(tempText, mainConditionStack, textFormat.largeTemp)
+ }
+
+ // If we're showing the description, add it.
+ if (weatherSettings.showCondition) {
+ let conditionTextStack = align(currentWeatherStack)
+ let conditionText = provideText(data.weather.currentDescription, conditionTextStack, textFormat.smallTemp)
+ conditionTextStack.setPadding(padding, padding, 0, padding)
+ }
+
+ // Add the temp vertically if it's not horizontal.
+ if (!weatherSettings.horizontalCondition) {
+ const tempStack = align(currentWeatherStack)
+ tempStack.setPadding(0, padding, 0, padding)
+ const tempText = Math.round(data.weather.currentTemp) + "°"
+ const temp = provideText(tempText, tempStack, textFormat.largeTemp)
+ }
+
+ // If we're not showing the high and low, end it here.
+ if (!weatherSettings.showHighLow) { return }
+
+ // Show the temp bar and high/low values.
+ let tempBarStack = align(currentWeatherStack)
+ tempBarStack.layoutVertically()
+ tempBarStack.setPadding(0, padding, padding, padding)
+
+ let tempBar = drawTempBar()
+ let tempBarImage = tempBarStack.addImage(tempBar)
+ tempBarImage.size = new Size(50,0)
+
+ tempBarStack.addSpacer(1)
+
+ let highLowStack = tempBarStack.addStack()
+ highLowStack.layoutHorizontally()
+
+ const mainLowText = Math.round(data.weather.todayLow).toString()
+ const mainLow = provideText(mainLowText, highLowStack, textFormat.tinyTemp)
+ highLowStack.addSpacer()
+ const mainHighText = Math.round(data.weather.todayHigh).toString()
+ const mainHigh = provideText(mainHighText, highLowStack, textFormat.tinyTemp)
+
+ tempBarStack.size = new Size(60,30)
+ }
+
+ // Display upcoming weather.
+ async function future(column) {
+
+ // Get the weather settings.
+ const weatherSettings = settings.weather
+
+ // Requirements: weather and sunrise
+ if (!data.weather) { await setupWeather() }
+ if (!data.sun) { await setupSunrise() }
+
+ // Set up the future weather stack.
+ let futureWeatherStack = column.addStack()
+ futureWeatherStack.layoutVertically()
+ futureWeatherStack.setPadding(0, 0, 0, 0)
+ futureWeatherStack.url = "https://weather.com/" + locale + "weather/tenday/l/" + data.location.latitude + "," + data.location.longitude
+
+ // Determine if we should show the next hour.
+ const showNextHour = (currentDate.getHours() < weatherSettings.tomorrowShownAtHour)
+
+ // Set the label value.
+ const subLabelStack = align(futureWeatherStack)
+ const subLabelText = showNextHour ? localizedText.nextHourLabel : localizedText.tomorrowLabel
+ const subLabel = provideText(subLabelText, subLabelStack, textFormat.smallTemp)
+ subLabelStack.setPadding(0, padding, padding/2, padding)
+
+ // Set up the sub condition stack.
+ let subConditionStack = align(futureWeatherStack)
+ subConditionStack.layoutHorizontally()
+ subConditionStack.centerAlignContent()
+ subConditionStack.setPadding(0, padding, padding, padding)
+
+ // Determine if it will be night in the next hour.
+ var nightCondition
+ if (showNextHour) {
+ const addHour = currentDate.getTime() + (60*60*1000)
+ const newDate = new Date(addHour)
+ nightCondition = isNight(newDate)
+ } else {
+ nightCondition = false
+ }
+
+ let subCondition = subConditionStack.addImage(provideConditionSymbol(showNextHour ? data.weather.nextHourCondition : data.weather.forecast[1].Condition,nightCondition))
+ const subConditionSize = showNextHour ? 14 : 18
+ subCondition.imageSize = new Size(subConditionSize, subConditionSize)
+ tintIcon(subCondition, textFormat.smallTemp)
+ subConditionStack.addSpacer(5)
+
+ // The next part of the display changes significantly for next hour vs tomorrow.
+ let rainPercent
+ if (showNextHour) {
+ const subTempText = Math.round(data.weather.nextHourTemp) + "°"
+ const subTemp = provideText(subTempText, subConditionStack, textFormat.smallTemp)
+ rainPercent = data.weather.nextHourRain
+
+ } else {
+ let tomorrowLine = subConditionStack.addImage(drawVerticalLine(new Color(textFormat.tinyTemp.color || textFormat.defaultText.color, 0.5), 20))
+ tomorrowLine.imageSize = new Size(3,28)
+ subConditionStack.addSpacer(5)
+ let tomorrowStack = subConditionStack.addStack()
+ tomorrowStack.layoutVertically()
+
+ const tomorrowHighText = Math.round(data.weather.forecast[1].High) + ""
+ const tomorrowHigh = provideText(tomorrowHighText, tomorrowStack, textFormat.tinyTemp)
+ tomorrowStack.addSpacer(4)
+ const tomorrowLowText = Math.round(data.weather.forecast[1].Low) + ""
+ const tomorrowLow = provideText(tomorrowLowText, tomorrowStack, textFormat.tinyTemp)
+ rainPercent = data.weather.tomorrowRain
+ }
+
+ // If we're showing rain percentage, add it.
+ if (weatherSettings.showRain) {
+ let subRainStack = align(futureWeatherStack)
+ subRainStack.layoutHorizontally()
+ subRainStack.centerAlignContent()
+ subRainStack.setPadding(0, padding, padding, padding)
+
+ let subRain = subRainStack.addImage(SFSymbol.named("umbrella").image)
+ const subRainSize = showNextHour ? 14 : 18
+ subRain.imageSize = new Size(subRainSize, subRainSize)
+ subRain.tintColor = new Color(textFormat.smallTemp.color || textFormat.defaultText.color)
+ subRainStack.addSpacer(5)
+
+ const subRainText = provideText(Math.round(rainPercent*100) + "%", subRainStack, textFormat.smallTemp)
+ }
+ }
+
+ // Display forecast weather.
+ async function forecast(column) {
+
+ // Get the weather settings.
+ const weatherSettings = settings.weather
+
+ // Requirements: weather and sunrise
+ if (!data.weather) { await setupWeather() }
+ if (!data.sun) { await setupSunrise() }
+
+ let startIndex = weatherSettings.showToday ? 1 : 2
+ let endIndex = weatherSettings.showDays + startIndex
+ if (endIndex > 9) { endIndex = 9 }
+
+ for (var i=startIndex; i < endIndex; i++) {
+ // Set up the today weather stack.
+ let weatherStack = column.addStack()
+ weatherStack.layoutVertically()
+ weatherStack.setPadding(0, 0, 0, 0)
+ weatherStack.url = "https://weather.com/" + locale +"weather/tenday/l/" + data.location.latitude + "," + data.location.longitude
+
+ // Set up the date formatter and set its locale.
+ let df = new DateFormatter()
+ df.locale = locale
+
+ // Set up the sub condition stack.
+ let subConditionStack = align(weatherStack)
+ var myDate = new Date();
+ myDate.setDate(currentDate.getDate() + (i - 1));
+ df.dateFormat = weatherSettings.showDaysFormat
+
+ let dateStack = subConditionStack.addStack()
+ dateStack.layoutHorizontally()
+ dateStack.setPadding(0, 0, 0, 0)
+
+ let dateText = provideText(df.string(myDate), dateStack, textFormat.smallTemp)
+ dateText.lineLimit = 1
+ dateText.minimumScaleFactor = 0.5
+ dateStack.addSpacer()
+ let fontSize = textFormat.smallTemp.size || textFormat.defaultText.size
+ dateStack.size = new Size(fontSize*2.64,0)
+ subConditionStack.addSpacer(5)
+ subConditionStack.layoutHorizontally()
+ subConditionStack.centerAlignContent()
+ subConditionStack.setPadding(0, padding, padding, padding)
+
+ let subCondition = subConditionStack.addImage(provideConditionSymbol(data.weather.forecast[i - 1].Condition, false))
+ subCondition.imageSize = new Size(18, 18)
+ tintIcon(subCondition, textFormat.smallTemp)
+ subConditionStack.addSpacer(5)
+
+ let tempLine = subConditionStack.addImage(drawVerticalLine(new Color(textFormat.tinyTemp.color || textFormat.defaultText.color, 0.5), 20))
+ tempLine.imageSize = new Size(3,28)
+ subConditionStack.addSpacer(5)
+ let tempStack = subConditionStack.addStack()
+ tempStack.layoutVertically()
+
+ const tempHighText = Math.round(data.weather.forecast[i - 1].High) + ""
+ const tempHigh = provideText(tempHighText, tempStack, textFormat.tinyTemp)
+ tempStack.addSpacer(4)
+ const tempLowText = Math.round(data.weather.forecast[i - 1].Low) + ""
+ const tempLow = provideText(tempLowText, tempStack, textFormat.tinyTemp)
+ }
+ }
+
+ // Add a battery element to the widget.
+ async function battery(column) {
+
+ // Set up the battery level item.
+ const batteryStack = align(column)
+ batteryStack.layoutHorizontally()
+ batteryStack.centerAlignContent()
+ batteryStack.setPadding(padding/2, padding, padding/2, padding)
+
+ // Set up the battery icon.
+ const batteryIcon = batteryStack.addImage(provideBatteryIcon())
+ batteryIcon.imageSize = new Size(30,30)
+
+ // Change the battery icon to red if battery level is less than 20%.
+ const batteryLevel = Math.round(Device.batteryLevel() * 100)
+ if (batteryLevel > 20 || Device.isCharging() ) {
+ batteryIcon.tintColor = new Color(textFormat.battery.color || textFormat.defaultText.color)
+ } else {
+ batteryIcon.tintColor = Color.red()
+ }
+
+ // Format the rest of the item.
+ batteryStack.addSpacer(padding * 0.6)
+ provideText(batteryLevel + "%", batteryStack, textFormat.battery)
+ }
+
+ // Show the sunrise or sunset time.
+ async function sunrise(column, showSunset = false) {
+
+ // Requirements: sunrise
+ if (!data.sun) { await setupSunrise() }
+
+ const sunrise = data.sun.sunrise
+ const sunset = data.sun.sunset
+ const tomorrow = data.sun.tomorrow
+ const current = currentDate.getTime()
+
+ const showWithin = settings.sunrise.showWithin
+ const closeToSunrise = closeTo(sunrise) <= showWithin
+ const closeToSunset = closeTo(sunset) <= showWithin
+
+ // If we only show sometimes and we're not close, return.
+ if (showWithin > 0 && !closeToSunrise && !closeToSunset) { return }
+
+ // Otherwise, determine which time to show.
+ let timeToShow, symbolName
+ const halfHour = 30 * 60 * 1000
+
+ // Determine logic for when to show sunset for a combined element.
+ const combinedSunset = current > sunrise + halfHour && current < sunset + halfHour
+
+ // Determine if we should show the sunset.
+ if (settings.sunrise.separateElements ? showSunset : combinedSunset) {
+ symbolName = "sunset.fill"
+ timeToShow = sunset
+ }
+
+ // Otherwise, show a sunrise.
+ else {
+ symbolName = "sunrise.fill"
+ timeToShow = current > sunset ? tomorrow : sunrise
+ }
+
+ // Set up the stack.
+ const sunriseStack = align(column)
+ sunriseStack.setPadding(padding/2, padding, padding/2, padding)
+ sunriseStack.layoutHorizontally()
+ sunriseStack.centerAlignContent()
+
+ sunriseStack.addSpacer(padding * 0.3)
+
+ // Add the correct symbol.
+ const symbol = sunriseStack.addImage(SFSymbol.named(symbolName).image)
+ symbol.imageSize = new Size(22,22)
+ tintIcon(symbol, textFormat.sunrise)
+
+ sunriseStack.addSpacer(padding)
+
+ // Add the time.
+ const timeText = formatTime(new Date(timeToShow))
+ const time = provideText(timeText, sunriseStack, textFormat.sunrise)
+ }
+
+ // Allow for either term to be used.
+ async function sunset(column) {
+ return await sunrise(column, true)
+ }
+
+ // Return a text-creation function.
+ function text(input = null) {
+
+ function displayText(column) {
+
+ // Don't do anything if the input is blank.
+ if (!input || input == "") { return }
+
+ // Otherwise, add the text.
+ const textStack = align(column)
+ textStack.setPadding(padding, padding, padding, padding)
+ const textDisplay = provideText(input, textStack, textFormat.customText)
+ }
+ return displayText
+ }
+
+ // Display COVID info on the widget.
+ async function covid(column) {
+
+ if (!data.covid) { await setupCovid() }
+
+ // Set up the stack.
+ const covidStack = align(column)
+ covidStack.setPadding(padding/2, padding, padding/2, padding)
+ covidStack.layoutHorizontally()
+ covidStack.centerAlignContent()
+ covidStack.url = settings.covid.url
+
+ covidStack.addSpacer(padding * 0.3)
+
+ // Add the correct symbol.
+ const symbol = covidStack.addImage(SFSymbol.named("bandage").image)
+ symbol.imageSize = new Size(18,18)
+ symbol.tintColor = new Color(textFormat.covid.color || textFormat.defaultText.color)
+
+ covidStack.addSpacer(padding)
+
+ // Add the COVID information.
+ const covidText = localizedText.covid.replace(/{(.*?)}/g, (match, $1) => {
+ let val = data.covid[$1]
+ if (val) val = new Intl.NumberFormat(locale.replace('_','-')).format(val)
+ return val || ""
+ });
+ provideText(covidText, covidStack, textFormat.covid)
+
+ }
+
+ /*
+ * HELPER FUNCTIONS
+ * These functions perform duties for other functions.
+ * ===================================================
+ */
+
+ // Tints icons if needed.
+ function tintIcon(icon,format) {
+ if (!tintIcons) { return }
+ icon.tintColor = new Color(format.color || textFormat.defaultText.color)
+ }
+
+ // Determines if the provided date is at night.
+ function isNight(dateInput) {
+ const timeValue = dateInput.getTime()
+ return (timeValue < data.sun.sunrise) || (timeValue > data.sun.sunset)
+ }
+
+ // Determines if two dates occur on the same day
+ function sameDay(d1, d2) {
+ return d1.getFullYear() === d2.getFullYear() &&
+ d1.getMonth() === d2.getMonth() &&
+ d1.getDate() === d2.getDate()
+ }
+
+ // Returns the number of minutes between now and the provided date.
+ function closeTo(time) {
+ return Math.abs(currentDate.getTime() - time) / 60000
+ }
+
+ // Format the time for a Date input.
+ function formatTime(date) {
+ let df = new DateFormatter()
+ df.locale = locale
+ df.useNoDateStyle()
+ df.useShortTimeStyle()
+ return df.string(date)
+ }
+
+ // Provide a text symbol with the specified shape.
+ function provideTextSymbol(shape) {
+
+ // Rectangle character.
+ if (shape.startsWith("rect")) {
+ return "\u2759"
+ }
+ // Circle character.
+ if (shape == "circle") {
+ return "\u2B24"
+ }
+ // Default to the rectangle.
+ return "\u2759"
+ }
+
+ // Provide a battery SFSymbol with accurate level drawn on top of it.
+ function provideBatteryIcon() {
+
+ // If we're charging, show the charging icon.
+ if (Device.isCharging()) { return SFSymbol.named("battery.100.bolt").image }
+
+ // Set the size of the battery icon.
+ const batteryWidth = 87
+ const batteryHeight = 41
+
+ // Start our draw context.
+ let draw = new DrawContext()
+ draw.opaque = false
+ draw.respectScreenScale = true
+ draw.size = new Size(batteryWidth, batteryHeight)
+
+ // Draw the battery.
+ draw.drawImageInRect(SFSymbol.named("battery.0").image, new Rect(0, 0, batteryWidth, batteryHeight))
+
+ // Match the battery level values to the SFSymbol.
+ const x = batteryWidth*0.1525
+ const y = batteryHeight*0.247
+ const width = batteryWidth*0.602
+ const height = batteryHeight*0.505
+
+ // Prevent unreadable icons.
+ let level = Device.batteryLevel()
+ if (level < 0.05) { level = 0.05 }
+
+ // Determine the width and radius of the battery level.
+ const current = width * level
+ let radius = height/6.5
+
+ // When it gets low, adjust the radius to match.
+ if (current < (radius * 2)) { radius = current / 2 }
+
+ // Make the path for the battery level.
+ let barPath = new Path()
+ barPath.addRoundedRect(new Rect(x, y, current, height), radius, radius)
+ draw.addPath(barPath)
+ draw.setFillColor(Color.black())
+ draw.fillPath()
+ return draw.getImage()
+ }
+
+ // Provide a symbol based on the condition.
+ function provideConditionSymbol(cond,night) {
+
+ // Define our symbol equivalencies.
+ let symbols = {
+
+ // Error
+ "1": function() { return "exclamationmark.circle" },
+
+ // Thunderstorm
+ "2": function() { return "cloud.bolt.rain.fill" },
+
+ // Drizzle
+ "3": function() { return "cloud.drizzle.fill" },
+
+ // Rain
+ "5": function() { return (cond == 511) ? "cloud.sleet.fill" : "cloud.rain.fill" },
+
+ // Snow
+ "6": function() { return (cond >= 611 && cond <= 613) ? "cloud.snow.fill" : "snow" },
+
+ // Atmosphere
+ "7": function() {
+ if (cond == 781) { return "tornado" }
+ if (cond == 701 || cond == 741) { return "cloud.fog.fill" }
+ return night ? "cloud.fog.fill" : "sun.haze.fill"
+ },
+
+ // Clear and clouds
+ "8": function() {
+ if (cond == 800 || cond == 801) { return night ? "moon.stars.fill" : "sun.max.fill" }
+ if (cond == 802 || cond == 803) { return night ? "cloud.moon.fill" : "cloud.sun.fill" }
+ return "cloud.fill"
+ }
+ }
+
+ // Find out the first digit.
+ let conditionDigit = Math.floor(cond / 100)
+
+ // Get the symbol.
+ return SFSymbol.named(symbols[conditionDigit]()).image
+ }
+
+ // Provide a font based on the input.
+ function provideFont(fontName, fontSize) {
+ const fontGenerator = {
+ "ultralight": function() { return Font.ultraLightSystemFont(fontSize) },
+ "light": function() { return Font.lightSystemFont(fontSize) },
+ "regular": function() { return Font.regularSystemFont(fontSize) },
+ "medium": function() { return Font.mediumSystemFont(fontSize) },
+ "semibold": function() { return Font.semiboldSystemFont(fontSize) },
+ "bold": function() { return Font.boldSystemFont(fontSize) },
+ "heavy": function() { return Font.heavySystemFont(fontSize) },
+ "black": function() { return Font.blackSystemFont(fontSize) },
+ "italic": function() { return Font.italicSystemFont(fontSize) }
+ }
+
+ const systemFont = fontGenerator[fontName]
+ if (systemFont) { return systemFont() }
+ return new Font(fontName, fontSize)
+ }
+
+ // Add formatted text to a container.
+ function provideText(string, container, format) {
+ const textItem = container.addText(string)
+ const textFont = format.font || textFormat.defaultText.font
+ const textSize = format.size || textFormat.defaultText.size
+ const textColor = format.color || textFormat.defaultText.color
+
+ textItem.font = provideFont(textFont, textSize)
+ textItem.textColor = new Color(textColor)
+ return textItem
+ }
+
+ /*
+ * DRAWING FUNCTIONS
+ * These functions draw onto a canvas.
+ * ===================================
+ */
+
+ // Draw the vertical line in the tomorrow view.
+ function drawVerticalLine(color, height) {
+
+ const width = 2
+
+ let draw = new DrawContext()
+ draw.opaque = false
+ draw.respectScreenScale = true
+ draw.size = new Size(width,height)
+
+ let barPath = new Path()
+ const barHeight = height
+ barPath.addRoundedRect(new Rect(0, 0, width, height), width/2, width/2)
+ draw.addPath(barPath)
+ draw.setFillColor(color)
+ draw.fillPath()
+
+ return draw.getImage()
+ }
+
+ // Draw the temp bar.
+ function drawTempBar() {
+
+ // Set the size of the temp bar.
+ const tempBarWidth = 200
+ const tempBarHeight = 20
+
+ // Calculate the current percentage of the high-low range.
+ let percent = (data.weather.currentTemp - data.weather.todayLow) / (data.weather.todayHigh - data.weather.todayLow)
+
+ // If we're out of bounds, clip it.
+ if (percent < 0) {
+ percent = 0
+ } else if (percent > 1) {
+ percent = 1
+ }
+
+ // Determine the scaled x-value for the current temp.
+ const currPosition = (tempBarWidth - tempBarHeight) * percent
+
+ // Start our draw context.
+ let draw = new DrawContext()
+ draw.opaque = false
+ draw.respectScreenScale = true
+ draw.size = new Size(tempBarWidth, tempBarHeight)
+
+ // Make the path for the bar.
+ let barPath = new Path()
+ const barHeight = tempBarHeight - 10
+ barPath.addRoundedRect(new Rect(0, 5, tempBarWidth, barHeight), barHeight / 2, barHeight / 2)
+ draw.addPath(barPath)
+
+ // Determine the color.
+ const barColor = textFormat.battery.color || textFormat.defaultText.color
+ draw.setFillColor(new Color(textFormat.tinyTemp.color || textFormat.defaultText.color, 0.5))
+ draw.fillPath()
+
+ // Make the path for the current temp indicator.
+ let currPath = new Path()
+ currPath.addEllipse(new Rect(currPosition, 0, tempBarHeight, tempBarHeight))
+ draw.addPath(currPath)
+ draw.setFillColor(new Color(textFormat.tinyTemp.color || textFormat.defaultText.color, 1))
+ draw.fillPath()
+
+ return draw.getImage()
+ }
+}
diff --git a/Weather-Cal/weather-cal.js b/Weather-Cal/weather-cal.js
new file mode 100644
index 0000000..9da729a
--- /dev/null
+++ b/Weather-Cal/weather-cal.js
@@ -0,0 +1,315 @@
+// Variables used by Scriptable.
+// These must be at the very top of the file. Do not edit.
+// icon-color: deep-purple; icon-glyph: calendar;
+
+/*
+
+~
+
+Welcome to Weather Cal.
+Run this script to set up your widget.
+
+You can duplicate this script to create multiple widgets. Make sure to change the name of the script each time.
+
+Adjust the layout and other settings below.
+Happy scripting!
+
+~
+
+*/
+
+/*
+ * SETTINGS
+ * Adjust the settings of your widget.
+ * ===================================
+ */
+
+const settings = {
+ widget: {
+
+ // Set the locale code. Leave blank "" to match the device's locale.
+ locale: ""
+
+ // Set to imperial for Fahrenheit, or metric for Celsius
+ ,units: "imperial"
+
+ // The size of the widget preview in the app.
+ ,preview: "large"
+
+ // Set the padding around each item. Default is 5.
+ ,padding: 5
+
+ // Decide if icons should match the color of the text around them.
+ ,tintIcons: false
+ },
+
+/*
+ * LAYOUT
+ * Decide what items to show on the widget.
+ * ========================================
+ */
+
+// You always need to start with "row" and "column" items. Set the width of a column with parentheses, like "column(90)".
+
+// Adding left, right, or center will align everything after that. Add "space" for a flexible space, or "space(50)" for a specific height.
+
+// There are many possible items, including: date, greeting, events, reminders, current, future, forecast, battery, sunrise, text
+
+ layout: `
+
+ row
+ column
+ date
+ sunset
+ battery
+ space
+ events
+
+ column(90)
+ current
+ future
+
+ `,
+
+/*
+ * LOCALIZATION
+ * Change the language or wording of text displayed.
+ * =================================================
+ */
+
+ localization: {
+
+ // The text shown if you add a greeting item to the layout.
+ nightGreeting: "Good night."
+ ,morningGreeting: "Good morning."
+ ,afternoonGreeting: "Good afternoon."
+ ,eveningGreeting: "Good evening."
+
+ // The text shown if you add a future weather item to the layout, or tomorrow's events.
+ ,nextHourLabel: "Next hour"
+ ,tomorrowLabel: "Tomorrow"
+
+ // Shown when noEventBehavior is set to "message".
+ ,noEventMessage: "Enjoy the rest of your day."
+
+ // The text shown after the hours and minutes of an event duration.
+ ,durationMinute: "m"
+ ,durationHour: "h"
+
+ // Each {token} is replaced with the number from the data.
+ ,covid: "{cases} cases, {deaths} deaths, {recovered} recoveries"
+ },
+
+/*
+ * ITEMS
+ * Choose how each item is displayed.
+ * ==================================
+ */
+
+ // DATE
+ // ====
+ date: {
+
+ // If set to true, date will become smaller when events are displayed.
+ dynamicDateSize: true
+
+ // If the date is not dynamic, should it be large or small?
+ ,staticDateSize: "small"
+
+ // Determine the date format for each date type. See docs.scriptable.app/dateformatter
+ ,smallDateFormat: "EEEE, MMMM d"
+ ,largeDateLineOne: "EEEE,"
+ ,largeDateLineTwo: "MMMM d"
+ },
+
+ // EVENTS
+ // ======
+ events: {
+
+ // How many events to show.
+ numberOfEvents: 3
+
+ // Minutes after an event begins that it should still be shown.
+ ,minutesAfter: 5
+
+ // Show all-day events.
+ ,showAllDay: true
+
+ // The hour (in 24-hour time) to start showing tomorrow's events. 0 for always, 24 for never.
+ ,showTomorrow: 20
+
+ // Can be blank "" or set to "duration" or "time" to display how long an event is.
+ ,showEventLength: "duration"
+
+ // Set which calendars for which to show events. Empty [] means all calendars.
+ ,selectCalendars: []
+
+ // Leave blank "" for no color, or specify shape (circle, rectangle) and/or side (left, right).
+ ,showCalendarColor: "rectangle left"
+
+ // When no events remain, show a hard-coded "message", a "greeting", or "none".
+ ,noEventBehavior: "message"
+ },
+
+ // REMINDERS
+ // =========
+ reminders: {
+
+ // How many reminders to show. Use 0 for all.
+ numberOfReminders: 3
+
+ // Set to true for a relative due date ("in 3 hours") instead of absolute ("3:00 PM")
+ ,useRelativeDueDate: false
+
+ // Set to true to show reminders without a due date. Default is false.
+ ,showWithoutDueDate: false
+
+ // Show reminders that are overdue.
+ ,showOverdue: true
+
+ // Set to true to hide reminders due in future days.
+ ,todayOnly: false
+
+ // Set which calendars for which to show events. Empty [] means all calendars.
+ ,selectLists: []
+
+ // Leave blank "" for no color, or specify shape (circle, rectangle) and/or side (left, right).
+ ,showListColor: "rectangle left"
+ },
+
+ // SUNRISE
+ // =======
+ sunrise: {
+
+ // How many minutes before/after sunrise or sunset to show this element. 0 for always.
+ showWithin: 0
+
+ // Set to true to use separate "sunrise" and "sunset" elements. Default is false.
+ ,separateElements: false
+ },
+
+ // WEATHER
+ // =======
+ weather: {
+
+ // Show the location of the current weather.
+ showLocation: false
+
+ // Show the condition and temperature horizontally. Default is false.
+ ,horizontalCondition: false
+
+ // Show the text description of the current conditions.
+ ,showCondition: false
+
+ // Show today's high and low temperatures.
+ ,showHighLow: true
+
+ // Show the percent chance of rain in the future weather item.
+ ,showRain: true
+
+ // The hour (in 24-hour time) to switch to tomorrow's weather. 0 for always, 24 for never.
+ ,tomorrowShownAtHour: 20
+
+ // Set the amount of days to show in the forecast item.
+ ,showDays: 3
+
+ // Set the format for each day of the week in the forecast item.
+ ,showDaysFormat: "E"
+
+ // Set to true to show today's weather in the forecast item.
+ ,showToday: false
+ },
+
+ // COVID
+ // =====
+ covid: {
+
+ // Country for COVID information.
+ country: "China"
+
+ // URL to open when the COVID data is tapped.
+ ,url: "https://covid19.who.int"
+ },
+
+/*
+ * FONTS
+ * Change the size, color, and font of various text elements.
+ * ==========================================================
+ */
+
+ font: {
+
+ // Set the default font and color.
+ defaultText: { size: 14, color: "ffffff", font: "regular" },
+
+ // Any blank values will use the default.
+ smallDate: { size: 17, color: "", font: "semibold" },
+ largeDate1: { size: 30, color: "", font: "light" },
+ largeDate2: { size: 30, color: "", font: "light" },
+
+ greeting: { size: 30, color: "", font: "semibold" },
+ eventLabel: { size: 14, color: "", font: "semibold" },
+ eventTitle: { size: 14, color: "", font: "semibold" },
+ eventTime: { size: 14, color: "ffffffcc", font: "" },
+ noEvents: { size: 30, color: "", font: "semibold" },
+
+ largeTemp: { size: 34, color: "", font: "light" },
+ smallTemp: { size: 14, color: "", font: "" },
+ tinyTemp: { size: 12, color: "", font: "" },
+
+ customText: { size: 14, color: "", font: "" },
+
+ battery: { size: 14, color: "", font: "medium" },
+ sunrise: { size: 14, color: "", font: "medium" },
+ covid: { size: 14, color: "", font: "medium" },
+ },
+}
+
+/*
+ * CODE
+ * Be more careful editing this section.
+ * =====================================
+ */
+
+// Names of Weather Cal elements.
+const codeFilename = "weather-cal-code"
+const gitHubUrl = "https://raw.githubusercontent.com/KerwinKwong/Weather-Cal/main/Weather-Cal/weather-cal-code.js"
+
+// Determine if the user is using iCloud.
+let files = FileManager.local()
+const iCloudInUse = files.isFileStoredIniCloud(module.filename)
+
+// If so, use an iCloud file manager.
+files = iCloudInUse ? FileManager.iCloud() : files
+
+// Determine if the Weather Cal code exists and download if needed.
+const pathToCode = files.joinPath(files.documentsDirectory(), codeFilename + ".js")
+if (!files.fileExists(pathToCode)) {
+ const req = new Request(gitHubUrl)
+ const codeString = await req.loadString()
+ files.writeString(pathToCode, codeString)
+}
+
+// Import the code.
+if (iCloudInUse) { await files.downloadFileFromiCloud(pathToCode) }
+const code = importModule(codeFilename)
+
+// Run the initial setup or settings menu.
+if (config.runsInApp) {
+ const showPreview = await code.runSetup(Script.name(), iCloudInUse, codeFilename, gitHubUrl)
+ if (!showPreview) return
+}
+
+// Set up the widget.
+const widget = await code.createWidget(settings, Script.name(), iCloudInUse)
+Script.setWidget(widget)
+
+// If we're in app, display the preview.
+if (config.runsInApp) {
+ const preview = settings.widget.preview
+ if (preview == "small") { widget.presentSmall() }
+ else if (preview == "medium") { widget.presentMedium() }
+ else if (preview == "large") { widget.presentLarge() }
+}
+
+Script.complete()
diff --git a/Weather-Cal_Chinese.js b/Weather-Cal_Chinese.js
new file mode 100644
index 0000000..95f3b60
--- /dev/null
+++ b/Weather-Cal_Chinese.js
@@ -0,0 +1,1449 @@
+/*
+ * SETUP/设置
+ * Use this section to set up the widget.
+ * 使用此部分来设置小部件
+ * ======================================
+ */
+
+// To use weather, get a free API key at openweathermap.org/appid and paste it in between the quotation marks.
+// 要使用天气,请在http://openweathermap.org/appid 中获取免费的API密钥并将其粘贴在引号之间。
+const apiKey = ""
+
+// Set the locale code. Leave blank "" to match the device's locale. You can change the hard-coded text strings in the TEXT section below.
+// 设置语言环境代码。“”内保留空白以匹配设备的语言环境。您可以在下面的“文本”部分中更改硬编码的文本字符串。
+let locale = "zh_cn"
+
+// Set to true for fixed location, false to update location as you move around
+// 固定使用当前位置设置为true,更换了位置时设置为false以更新位置信息
+const lockLocation = true
+
+// The size of the widget preview in the app.
+// 小部件预览时的大小。large/medium/small
+const widgetPreview = "medium"
+
+// Set to true for an image background, false for no image.
+// 使用图片背景,设置为true;不使用图片,则设置为false(不使用自定义背景时则使用默认的渐变背景)
+const imageBackground = true
+
+// Set to true to reset the widget's background image.
+// 重置小部件的背景图像时设置为true以重新选择新的图像作为小部件背景
+const forceImageUpdate = false
+
+// Set the padding around each item. Default is 10.
+// 设置默认的边距(更多边距设置参考xxxStack.setpadding)
+const padding = 5
+
+/*
+ * LAYOUT/布局
+ * Decide what items to show on the widget.
+ * 此设置决定要在小部件上显示的项目。
+ * ========================================
+ */
+
+// You always need to start with "row," and "column," items, but you can now add as many as you want.
+// Adding left, right, or center will align everything after that. The default alignment is left.
+// You can add a flexible vertical space with "space," or a fixed-size space like this: "space(50)"
+// Align items to the top or bottom of columns by adding "space," before or after all items in the column.
+// There are many possible items, including: date, greeting, events, current, future, battery, sunrise, and text("Your text here")
+
+
+// Set the width of the column, or set to 0 for an automatic width.
+// 设置列的宽度,或者将其设置为0以表示自动宽度。
+
+// You can add items to the column:
+// 把你要显示在小部件上的项目添加到items:
+
+// date, greeting, events, current, future, battery, text("Your text here")
+// 日期,问候语,事件,当前天气,未来天气,电池,文本(“此处输入文字”)(默认只有这些项目,可自定义添加)
+
+// You can also add a left, center, or right to the list. Everything after it will be aligned that way.
+// 您还可以在列表中添加left(居左对齐),center(居中对齐)或right(居右对齐)。之后的该列下的所有内容都将以这种方式对齐。
+
+// Make sure to always put a comma after each item.
+// 注意格式,确保在每个项目后面加上逗号!!!
+
+/*----------------------------|
+| greeting | 95 |
+| date | current |
+| battery | sunrise |
+|-----------------------------|
+| events | future |
+|----------------------------*/
+
+const items = [
+
+ row,
+
+ column,
+ greeting,
+ date,
+ battery,
+
+ column(95),
+ right,
+ current,
+ sunrise,
+
+ row,
+
+ column,
+ left,
+ events,
+
+ column(95),
+ right,
+ future,
+
+]
+
+/*
+ * ITEM SETTINGS/项目设置
+ * Choose how each item is displayed.
+ * 选择每个项目的显示方式。
+ * ==================================
+ */
+
+// DATE/日期
+// ========
+const dateSettings = {
+
+ // If set to true, date will become smaller when events are displayed.
+ // 如果设置为true,则显示事件时日期将变小。
+ dynamicDateSize: false
+
+ // If the date is not dynamic, should it be large or small?
+ // 如果日期非dynamic的,它将以什么大小显示?large/small
+ ,staticDateSize: "large"
+
+ // Determine the date format for each date type. See docs.scriptable.app/dateformatter
+ // 设置每种日期类型的日期格式。参见docs.scriptable.app/dateformatter
+ ,smallDateFormat: "yyyy年MM月d日,E" //上面的设置为small时此项生效
+ ,largeDateLineOne: "yyyy年MM月d日" //上面的设置为large时此项生效并显示在第一行
+ ,largeDateLineTwo: "EEEE" //上面的设置为large时生效并显示在第二行
+}
+
+// EVENTS/事件
+// ==========
+const eventSettings = {
+
+ // How many events to show.
+ // 你想显示多少个事件在小部件上
+ numberOfEvents: 3
+
+ // Show all-day events.
+ // 是否显示全天的事件,不显示则设置为false
+ ,showAllDay: true
+
+ // Show tomorrow's events.
+ // 是否显示明天/后的事件,不显示则设置为false
+ ,showTomorrow: true
+
+ // Can be blank "" or set to "duration" or "time" to display how long an event is.
+ // “”内可以为空白,也可以设置为“ duration”或“ time”以显示事件的持续时间(则设置了之后会显示事件的时间XX小时,XX分钟)
+ ,showEventLength: "duration"
+
+ // Set which calendars for which to show events. Empty [] means all calendars.
+ // 设置要显示事件的日历。空[]表示所有日历。如果你日历上有订阅多个日历,则可选此项,或留空则显示全部日历事件
+ ,selectCalendars: []
+
+ // Leave blank "" for no color, or specify shape (circle, rectangle) and/or side (left, right).
+ // “”不设置为无颜色,或可指定显示的形状(圆形,矩形)或侧面(左侧,右侧)
+ ,showCalendarColor: "rectangle left"
+
+ // When no events remain, show a hard-coded "message", a "greeting", or "none".
+ // 如果没有事件,显示硬编码的“消息”,“问候”或“无”。
+ ,noEventBehavior: "message"
+}
+
+// SUNRISE/日出日出
+// ==============
+const sunriseSettings = {
+
+ // How many minutes before/after sunrise or sunset to show this element. 0 for always.
+ // 日出或日落前后多少分钟才能显示此项。如果想始终显示则设置为 0
+ showWithin: 0
+}
+
+// WEATHER/天气
+// ===========
+const weatherSettings = {
+
+ // Set to imperial for Fahrenheit, or metric for Celsius
+ // 设置温度单位,imperial为华氏度,metric为摄氏度
+ units: "metric"
+
+ // Show the location of the current weather.
+ // true显示当前天气的位置,false则不显示(注意开启后会占用顶部位置空间)
+ ,showLocation: false
+
+ // Show the text description of the current conditions.
+ // true显示当前天气的文字说明,false则不显示(注意,这个API并不支持中文)
+ ,showCondition: false
+
+ // Show today's high and low temperatures.
+ // true显示今天的最高/低温度,false则不显示
+ ,showHighLow: true
+
+ // Set the hour (in 24-hour time) to switch to tomorrow's weather. Set to 24 to never show it.
+ // 设置多少小时(以24小时制)以监视明天的天气。设置为24永不显示它。(则该数值是你想在哪个时间开始显示明天的天气,如设置为20,则当天晚上8点才显示明天的天气,晚上8点前都将显示每个时段的下一个小时的天气)
+ ,tomorrowShownAtHour: 20
+}
+
+/*
+ * TEXT/文本
+ * Change the language and formatting of text displayed.
+ * 更改所显示文本的语言和格式。
+ * =====================================================
+ */
+
+// You can change the language or wording of any text in the widget.
+// 您可以更改窗口小部件中任何文本的语言或措辞。
+const localizedText = {
+
+ // The text shown if you add a greeting item to the layout.
+ // 如果在布局中添加问候语,则显示此处的文本。
+ nightGreeting: "该睡觉了哟!"
+ ,morningGreeting: "早上好呀!"
+ ,noonGreeting: "中午好呀!"
+ ,afternoonGreeting: "下午好呀!"
+ ,eveningGreeting: "晚上好呀!"
+
+ // The text shown if you add a future weather item to the layout, or tomorrow's events.
+ // 如果将未来的天气项目添加到布局或明天的事件中,则显示此处的文本。
+ ,nextHourLabel: "下一小时"
+ ,tomorrowLabel: "明天"
+
+ // Shown when noEventBehavior is set to "message".
+ // 当没有事件时则显示此处的“ message”
+ ,noEventMessage: "Get out of here to study."
+
+ // The text shown after the hours and minutes of an event duration.
+ // 事件持续时间显示的文本(小时/分钟)。
+ ,durationMinute: "分"
+ ,durationHour: "小时"
+
+}
+
+// Set the font, size, and color of various text elements. Use iosfonts.com to find fonts to use. If you want to use the default iOS font, set the font name to one of the following: ultralight, light, regular, medium, semibold, bold, heavy, black, or italic.
+// 设置各种文本元素的字体,大小和颜色。使用http://iosfonts.com 查找要使用的字体。如果要使用默认的iOS字体,请将字体名称设置为以下之一:超轻,轻,常规,中,半粗体,粗体,粗体,黑色或斜体。
+const textFormat = {
+
+ // Set the default font and color.
+ // 设置默认的字体和颜色。
+ defaultText: { size: 14, color: "ffffff", font: "regular" },
+
+ // Any blank values will use the default.
+ // 以下的空白值都将使用上面的默认值。
+ smallDate: { size: 16, color: "", font: "semibold" },
+ largeDate1: { size: 16, color: "", font: "medium" },
+ largeDate2: { size: 16, color: "", font: "medium" },
+
+ greeting: { size: 26, color: "", font: "semibold" },
+ eventLabel: { size: 14, color: "", font: "semibold" },
+ eventTitle: { size: 14, color: "", font: "semibold" },
+ eventTime: { size: 14, color: "ffffffcc", font: "" },
+ noEvents: { size: 16, color: "", font: "semibold" },
+
+ largeTemp: { size: 16, color: "", font: "semibold" },
+ smallTemp: { size: 10, color: "", font: "" },
+ tinyTemp: { size: 10, color: "", font: "" },
+
+ customText: { size: 14, color: "", font: "" },
+
+ battery: { size: 16, color: "", font: "medium" },
+ sunrise: { size: 12, color: "", font: "medium" },
+}
+
+/*
+ * WIDGET CODE/小部件代码
+ * Be more careful editing this section.
+ * 在编辑此部分时要格外小心(所有小部件的源数据将从此处调用)
+ * ===============================================
+ */
+
+// Make sure we have a locale value.
+// 语言环境值,对应上面设置的语言,不设置将使用设备的语言
+if (locale == "" || locale == null) { locale = Device.locale() }
+
+// Declare the data variables.
+// 声明数据变量
+var eventData, locationData, sunData, weatherData
+
+// Create global constants.
+// 创建全局常量
+const currentDate = new Date()
+const files = FileManager.local()
+
+/*
+ * COLUMNS
+ * =======
+ */
+
+// Set up the widget with padding.
+// 使用padding来设定widget
+const widget = new ListWidget()
+const horizontalPad = padding < 10 ? 10 - padding : 10
+const verticalPad = padding < 15 ? 15 - padding : 15
+widget.setPadding(horizontalPad, verticalPad, horizontalPad, verticalPad)
+widget.spacing = 0
+
+// Set up the global variables.
+// 设置全局变量
+var currentRow = {}
+var currentColumn = {}
+
+// Set up the initial alignment.
+// 设置初始对齐方式
+var currentAlignment = alignLeft
+
+// Set up our items.
+// 设置items
+for (item of items) { await item(currentColumn) }
+/*
+ * BACKGROUND DISPLAY/背景显示
+ * =========================
+ */
+
+// If it's an image background, display it.
+// 如果它是图像背景,则显示它。
+if (imageBackground) {
+
+ // Determine if our image exists and when it was saved.
+ // 判断图像是否存在以及何时保存
+ const path = files.joinPath(files.documentsDirectory(), "Weather-Cal-image")
+ const exists = files.fileExists(path)
+
+ // If it exists and an update isn't forced, use the cache.
+ // 如果已有背景图像并且不打开每次运行时重新选择图像时使用缓存已有的背景图像。
+ if (exists && (config.runsInWidget || !forceImageUpdate)) {
+ widget.backgroundImage = files.readImage(path)
+
+ // If it's missing when running in the widget, use a gray background.
+ // 如果在小部件中运行时缺少这个背景,将使用灰色背景。
+ } else if (!exists && config.runsInWidget) {
+ widget.backgroundColor = Color.gray()
+
+ // But if we're running in app, prompt the user for the image.
+ // 但是,如果在应用程序中运行,则提示选择图像
+ } else {
+ const img = await Photos.fromLibrary()
+ widget.backgroundImage = img
+ files.writeImage(path, img)
+ }
+
+// If it's not an image background, show the gradient.
+// 如果不是图片背景,显示渐变
+} else {
+ let gradient = new LinearGradient()
+ let gradientSettings = await setupGradient()
+
+ gradient.colors = gradientSettings.color()
+ gradient.locations = gradientSettings.position()
+
+ widget.backgroundGradient = gradient
+}
+
+// Finish the widget and show a preview.
+// 完成小部件并显示预览
+Script.setWidget(widget)
+if (widgetPreview == "small") { widget.presentSmall() }
+else if (widgetPreview == "medium") { widget.presentMedium() }
+else if (widgetPreview == "large") { widget.presentLarge() }
+Script.complete()
+
+/*
+ * LAYOUT FUNCTIONS/布局函数
+ * These functions manage spacing and alignment.
+ * 这些函数管理间距和对齐方式
+ * =============================================
+ */
+
+// Makes a new row on the widget.
+// 在窗口小部件上创建新行
+function row(input = null) {
+
+ function makeRow() {
+ currentRow = widget.addStack()
+ currentRow.layoutHorizontally()
+ currentRow.setPadding(0, 0, 0, 0)
+ currentColumn.spacing = 0
+
+ // If input was given, make a column of that size.
+ // 如果输入了参数则使用参数的尺寸大小来创建
+ if (input > 0) { currentRow.size = new Size(0,input) }
+ }
+
+ // If there's no input or it's a number, it's being called in the layout declaration.
+ if (!input || typeof input == "number") { return makeRow }
+
+ // Otherwise, it's being called in the generator.
+ else { makeRow() }
+}
+
+// Makes a new column on the widget.
+function column(input = null) {
+
+ function makeColumn() {
+ currentColumn = currentRow.addStack()
+ currentColumn.layoutVertically()
+ currentColumn.setPadding(0, 0, 0, 0)
+ currentColumn.spacing = 0
+
+ // If input was given, make a column of that size.
+ if (input > 0) { currentColumn.size = new Size(input,0) }
+ }
+
+ // If there's no input or it's a number, it's being called in the layout declaration.
+ if (!input || typeof input == "number") { return makeColumn }
+
+ // Otherwise, it's being called in the generator.
+ else { makeColumn() }
+}
+
+// Create an aligned stack to add content to.
+// 创建对齐的Stack以向其添加内容
+function align(column) {
+
+ // Add the containing stack to the column.
+ // 将包含Stack的内容添加到该列中
+ let alignmentStack = column.addStack()
+ alignmentStack.layoutHorizontally()
+
+ // Get the correct stack from the alignment function.
+ // 从对齐函数获取正确的Stack
+ let returnStack = currentAlignment(alignmentStack)
+ returnStack.layoutVertically()
+ return returnStack
+}
+
+// Create a right-aligned stack.
+// 创建一个居右对齐的Stack
+function alignRight(alignmentStack) {
+ alignmentStack.addSpacer()
+ let returnStack = alignmentStack.addStack()
+ return returnStack
+}
+
+// Create a left-aligned stack.
+// 创建一个居左对齐的Stack
+function alignLeft(alignmentStack) {
+ let returnStack = alignmentStack.addStack()
+ alignmentStack.addSpacer()
+ return returnStack
+}
+
+// Create a center-aligned stack.
+// 创建一个居中对齐的Stack
+function alignCenter(alignmentStack) {
+ alignmentStack.addSpacer()
+ let returnStack = alignmentStack.addStack()
+ alignmentStack.addSpacer()
+ return returnStack
+}
+
+// This function adds a space, with an optional amount.
+// 此函数添加一个间距,并带有一个可选的数值
+function space(input = null) {
+
+ // This function adds a spacer with the input width.
+ // 此函数在输入宽度处添加一个间距
+ function spacer(column) {
+
+ // If the input is null or zero, add a flexible spacer.
+ // 如果输入为null或零时,添加一个间距
+ if (!input || input == 0) { column.addSpacer() }
+
+ // Otherwise, add a space with the specified length.
+ // 否则,添加具有指定长度的间距
+ else { column.addSpacer(input) }
+ }
+
+ // If there's no input or it's a number, it's being called in the column declaration.
+ // 如果没有输入或是数字,则在列声明中调用它
+ if (!input || typeof input == "number") { return spacer }
+
+ // Otherwise, it's being called in the column generator.
+ // 否则,将在列生成器中调用它
+ else { input.addSpacer() }
+}
+
+// Change the current alignment to right.
+// 将当前对齐方式更改为居右
+function right(x) { currentAlignment = alignRight }
+
+// Change the current alignment to left.
+// 将当前对齐方式更改为居左
+function left(x) { currentAlignment = alignLeft }
+
+// Change the current alignment to center.
+// 将当前对齐方式更改为居中
+function center(x) { currentAlignment = alignCenter }
+
+/*
+ * SETUP FUNCTIONS
+ * 设定函数
+ * These functions prepare data needed for items.
+ * 以下这些函数是小部件所需的数据
+ * ==============================================
+ */
+
+// Set up the eventData object.
+// 设定事件日期的对象
+async function setupEvents() {
+
+ eventData = {}
+ const calendars = eventSettings.selectCalendars
+ const numberOfEvents = eventSettings.numberOfEvents
+
+ // Function to determine if an event should be shown.
+ // 判断是否应该显示事件的函数。
+ function shouldShowEvent(event) {
+
+ // If events are filtered and the calendar isn't in the selected calendars, return false.
+ // 如果事件被过滤,并且日历不在所选日历中,则返回false
+ if (calendars.length && !calendars.includes(event.calendar.title)) { return false }
+
+ // Hack to remove canceled Office 365 events.
+ // 删除已取消的Office 365事件
+ if (event.title.startsWith("Canceled:")) { return false }
+
+ // If it's an all-day event, only show if the setting is active.
+ // 如果是全天事件,则仅在设置处于active状态时显示
+ if (event.isAllDay) { return eventSettings.showAllDay }
+
+ // Otherwise, return the event if it's in the future.
+ // 否则,会返回处于未来的事件
+ return (event.startDate.getTime() > currentDate.getTime())
+ }
+
+ // Determine which events to show, and how many.
+ // 判断要显示的事件以及数量
+ const todayEvents = await CalendarEvent.today([])
+ let shownEvents = 0
+ let futureEvents = []
+
+ for (const event of todayEvents) {
+ if (shownEvents == numberOfEvents) { break }
+ if (shouldShowEvent(event)) {
+ futureEvents.push(event)
+ shownEvents++
+ }
+ }
+
+ // If there's room and we need to, show tomorrow's events.
+ // 如果需要的话,显示明天的事件
+ let multipleTomorrowEvents = false
+ if (eventSettings.showTomorrow && shownEvents < numberOfEvents) {
+
+ const tomorrowEvents = await CalendarEvent.tomorrow([])
+ for (const event of tomorrowEvents) {
+ if (shownEvents == numberOfEvents) { break }
+ if (shouldShowEvent(event)) {
+
+ // Add the tomorrow label prior to the first tomorrow event.
+ // 在第一个明天事件之前添加“明天标签”
+ if (!multipleTomorrowEvents) {
+
+ // The tomorrow label is pretending to be an event.
+ futureEvents.push({ title: localizedText.tomorrowLabel.toUpperCase(), isLabel: true })
+ multipleTomorrowEvents = true
+ }
+
+ // Show the tomorrow event and increment the counter.
+ // 显示明天的事件并增加计数器
+ futureEvents.push(event)
+ shownEvents++
+ }
+ }
+ }
+
+ // Store the future events, and whether or not any events are displayed.
+ // 存储未来的事件,以及是否显示全部事件
+ eventData.futureEvents = futureEvents
+ eventData.eventsAreVisible = (futureEvents.length > 0) && (eventSettings.numberOfEvents > 0)
+}
+
+// Set up the gradient for the widget background.
+// 设置小部件渐变背景
+async function setupGradient() {
+
+ // Requirements: sunrise
+ if (!sunData) { await setupSunrise() }
+
+ let gradient = {
+ dawn: {
+ color() { return [new Color("142C52"), new Color("1B416F"), new Color("62668B")] },
+ position() { return [0, 0.5, 1] },
+ },
+
+ sunrise: {
+ color() { return [new Color("274875"), new Color("766f8d"), new Color("f0b35e")] },
+ position() { return [0, 0.8, 1.5] },
+ },
+
+ midday: {
+ color() { return [new Color("3a8cc1"), new Color("90c0df")] },
+ position() { return [0, 1] },
+ },
+
+ noon: {
+ color() { return [new Color("b2d0e1"), new Color("80B5DB"), new Color("3a8cc1")] },
+ position() { return [-0.2, 0.2, 1.5] },
+ },
+
+ sunset: {
+ color() { return [new Color("32327A"), new Color("662E55"), new Color("7C2F43")] },
+ position() { return [0.1, 0.9, 1.2] },
+ },
+
+ twilight: {
+ color() { return [new Color("021033"), new Color("16296b"), new Color("414791")] },
+ position() { return [0, 0.5, 1] },
+ },
+
+ night: {
+ color() { return [new Color("16296b"), new Color("021033"), new Color("021033"), new Color("113245")] },
+ position() { return [-0.5, 0.2, 0.5, 1] },
+ },
+ }
+
+ const sunrise = sunData.sunrise
+ const sunset = sunData.sunset
+
+ // Use sunrise or sunset if we're within 30min of it.
+ // 如果距离30分钟以内,使用日出或日落
+ if (closeTo(sunrise)<=15) { return gradient.sunrise }
+ if (closeTo(sunset)<=15) { return gradient.sunset }
+
+ // In the 30min before/after, use dawn/twilight.
+ // 如果距离30分钟前/后,使用黎明/暮光
+ if (closeTo(sunrise)<=45 && utcTime < sunrise) { return gradient.dawn }
+ if (closeTo(sunset)<=45 && utcTime > sunset) { return gradient.twilight }
+
+ // Otherwise, if it's night, return night.
+ // 否则,如果是夜晚,则使用夜晚
+ if (isNight(currentDate)) { return gradient.night }
+
+ // If it's around noon, the sun is high in the sky.
+ // 如果在正午时分,太阳在天空中很高
+ if (currentDate.getHours() == 12) { return gradient.noon }
+
+ // Otherwise, return the "typical" theme.
+ // 否则,返回“typical”主题。
+ return gradient.midday
+}
+
+// Set up the locationData object.
+// 设置位置数据对象
+async function setupLocation() {
+
+ locationData = {}
+ const locationPath = files.joinPath(files.documentsDirectory(), "Weather-Cal-loc")
+
+ // If our location is unlocked or cache doesn't exist, ask iOS for location.
+ // 如果位置已解锁定或不存在缓存,询问iOS
+ var readLocationFromFile = false
+ if (!lockLocation || !files.fileExists(locationPath)) {
+ try {
+ const location = await Location.current()
+ const geocode = await Location.reverseGeocode(location.latitude, location.longitude, locale)
+ locationData.latitude = location.latitude
+ locationData.longitude = location.longitude
+ locationData.locality = geocode[0].locality
+ files.writeString(locationPath, location.latitude + "|" + location.longitude + "|" + locationData.locality)
+
+ } catch(e) {
+ // If we fail in unlocked mode, read it from the cache.
+ if (!lockLocation) { readLocationFromFile = true }
+
+ // We can't recover if we fail on first run in locked mode.
+ else { return }
+ }
+ }
+
+ // If our location is locked or we need to read from file, do it.
+ // 如果位置信息被锁定或需要从文件中读取,执行此操作
+ if (lockLocation || readLocationFromFile) {
+ const locationStr = files.readString(locationPath).split("|")
+ locationData.latitude = locationStr[0]
+ locationData.longitude = locationStr[1]
+ locationData.locality = locationStr[2]
+ }
+}
+
+// Set up the sunData object.
+// 设置日落/日出数据对象
+async function setupSunrise() {
+
+ // Requirements: location
+ if (!locationData) { await setupLocation() }
+
+ // Set up the sunrise/sunset cache.
+ // 设置日出/日落缓存
+ const sunCachePath = files.joinPath(files.documentsDirectory(), "Weather-Cal-sun")
+ const sunCacheExists = files.fileExists(sunCachePath)
+ const sunCacheDate = sunCacheExists ? files.modificationDate(sunCachePath) : 0
+ let sunDataRaw, afterSunset
+
+ // If cache exists and was created today, use cached data.
+ // 如果缓存存在并且是今天创建的,使用缓存的数据
+ if (sunCacheExists && sameDay(currentDate, sunCacheDate)) {
+ const sunCache = files.readString(sunCachePath)
+ sunDataRaw = JSON.parse(sunCache)
+
+ // Determine if it's after sunset.
+ // 判断是否在日落之后
+ const sunsetDate = new Date(sunDataRaw.results.sunset)
+ afterSunset = currentDate.getTime() - sunsetDate.getTime() > (45 * 60 * 1000)
+ }
+
+ // If we don't have data yet, or we need to get tomorrow's data, get it from the server.
+ // 如果还没有数据,或者需要获取明天的数据,从服务器获取。
+ if (!sunDataRaw || afterSunset) {
+ let tomorrowDate = new Date()
+ tomorrowDate.setDate(currentDate.getDate() + 1)
+ const dateToUse = afterSunset ? tomorrowDate : currentDate
+ const sunReq = "https://api.sunrise-sunset.org/json?lat=" + locationData.latitude + "&lng=" + locationData.longitude + "&formatted=0&date=" + dateToUse.getFullYear() + "-" + (dateToUse.getMonth()+1) + "-" + dateToUse.getDate()
+ sunDataRaw = await new Request(sunReq).loadJSON()
+ files.writeString(sunCachePath, JSON.stringify(sunDataRaw))
+ }
+
+ // Store the timing values.
+ // 存储计时值
+ sunData = {}
+ sunData.sunrise = new Date(sunDataRaw.results.sunrise).getTime()
+ sunData.sunset = new Date(sunDataRaw.results.sunset).getTime()
+}
+
+// Set up the weatherData object.
+// 设置天气数据对象
+async function setupWeather() {
+
+ // Requirements: location
+ if (!locationData) { await setupLocation() }
+
+ // Set up the cache.
+ // 设定缓存
+ const cachePath = files.joinPath(files.documentsDirectory(), "Weather-Cal-cache")
+ const cacheExists = files.fileExists(cachePath)
+ const cacheDate = cacheExists ? files.modificationDate(cachePath) : 0
+ var weatherDataRaw
+
+ // If cache exists and it's been less than 60 seconds since last request, use cached data.
+ // 如果存在缓存,并且距离上次请求少于60秒,使用缓存的数据
+ if (cacheExists && (currentDate.getTime() - cacheDate.getTime()) < 60000) {
+ const cache = files.readString(cachePath)
+ weatherDataRaw = JSON.parse(cache)
+
+ // Otherwise, use the API to get new weather data.
+ // 否则,使用API获取新的天气数据
+ } else {
+ const weatherReq = "https://api.openweathermap.org/data/2.5/onecall?lat=" + locationData.latitude + "&lon=" + locationData.longitude + "&exclude=minutely,alerts&units=" + weatherSettings.units + "&lang=" + locale + "&appid=" + apiKey
+ weatherDataRaw = await new Request(weatherReq).loadJSON()
+ files.writeString(cachePath, JSON.stringify(weatherDataRaw))
+ }
+
+ // Store the weather values.
+ // 储存天气数据值
+ weatherData = {}
+ weatherData.currentTemp = weatherDataRaw.current.temp
+ weatherData.currentCondition = weatherDataRaw.current.weather[0].id
+ //weatherData.currentDescription = weatherDataRaw.current.weather[0].main //英文天气描述
+ weatherData.currentDescription = weatherDataRaw.current.weather[0].description //中文天气描述
+ weatherData.todayHigh = weatherDataRaw.daily[0].temp.max
+ weatherData.todayLow = weatherDataRaw.daily[0].temp.min
+
+ weatherData.nextHourTemp = weatherDataRaw.hourly[1].temp
+ weatherData.nextHourCondition = weatherDataRaw.hourly[1].weather[0].id
+
+ weatherData.tomorrowHigh = weatherDataRaw.daily[1].temp.max
+ weatherData.tomorrowLow = weatherDataRaw.daily[1].temp.min
+ weatherData.tomorrowCondition = weatherDataRaw.daily[1].weather[0].id
+}
+
+/*
+ * WIDGET ITEMS/小部件项目
+ * These functions display items on the widget.
+ * 以下这些函数将是显示在小部件上的项目
+ * ============================================
+ */
+
+// Display the date on the widget.
+// 在小部件上显示日期
+async function date(column) {
+
+ // Requirements: events (if dynamicDateSize is enabled)
+ if (!eventData && dateSettings.dynamicDateSize) { await setupEvents() }
+
+ // Set up the date formatter and set its locale.
+ // 设置日期格式并设置其语言环境
+ let df = new DateFormatter()
+ df.locale = locale
+
+ // Show small if it's hard coded, or if it's dynamic and events are visible.
+ // 如果是有硬编码文本或有事件显示,则显示为小日期样式
+ if (dateSettings.staticDateSize == "small" || (dateSettings.dynamicDateSize && eventData.eventsAreVisible)) {
+ let dateStack = align(column)
+ dateStack.setPadding(padding, padding, padding, padding)
+
+ df.dateFormat = dateSettings.smallDateFormat
+ let dateText = provideText(df.string(currentDate), dateStack, textFormat.smallDate)
+
+ // Otherwise, show the large date.
+ // 否则,显示大日期样式
+ } else {
+ let dateOneStack = align(column)
+ df.dateFormat = dateSettings.largeDateLineOne
+ let dateOne = provideText(df.string(currentDate), dateOneStack, textFormat.largeDate1)
+ dateOneStack.setPadding(padding/2, padding, 0, padding)
+
+ let dateTwoStack = align(column)
+ df.dateFormat = dateSettings.largeDateLineTwo
+ let dateTwo = provideText(df.string(currentDate), dateTwoStack, textFormat.largeDate2)
+ dateTwoStack.setPadding(0, padding, padding, padding*2) //日期的间距设置,当你在日期设置中选择了显示“large”日期时,调整这项以更改边距,依次是逆时针顺序上、左、下、右
+ }
+}
+
+// Display a time-based greeting on the widget.
+// 在小部件上显示每个时间段的问候语
+async function greeting(column) {
+
+ // This function makes a greeting based on the time of day.
+ // 此函数可以调整一天中不同时间段的问候语显示
+ function makeGreeting() {
+ const hour = currentDate.getHours()
+ if (hour < 5 ) { return localizedText.nightGreeting }
+ if (hour < 11) { return localizedText.morningGreeting }
+ if (hour-12 < 1 ) { return localizedText.noonGreeting }
+ if (hour-12 < 6 ) { return localizedText.afternoonGreeting }
+ if (hour-12 < 11) { return localizedText.eveningGreeting }
+ return localizedText.nightGreeting
+ }
+
+ // Set up the greeting.
+ // 设置问候语Stack和边距
+ let greetingStack = align(column)
+ let greeting = provideText(makeGreeting(), greetingStack, textFormat.greeting)
+ greetingStack.setPadding(padding, padding, padding, padding) //问候语的间距设置,调整这项以更改边距,依次是逆时针顺序上、左、下、右
+}
+
+// Display events on the widget.
+// 在小部件上显示事件
+async function events(column) {
+
+ // Requirements: events
+ if (!eventData) { await setupEvents() }
+
+ // If no events are visible, figure out what to do.
+ // 判断没有事件时该显示什么
+ if (!eventData.eventsAreVisible) {
+ const display = eventSettings.noEventBehavior
+
+ // If it's a greeting, let the greeting function handle it.
+ // 如果是问候语,将由问候语函数处理它
+ if (display == "greeting") { return await greeting(column) }
+
+ // If it's a message, get the localized text.
+ // 如果是消息,将获取本地化的文本
+ if (display == "message" && localizedText.noEventMessage.length) {
+ const messageStack = align(column)
+ messageStack.setPadding(padding, padding, padding, padding) //自定义本文的间距设置,如果你选择了没有事件是显示这个内容,调整这项以更改边距,依次是逆时针顺序上、左、下、右
+ provideText(localizedText.noEventMessage, messageStack, textFormat.noEvents)
+ }
+
+ // Whether or not we displayed something, return here.
+ return
+ }
+
+ // Set up the event stack.
+ // 设置事件Stack和间距
+ let eventStack = column.addStack()
+ eventStack.layoutVertically()
+ const todaySeconds = Math.floor(currentDate.getTime() / 1000) - 978307200
+ eventStack.url = 'calshow:' + todaySeconds
+
+ // If there are no events and we have a message, show it and return.
+ if (!eventData.eventsAreVisible && localizedText.noEventMessage.length) {
+ let message = provideText(localizedText.noEventMessage, eventStack, textFormat.noEvents)
+ eventStack.setPadding(padding, padding, padding, padding) //事件的间距设置,调整这项以更改边距,依次是逆时针顺序上、左、下、右
+ return
+ }
+
+ // If we're not showing the message, don't pad the event stack.
+ // 如果没有事件显示将不会显示这个事件Stack
+ eventStack.setPadding(0, 0, 0, 0) //当没有事件时改为这个边距,全是0代表不限制这个Stack了,被自定义文本替代(这个默尔开启了,可开启/关闭)
+
+ // Add each event to the stack.
+ // 将每个事件添加到Stack中
+ var currentStack = eventStack
+ const futureEvents = eventData.futureEvents
+ for (let i = 0; i < futureEvents.length; i++) {
+
+ const event = futureEvents[i]
+ const bottomPadding = (padding-10 < 0) ? 0 : padding-10
+
+ // If it's the tomorrow label, change to the tomorrow stack.
+ // 如果是明天的lable,则改用明天的Stack
+ if (event.isLabel) {
+ let tomorrowStack = column.addStack()
+ tomorrowStack.layoutVertically()
+ const tomorrowSeconds = Math.floor(currentDate.getTime() / 1000) - 978220800
+ tomorrowStack.url = 'calshow:' + tomorrowSeconds
+ currentStack = tomorrowStack
+
+ // Mimic the formatting of an event title, mostly.
+ // 事件标题的格式
+ const eventLabelStack = align(currentStack)
+ const eventLabel = provideText(event.title, eventLabelStack, textFormat.eventLabel)
+ eventLabelStack.setPadding(padding, padding, padding, padding)
+ continue
+ }
+
+ const titleStack = align(currentStack)
+ titleStack.layoutHorizontally()
+ const showCalendarColor = eventSettings.showCalendarColor
+ const colorShape = showCalendarColor.includes("circle") ? "circle" : "rectangle"
+
+ // If we're showing a color, and it's not shown on the right, add it to the left.
+ if (showCalendarColor.length && !showCalendarColor.includes("right")) {
+ let colorItemText = provideTextSymbol(colorShape) + " "
+ let colorItem = provideText(colorItemText, titleStack, textFormat.eventTitle)
+ colorItem.textColor = event.calendar.color
+ }
+
+ const title = provideText(event.title.trim(), titleStack, textFormat.eventTitle)
+ titleStack.setPadding(padding, padding, event.isAllDay ? padding : padding/5, padding)
+
+ // If we're showing a color on the right, show it.
+ if (showCalendarColor.length && showCalendarColor.includes("right")) {
+ let colorItemText = " " + provideTextSymbol(colorShape)
+ let colorItem = provideText(colorItemText, titleStack, textFormat.eventTitle)
+ colorItem.textColor = event.calendar.color
+ }
+
+ // If there are too many events, limit the line height.
+ // //如果事件太多,限制行高
+ if (futureEvents.length >= 3) { title.lineLimit = 1 }
+
+ // If it's an all-day event, we don't need a time.
+ // 如果是全天的的事件,则不显示时间
+ if (event.isAllDay) { continue }
+
+ // Format the time information.
+ // 格式化时间信息
+ let timeText = formatTime(event.startDate)
+
+ // If we show the length as time, add an en dash and the time.
+ // 如果显示为时间,添加一个破折号“-”
+ if (eventSettings.showEventLength == "time") {
+ timeText += "–" + formatTime(event.endDate)
+
+ // If we should it as a duration, add the minutes.
+ } else if (eventSettings.showEventLength == "duration") {
+ const duration = (event.endDate.getTime() - event.startDate.getTime()) / (1000*60)
+ const hours = Math.floor(duration/60)
+ const minutes = Math.floor(duration % 60)
+ const hourText = hours>0 ? hours + localizedText.durationHour : ""
+ const minuteText = minutes>0 ? minutes + localizedText.durationMinute : ""
+ const showSpace = hourText.length && minuteText.length
+ timeText += " \u2022 " + hourText + (showSpace ? " " : "") + minuteText
+ }
+
+ const timeStack = align(currentStack)
+ const time = provideText(timeText, timeStack, textFormat.eventTime)
+ timeStack.setPadding(0, padding, padding, padding)
+ }
+}
+
+// Display the current weather.
+// 显示当前天气在小部件上
+async function current(column) {
+
+ // Requirements: weather and sunrise
+ if (!weatherData) { await setupWeather() }
+ if (!sunData) { await setupSunrise() }
+
+ // Set up the current weather stack.
+ // 设置当前天气的Stack
+ let currentWeatherStack = column.addStack()
+ currentWeatherStack.layoutVertically()
+ currentWeatherStack.setPadding(0, 0, 0, 0) //当前天气的间距设置,调整这项以更改边距,依次是逆时针顺序上、左、下、右
+ currentWeatherStack.url = "https://weather.com/weather/today/l/" + locationData.latitude + "," + locationData.longitude
+
+ // If we're showing the location, add it.
+ // 如果要显示位置,添加这个
+ if (weatherSettings.showLocation) {
+ let locationTextStack = align(currentWeatherStack)
+ let locationText = provideText(locationData.locality, locationTextStack, textFormat.smallTemp)
+ locationTextStack.setPadding(padding, padding, padding, padding) //位置名称的间距设置,调整这项以更改边距,依次是逆时针顺序上、左、下、右(这个默认关闭,可到天气设置处启用)
+ }
+
+ // Show the current condition symbol.
+ // 显示当前天气的图标
+ let mainConditionStack = align(currentWeatherStack)
+ let mainCondition = mainConditionStack.addImage(provideConditionSymbol(weatherData.currentCondition,isNight(currentDate)))
+ mainCondition.imageSize = new Size(22,22)
+ mainConditionStack.setPadding(weatherSettings.showLocation ? 0 : padding, padding, 0, padding) //当前天气图标的间距设置,调整这项以更改边距,依次是逆时针顺序上、左、下、右
+
+ // If we're showing the description, add it.
+ // 如果要显示天气描述,添加这个
+ if (weatherSettings.showCondition) {
+ let conditionTextStack = align(currentWeatherStack)
+ let conditionText = provideText(weatherData.currentDescription, conditionTextStack, textFormat.smallTemp)
+ conditionTextStack.setPadding(padding, padding, 0, padding) //天气描述的间距设置,调整这项以更改边距,依次是逆时针顺序上、左、下、右
+ }
+
+ // Show the current temperature.
+ // 显示当前温度
+ const tempStack = align(currentWeatherStack)
+ tempStack.setPadding(0, padding, 0, padding) //当前温度的间距设置,调整这项以更改边距,依次是逆时针顺序上、左、下、右
+ const tempText = Math.round(weatherData.currentTemp) + "°"
+ const temp = provideText(tempText, tempStack, textFormat.largeTemp)
+
+ // If we're not showing the high and low, end it here.
+ if (!weatherSettings.showHighLow) { return }
+
+ // Show the temp bar and high/low values.
+ // 显示温度条和高/低值
+ let tempBarStack = align(currentWeatherStack)
+ tempBarStack.layoutVertically()
+ tempBarStack.setPadding(0, padding, padding, padding) //高/低温度的间距设置,调整这项以更改边距,依次是逆时针顺序上、左、下、右
+
+ let tempBar = drawTempBar()
+ let tempBarImage = tempBarStack.addImage(tempBar)
+ tempBarImage.size = new Size(50,0)
+
+ tempBarStack.addSpacer(1)
+
+ let highLowStack = tempBarStack.addStack()
+ highLowStack.layoutHorizontally()
+
+ const mainLowText = Math.round(weatherData.todayLow).toString()
+ const mainLow = provideText(mainLowText, highLowStack, textFormat.tinyTemp)
+ highLowStack.addSpacer()
+ const mainHighText = Math.round(weatherData.todayHigh).toString()
+ const mainHigh = provideText(mainHighText, highLowStack, textFormat.tinyTemp)
+
+ tempBarStack.size = new Size(60,30)
+}
+
+// Display upcoming weather.
+//显示未来的天气
+async function future(column) {
+
+ // Requirements: weather and sunrise
+ if (!weatherData) { await setupWeather() }
+ if (!sunData) { await setupSunrise() }
+
+ // Set up the future weather stack.
+ // 设置未来天气的Stack
+ let futureWeatherStack = column.addStack()
+ futureWeatherStack.layoutVertically()
+ futureWeatherStack.setPadding(0, 0, 0, 0)
+ futureWeatherStack.url = "https://weather.com/weather/tenday/l/" + locationData.latitude + "," + locationData.longitude
+
+ // Determine if we should show the next hour.
+ // 判断是否应该显示下一个小时的天气
+ const showNextHour = (currentDate.getHours() < weatherSettings.tomorrowShownAtHour)
+
+ // Set the label value.
+ // 设置标签值
+ const subLabelStack = align(futureWeatherStack)
+ const subLabelText = showNextHour ? localizedText.nextHourLabel : localizedText.tomorrowLabel
+ const subLabel = provideText(subLabelText, subLabelStack, textFormat.smallTemp)
+ subLabelStack.setPadding(0, padding, padding/2, padding)
+
+ // Set up the sub condition stack.
+ // 设置子条件的Stack
+ let subConditionStack = align(futureWeatherStack)
+ subConditionStack.layoutHorizontally()
+ subConditionStack.centerAlignContent()
+ subConditionStack.setPadding(0, padding, padding, padding)
+
+ // Determine if it will be night in the next hour.
+ // 判断下一个小时是否会是夜晚
+ var nightCondition
+ if (showNextHour) {
+ const addHour = currentDate.getTime() + (60*60*1000)
+ const newDate = new Date(addHour)
+ nightCondition = isNight(newDate)
+ } else {
+ nightCondition = false
+ }
+
+ let subCondition = subConditionStack.addImage(provideConditionSymbol(showNextHour ? weatherData.nextHourCondition : weatherData.tomorrowCondition,nightCondition))
+ const subConditionSize = showNextHour ? 14 : 18
+ subCondition.imageSize = new Size(subConditionSize, subConditionSize)
+ subConditionStack.addSpacer(5)
+
+ // The next part of the display changes significantly for next hour vs tomorrow.
+ // 与明天相比,下一个小时的显示内容会有很大变化
+ if (showNextHour) {
+ const subTempText = Math.round(weatherData.nextHourTemp) + "°"
+ const subTemp = provideText(subTempText, subConditionStack, textFormat.smallTemp)
+
+ } else {
+ let tomorrowLine = subConditionStack.addImage(drawVerticalLine(new Color("ffffff", 0.5), 20))
+ tomorrowLine.imageSize = new Size(3,28)
+ subConditionStack.addSpacer(5)
+ let tomorrowStack = subConditionStack.addStack()
+ tomorrowStack.layoutVertically()
+
+ const tomorrowHighText = Math.round(weatherData.tomorrowHigh) + ""
+ const tomorrowHigh = provideText(tomorrowHighText, tomorrowStack, textFormat.tinyTemp)
+ tomorrowStack.addSpacer(4)
+ const tomorrowLowText = Math.round(weatherData.tomorrowLow) + ""
+ const tomorrowLow = provideText(tomorrowLowText, tomorrowStack, textFormat.tinyTemp)
+ }
+}
+
+// Return a text-creation function.
+// 返回一个文本创建函数
+function text(input = null) {
+
+ function displayText(column) {
+
+ // Don't do anything if the input is blank.
+ // 如果输入为空,则不执行任何操作
+ if (!input || input == "") { return }
+
+ // Otherwise, add the text.
+ // 否则添加该文本
+ const textStack = align(column)
+ textStack.setPadding(padding, padding, padding, padding) //自定义文本的间距设置,调整这项以更改边距,依次是逆时针顺序上、左、下、右
+ const textDisplay = provideText(input, textStack, textFormat.customText)
+ }
+ return displayText
+}
+
+// Add a battery element to the widget; consisting of a battery icon and percentage.
+// 向小部件添加电池元素;由电池图标和百分比组成
+async function battery(column) {
+
+ // Get battery level via Scriptable function and format it in a convenient way
+ // 通过脚本函数获取电池电量并以简单的方式对其进行格式化
+ function getBatteryLevel() {
+
+ const batteryLevel = Device.batteryLevel()
+ const batteryPercentage = `${Math.round(batteryLevel * 100)}%`
+
+ return batteryPercentage
+ }
+
+ const batteryLevel = Device.batteryLevel()
+
+ // Set up the battery level item
+ // 设置电池电量项目
+ let batteryStack = align(column)
+ batteryStack.layoutHorizontally()
+ batteryStack.centerAlignContent()
+
+ let batteryIcon = batteryStack.addImage(provideBatteryIcon())
+ batteryIcon.imageSize = new Size(30,30)
+
+
+ // Change the battery icon to red if battery level is <= 20 to match system behavior
+ // 如果电池电量小于等于20,则将电池图标更改为红色,以匹配系统行为
+ if ( Math.round(batteryLevel * 100) > 20 || Device.isCharging() ) {
+
+ batteryIcon.tintColor = new Color(textFormat.battery.color || textFormat.defaultText.color)
+
+ } else {
+
+ batteryIcon.tintColor = Color.red()
+
+ }
+
+ batteryStack.addSpacer(padding * 0.6)
+
+ // Display the battery status
+ // 显示电池状态
+ let batteryInfo = provideText(getBatteryLevel(), batteryStack, textFormat.battery)
+
+ batteryStack.setPadding(padding/2, padding, padding/2, padding) //电池电量的间距设置,调整这项以更改边距,依次是逆时针顺序上、左、下、右
+
+}
+
+// Show the sunrise or sunset time.
+// 显示日出或日落时间
+async function sunrise(column) {
+
+ // Requirements: sunrise
+ if (!sunData) { await setupSunrise() }
+
+ const sunrise = sunData.sunrise
+ const sunset = sunData.sunset
+ const showWithin = sunriseSettings.showWithin
+ const closeToSunrise = closeTo(sunrise) <= showWithin
+ const closeToSunset = closeTo(sunset) <= showWithin
+
+ // If we only show sometimes and we're not close, return.
+ if (showWithin > 0 && !closeToSunrise && !closeToSunset) { return }
+
+ // Otherwise, determine which time to show.
+ const showSunrise = closeTo(sunrise) <= closeTo(sunset)
+
+ // Set up the stack.
+ // 设置Stack
+ const sunriseStack = align(column)
+ sunriseStack.setPadding(padding/2, padding, padding/2, padding) //日落日出的间距设置,调整这项以更改边距,依次是逆时针顺序上、左、下、右
+ sunriseStack.layoutHorizontally()
+ sunriseStack.centerAlignContent()
+
+ sunriseStack.addSpacer(padding * 0.3)
+
+ // Add the correct symbol.
+ // 添加正确的符号
+ const symbolName = showSunrise ? "sunrise.fill" : "sunset.fill"
+ const symbol = sunriseStack.addImage(SFSymbol.named(symbolName).image)
+ symbol.imageSize = new Size(22,22)
+
+ sunriseStack.addSpacer(padding)
+
+ // Add the time.
+ // 添加时间
+ const timeText = formatTime(showSunrise ? new Date(sunrise) : new Date(sunset))
+ const time = provideText(timeText, sunriseStack, textFormat.sunrise)
+}
+
+// Allow for either term to be used.
+// 允许使用任一术语
+async function sunset(column) {
+ return await sunrise(column)
+}
+
+/*
+ * HELPER FUNCTIONS
+ * 帮助函数
+ * These functions perform duties for other functions.
+ * 这些函数都是服务于以上的项目的
+ * ===================================================
+ */
+
+// Determines if the provided date is at night.
+function isNight(dateInput) {
+ const timeValue = dateInput.getTime()
+ return (timeValue < sunData.sunrise) || (timeValue > sunData.sunset)
+}
+
+// Determines if two dates occur on the same day
+function sameDay(d1, d2) {
+ return d1.getFullYear() === d2.getFullYear() &&
+ d1.getMonth() === d2.getMonth() &&
+ d1.getDate() === d2.getDate()
+}
+
+// Returns the number of minutes between now and the provided date.
+function closeTo(time) {
+ return Math.abs(currentDate.getTime() - time) / 60000
+}
+
+// Format the time for a Date input.
+function formatTime(date) {
+ let df = new DateFormatter()
+ df.locale = locale
+ df.useNoDateStyle()
+ df.useShortTimeStyle()
+ return df.string(date)
+}
+
+// Provide a text symbol with the specified shape.
+function provideTextSymbol(shape) {
+
+ // Rectangle character.
+ if (shape.startsWith("rect")) {
+ return "\u2759"
+ }
+ // Circle character.
+ if (shape == "circle") {
+ return "\u2B24"
+ }
+ // Default to the rectangle.
+ return "\u2759"
+}
+
+// Provide a battery SFSymbol with accurate level drawn on top of it.
+function provideBatteryIcon() {
+
+ // If we're charging, show the charging icon.
+ if (Device.isCharging()) { return SFSymbol.named("battery.100.bolt").image }
+
+ // Set the size of the battery icon.
+ const batteryWidth = 87
+ const batteryHeight = 41
+
+ // Start our draw context.
+ let draw = new DrawContext()
+ draw.opaque = false
+ draw.respectScreenScale = true
+ draw.size = new Size(batteryWidth, batteryHeight)
+
+ // Draw the battery.
+ draw.drawImageInRect(SFSymbol.named("battery.0").image, new Rect(0, 0, batteryWidth, batteryHeight))
+
+ // Match the battery level values to the SFSymbol.
+ const x = batteryWidth*0.1525
+ const y = batteryHeight*0.247
+ const width = batteryWidth*0.602
+ const height = batteryHeight*0.505
+
+ // Prevent unreadable icons.
+ let level = Device.batteryLevel()
+ if (level < 0.05) { level = 0.05 }
+
+ // Determine the width and radius of the battery level.
+ const current = width * level
+ let radius = height/6.5
+
+ // When it gets low, adjust the radius to match.
+ if (current < (radius * 2)) { radius = current / 2 }
+
+ // Make the path for the battery level.
+ let barPath = new Path()
+ barPath.addRoundedRect(new Rect(x, y, current, height), radius, radius)
+ draw.addPath(barPath)
+ draw.setFillColor(Color.black())
+ draw.fillPath()
+ return draw.getImage()
+}
+
+// Provide a symbol based on the condition.
+function provideConditionSymbol(cond,night) {
+
+ // Define our symbol equivalencies.
+ let symbols = {
+
+ // Thunderstorm
+ "2": function() { return "cloud.bolt.rain.fill" },
+
+ // Drizzle
+ "3": function() { return "cloud.drizzle.fill" },
+
+ // Rain
+ "5": function() { return (cond == 511) ? "cloud.sleet.fill" : "cloud.rain.fill" },
+
+ // Snow
+ "6": function() { return (cond >= 611 && cond <= 613) ? "cloud.snow.fill" : "snow" },
+
+ // Atmosphere
+ "7": function() {
+ if (cond == 781) { return "tornado" }
+ if (cond == 701 || cond == 741) { return "cloud.fog.fill" }
+ return night ? "cloud.fog.fill" : "sun.haze.fill"
+ },
+
+ // Clear and clouds
+ "8": function() {
+ if (cond == 800 || cond == 801) { return night ? "moon.stars.fill" : "sun.max.fill" }
+ if (cond == 802 || cond == 803) { return night ? "cloud.moon.fill" : "cloud.sun.fill" }
+ return "cloud.fill"
+ }
+ }
+
+ // Find out the first digit.
+ let conditionDigit = Math.floor(cond / 100)
+
+ // Get the symbol.
+ return SFSymbol.named(symbols[conditionDigit]()).image
+}
+
+// Provide a font based on the input.
+function provideFont(fontName, fontSize) {
+ const fontGenerator = {
+ "ultralight": function() { return Font.ultraLightSystemFont(fontSize) },
+ "light": function() { return Font.lightSystemFont(fontSize) },
+ "regular": function() { return Font.regularSystemFont(fontSize) },
+ "medium": function() { return Font.mediumSystemFont(fontSize) },
+ "semibold": function() { return Font.semiboldSystemFont(fontSize) },
+ "bold": function() { return Font.boldSystemFont(fontSize) },
+ "heavy": function() { return Font.heavySystemFont(fontSize) },
+ "black": function() { return Font.blackSystemFont(fontSize) },
+ "italic": function() { return Font.italicSystemFont(fontSize) }
+ }
+
+ const systemFont = fontGenerator[fontName]
+ if (systemFont) { return systemFont() }
+ return new Font(fontName, fontSize)
+}
+
+// Add formatted text to a container.
+function provideText(string, container, format) {
+ const textItem = container.addText(string)
+ const textFont = format.font || textFormat.defaultText.font
+ const textSize = format.size || textFormat.defaultText.size
+ const textColor = format.color || textFormat.defaultText.color
+
+ textItem.font = provideFont(textFont, textSize)
+ textItem.textColor = new Color(textColor)
+ return textItem
+}
+
+/*
+ * DRAWING FUNCTIONS
+ * These functions draw onto a canvas.
+ * ===================================
+ */
+
+// Draw the vertical line in the tomorrow view.
+function drawVerticalLine(color, height) {
+
+ const width = 2
+
+ let draw = new DrawContext()
+ draw.opaque = false
+ draw.respectScreenScale = true
+ draw.size = new Size(width,height)
+
+ let barPath = new Path()
+ const barHeight = height
+ barPath.addRoundedRect(new Rect(0, 0, width, height), width/2, width/2)
+ draw.addPath(barPath)
+ draw.setFillColor(color)
+ draw.fillPath()
+
+ return draw.getImage()
+}
+
+// Draw the temp bar.
+function drawTempBar() {
+
+ // Set the size of the temp bar.
+ const tempBarWidth = 200
+ const tempBarHeight = 20
+
+ // Calculate the current percentage of the high-low range.
+ let percent = (weatherData.currentTemp - weatherData.todayLow) / (weatherData.todayHigh - weatherData.todayLow)
+
+ // If we're out of bounds, clip it.
+ if (percent < 0) {
+ percent = 0
+ } else if (percent > 1) {
+ percent = 1
+ }
+
+ // Determine the scaled x-value for the current temp.
+ const currPosition = (tempBarWidth - tempBarHeight) * percent
+
+ // Start our draw context.
+ let draw = new DrawContext()
+ draw.opaque = false
+ draw.respectScreenScale = true
+ draw.size = new Size(tempBarWidth, tempBarHeight)
+
+ // Make the path for the bar.
+ let barPath = new Path()
+ const barHeight = tempBarHeight - 10
+ barPath.addRoundedRect(new Rect(0, 5, tempBarWidth, barHeight), barHeight / 2, barHeight / 2)
+ draw.addPath(barPath)
+ draw.setFillColor(new Color("ffffff", 0.5))
+ draw.fillPath()
+
+ // Make the path for the current temp indicator.
+ let currPath = new Path()
+ currPath.addEllipse(new Rect(currPosition, 0, tempBarHeight, tempBarHeight))
+ draw.addPath(currPath)
+ draw.setFillColor(new Color("ffffff", 1))
+ draw.fillPath()
+
+ return draw.getImage()
+}
diff --git a/weather-cal.js b/Weather-Cal_English.js
similarity index 88%
rename from weather-cal.js
rename to Weather-Cal_English.js
index 4944f9c..fdba111 100644
--- a/weather-cal.js
+++ b/Weather-Cal_English.js
@@ -22,8 +22,8 @@ const imageBackground = true
// Set to true to reset the widget's background image.
const forceImageUpdate = false
-// Set the padding around each item. Default is 10.
-const padding = 10
+// Set the padding around each item. Default is 5.
+const padding = 5
/*
* LAYOUT
@@ -31,37 +31,35 @@ const padding = 10
* ========================================
*/
-// Set the width of the column, or set to 0 for an automatic width.
+// You always need to start with "row," and "column," items, but you can now add as many as you want.
+// Adding left, right, or center will align everything after that. The default alignment is left.
-// You can add items to the column:
-// date, greeting, events, current, future, battery, text("Your text here")
-// You can also add a left, center, or right to the list. Everything after it will be aligned that way.
+// You can add a flexible vertical space with "space," or a fixed-size space like this: "space(50)"
+// Align items to the top or bottom of columns by adding "space," before or after all items in the column.
+// There are many possible items, including: date, greeting, events, current, future, battery, sunrise, and text("Your text here")
// Make sure to always put a comma after each item.
-const columns = [{
+const items = [
- // Settings for the left column.
- width: 0,
- items: [
-
- left,
- greeting,
+ row,
+
+ column,
date,
- events,
-
-]}, {
-
- // Settings for the right column.
- width: 100,
- items: [
+ battery,
+ sunrise,
+ space,
- left,
+ column(90),
current,
- space,
future,
+
+ row,
+
+ column,
+ events,
-]}]
+]
/*
* ITEM SETTINGS
@@ -74,7 +72,7 @@ const columns = [{
const dateSettings = {
// If set to true, date will become smaller when events are displayed.
- dynamicDateSize: true
+ dynamicDateSize: false
// If the date is not dynamic, should it be large or small?
,staticDateSize: "large"
@@ -190,8 +188,8 @@ const textFormat = {
customText: { size: 14, color: "", font: "" },
- battery: { size: 18, color: "", font: "medium" },
- sunrise: { size: 18, color: "", font: "medium" },
+ battery: { size: 14, color: "", font: "medium" },
+ sunrise: { size: 14, color: "", font: "medium" },
}
/*
@@ -211,37 +209,26 @@ const currentDate = new Date()
const files = FileManager.local()
/*
- * COLUMNS
- * =======
+ * CONSTRUCTION
+ * ============
*/
-// Set up the widget and the main stack.
-let widget = new ListWidget()
-widget.setPadding(0, 0, 0, 0)
+// Set up the widget with padding.
+const widget = new ListWidget()
+const horizontalPad = padding < 10 ? 10 - padding : 10
+const verticalPad = padding < 15 ? 15 - padding : 15
+widget.setPadding(horizontalPad, verticalPad, horizontalPad, verticalPad)
+widget.spacing = 0
-let mainStack = widget.addStack()
-mainStack.layoutHorizontally()
-mainStack.setPadding(0, 0, 0, 0)
+// Set up the global variables.
+var currentRow = {}
+var currentColumn = {}
-// Set up alignment.
-var currentAlignment = left
+// Set up the initial alignment.
+var currentAlignment = alignLeft
-// Set up our columns.
-for (var x = 0; x < columns.length; x++) {
-
- let column = columns[x]
- let columnStack = mainStack.addStack()
- columnStack.layoutVertically()
-
- // Only add padding on the first or last column.
- columnStack.setPadding(0, x == 0 ? padding/2 : 0, 0, x == columns.length-1 ? padding/2 : 0)
- columnStack.size = new Size(column.width,0)
-
- // Add the items to the column.
- for (var i = 0; i < column.items.length; i++) {
- await column.items[i](columnStack)
- }
-}
+// Set up our items.
+for (item of items) { await item(currentColumn) }
/*
* BACKGROUND DISPLAY
@@ -294,6 +281,46 @@ Script.complete()
* =============================================
*/
+// Makes a new row on the widget.
+function row(input = null) {
+
+ function makeRow() {
+ currentRow = widget.addStack()
+ currentRow.layoutHorizontally()
+ currentRow.setPadding(0, 0, 0, 0)
+ currentColumn.spacing = 0
+
+ // If input was given, make a column of that size.
+ if (input > 0) { currentRow.size = new Size(0,input) }
+ }
+
+ // If there's no input or it's a number, it's being called in the layout declaration.
+ if (!input || typeof input == "number") { return makeRow }
+
+ // Otherwise, it's being called in the generator.
+ else { makeRow() }
+}
+
+// Makes a new column on the widget.
+function column(input = null) {
+
+ function makeColumn() {
+ currentColumn = currentRow.addStack()
+ currentColumn.layoutVertically()
+ currentColumn.setPadding(0, 0, 0, 0)
+ currentColumn.spacing = 0
+
+ // If input was given, make a column of that size.
+ if (input > 0) { currentColumn.size = new Size(input,0) }
+ }
+
+ // If there's no input or it's a number, it's being called in the layout declaration.
+ if (!input || typeof input == "number") { return makeColumn }
+
+ // Otherwise, it's being called in the generator.
+ else { makeColumn() }
+}
+
// Create an aligned stack to add content to.
function align(column) {
@@ -635,12 +662,12 @@ async function date(column) {
let dateOneStack = align(column)
df.dateFormat = dateSettings.largeDateLineOne
let dateOne = provideText(df.string(currentDate), dateOneStack, textFormat.largeDate1)
- dateOneStack.setPadding(padding, padding, 0, padding)
+ dateOneStack.setPadding(padding/2, padding, 0, padding)
let dateTwoStack = align(column)
df.dateFormat = dateSettings.largeDateLineTwo
let dateTwo = provideText(df.string(currentDate), dateTwoStack, textFormat.largeDate2)
- dateTwoStack.setPadding(0, padding, padding, 10)
+ dateTwoStack.setPadding(0, padding, padding, padding)
}
}
@@ -722,7 +749,7 @@ async function events(column) {
// Mimic the formatting of an event title, mostly.
const eventLabelStack = align(currentStack)
const eventLabel = provideText(event.title, eventLabelStack, textFormat.eventLabel)
- eventLabelStack.setPadding(i==0 ? padding : padding/2, padding, padding/2, padding)
+ eventLabelStack.setPadding(padding, padding, padding, padding)
continue
}
@@ -739,7 +766,7 @@ async function events(column) {
}
const title = provideText(event.title.trim(), titleStack, textFormat.eventTitle)
- titleStack.setPadding(i==0 ? padding : padding/2, padding, event.isAllDay ? padding/2 : padding/10, padding)
+ titleStack.setPadding(padding, padding, event.isAllDay ? padding : padding/5, padding)
// If we're showing a color on the right, show it.
if (showCalendarColor.length && showCalendarColor.includes("right")) {
@@ -774,7 +801,7 @@ async function events(column) {
const timeStack = align(currentStack)
const time = provideText(timeText, timeStack, textFormat.eventTime)
- timeStack.setPadding(0, padding, i==futureEvents.length-1 ? padding : padding/2, padding)
+ timeStack.setPadding(0, padding, padding, padding)
}
}
@@ -795,7 +822,7 @@ async function current(column) {
if (weatherSettings.showLocation) {
let locationTextStack = align(currentWeatherStack)
let locationText = provideText(locationData.locality, locationTextStack, textFormat.smallTemp)
- locationTextStack.setPadding(padding, padding, padding/2, padding)
+ locationTextStack.setPadding(padding, padding, padding, padding)
}
// Show the current condition symbol.
@@ -808,7 +835,7 @@ async function current(column) {
if (weatherSettings.showCondition) {
let conditionTextStack = align(currentWeatherStack)
let conditionText = provideText(weatherData.currentDescription, conditionTextStack, textFormat.smallTemp)
- conditionTextStack.setPadding(padding/2, padding, 0, padding)
+ conditionTextStack.setPadding(padding, padding, 0, padding)
}
// Show the current temperature.
@@ -823,7 +850,7 @@ async function current(column) {
// Show the temp bar and high/low values.
let tempBarStack = align(currentWeatherStack)
tempBarStack.layoutVertically()
- tempBarStack.setPadding(0, padding, padding/2, padding)
+ tempBarStack.setPadding(0, padding, padding, padding)
let tempBar = drawTempBar()
let tempBarImage = tempBarStack.addImage(tempBar)
@@ -840,7 +867,7 @@ async function current(column) {
const mainHighText = Math.round(weatherData.todayHigh).toString()
const mainHigh = provideText(mainHighText, highLowStack, textFormat.tinyTemp)
- tempBarStack.size = new Size(70,30)
+ tempBarStack.size = new Size(60,30)
}
// Display upcoming weather.
@@ -863,7 +890,7 @@ async function future(column) {
const subLabelStack = align(futureWeatherStack)
const subLabelText = showNextHour ? localizedText.nextHourLabel : localizedText.tomorrowLabel
const subLabel = provideText(subLabelText, subLabelStack, textFormat.smallTemp)
- subLabelStack.setPadding(0, padding, padding/4, padding)
+ subLabelStack.setPadding(0, padding, padding/2, padding)
// Set up the sub condition stack.
let subConditionStack = align(futureWeatherStack)
@@ -933,7 +960,7 @@ async function battery(column) {
return batteryPercentage
}
-
+
const batteryLevel = Device.batteryLevel()
// Set up the battery level item
@@ -944,11 +971,10 @@ async function battery(column) {
let batteryIcon = batteryStack.addImage(provideBatteryIcon())
batteryIcon.imageSize = new Size(30,30)
-
// Change the battery icon to red if battery level is <= 20 to match system behavior
if ( Math.round(batteryLevel * 100) > 20 || Device.isCharging() ) {
- batteryIcon.tintColor = Color.white()
+ batteryIcon.tintColor = new Color(textFormat.battery.color || textFormat.defaultText.color)
} else {
@@ -956,12 +982,12 @@ async function battery(column) {
}
- batteryStack.addSpacer(padding * 0.8)
+ batteryStack.addSpacer(padding * 0.6)
// Display the battery status
let batteryInfo = provideText(getBatteryLevel(), batteryStack, textFormat.battery)
- batteryStack.setPadding(padding, padding, padding, padding)
+ batteryStack.setPadding(padding/2, padding, padding/2, padding)
}
@@ -985,16 +1011,18 @@ async function sunrise(column) {
// Set up the stack.
const sunriseStack = align(column)
- sunriseStack.setPadding(padding, padding, padding, padding)
+ sunriseStack.setPadding(padding/2, padding, padding/2, padding)
sunriseStack.layoutHorizontally()
sunriseStack.centerAlignContent()
+ sunriseStack.addSpacer(padding * 0.3)
+
// Add the correct symbol.
const symbolName = showSunrise ? "sunrise.fill" : "sunset.fill"
const symbol = sunriseStack.addImage(SFSymbol.named(symbolName).image)
symbol.imageSize = new Size(22,22)
- sunriseStack.addSpacer(padding * 0.8)
+ sunriseStack.addSpacer(padding)
// Add the time.
const timeText = formatTime(showSunrise ? new Date(sunrise) : new Date(sunset))
@@ -1054,43 +1082,49 @@ function provideTextSymbol(shape) {
return "\u2759"
}
-// Provide the SF Symbols battery icon depending on the battery level.
+// Provide a battery SFSymbol with accurate level drawn on top of it.
function provideBatteryIcon() {
- // Charging symbol
- if ( Device.isCharging() ) {
-
- let batIcon = SFSymbol.named("battery.100.bolt")
- batIcon.applyLightWeight()
-
- return batIcon.image
- }
+ // If we're charging, show the charging icon.
+ if (Device.isCharging()) { return SFSymbol.named("battery.100.bolt").image }
- const batteryLevel = Device.batteryLevel()
+ // Set the size of the battery icon.
+ const batteryWidth = 87
+ const batteryHeight = 41
- // Battery mostly full
- if ( Math.round(batteryLevel * 100) > 65 ) {
-
- let batIcon = SFSymbol.named("battery.100")
- batIcon.applyLightWeight()
-
- return batIcon.image
- }
+ // Start our draw context.
+ let draw = new DrawContext()
+ draw.opaque = false
+ draw.respectScreenScale = true
+ draw.size = new Size(batteryWidth, batteryHeight)
- // Battery getting low
- if ( Math.round(batteryLevel * 100) > 30 ) {
-
- let batIcon = SFSymbol.named("battery.25")
- batIcon.applyLightWeight()
-
- return batIcon.image
- }
+ // Draw the battery.
+ draw.drawImageInRect(SFSymbol.named("battery.0").image, new Rect(0, 0, batteryWidth, batteryHeight))
+
+ // Match the battery level values to the SFSymbol.
+ const x = batteryWidth*0.1525
+ const y = batteryHeight*0.247
+ const width = batteryWidth*0.602
+ const height = batteryHeight*0.505
- // Low battery
- let batIcon = SFSymbol.named("battery.0")
- batIcon.applySemiboldWeight()
+ // Prevent unreadable icons.
+ let level = Device.batteryLevel()
+ if (level < 0.05) { level = 0.05 }
+
+ // Determine the width and radius of the battery level.
+ const current = width * level
+ let radius = height/6.5
+
+ // When it gets low, adjust the radius to match.
+ if (current < (radius * 2)) { radius = current / 2 }
- return batIcon.image
+ // Make the path for the battery level.
+ let barPath = new Path()
+ barPath.addRoundedRect(new Rect(x, y, current, height), radius, radius)
+ draw.addPath(barPath)
+ draw.setFillColor(Color.black())
+ draw.fillPath()
+ return draw.getImage()
}
// Provide a symbol based on the condition.
@@ -1182,7 +1216,7 @@ function drawVerticalLine(color, height) {
let barPath = new Path()
const barHeight = height
- barPath.addRoundedRect(new Rect(0, 0, height, height), width/2, width/2)
+ barPath.addRoundedRect(new Rect(0, 0, width, height), width/2, width/2)
draw.addPath(barPath)
draw.setFillColor(color)
draw.fillPath()
diff --git a/image/Weather-Cal.jpg b/image/Weather-Cal.jpg
new file mode 100644
index 0000000..8898059
Binary files /dev/null and b/image/Weather-Cal.jpg differ
diff --git a/widget-blur.js b/widget-blur.js
new file mode 100644
index 0000000..ed3fe9f
--- /dev/null
+++ b/widget-blur.js
@@ -0,0 +1,807 @@
+// Variables used by Scriptable.
+// These must be at the very 顶部 of the file. Do not edit.
+// icon-color: yellow; icon-glyph: magic;
+
+// This script was created by Max Zeryck.
+
+// The amount of blurring. Default is 150.
+let blur = 150
+
+// Determine if user has taken the screenshot.
+var message
+message = "开始之前,请回到主屏幕并进入编辑模式。 滑到最右边的空白页并截图。"
+let options = ["继续选择图片","退出以截图","更新代码"]
+let response = await generateAlert(message,options)
+
+// Return if we need to exit.
+if (response == 1) return
+
+// Update the code.
+if (response == 2) {
+
+ // Determine if the user is using iCloud.
+ let files = FileManager.local()
+ const iCloudInUse = files.isFileStoredIniCloud(module.filename)
+
+ // If so, use an iCloud file manager.
+ files = iCloudInUse ? FileManager.iCloud() : files
+
+ // Try to download the file.
+ try {
+ const req = new Request("https://raw.githubusercontent.com/KerwinKwong/Weather-Cal/main/widget-blur.js")
+ const codeString = await req.loadString()
+ files.writeString(module.filename, codeString)
+ message = "代码已更新。如果脚本已打开,请将其关闭以使更改生效。"
+ } catch {
+ message = "更新失败,请稍后再试。"
+ }
+ options = ["OK"]
+ await generateAlert(message,options)
+ return
+}
+
+// Get screenshot and determine phone size.
+let img = await Photos.fromLibrary()
+let height = img.size.height
+let phone = phoneSizes()[height]
+if (!phone) {
+ message = "您似乎选择了非iPhone屏幕截图的图像,或者不支持您的iPhone。请使用其他图像再试一次!"
+ await generateAlert(message,["OK"])
+ return
+}
+
+// Extra setup needed for 2436-sized phones.
+if (height == 2436) {
+
+ let files = FileManager.local()
+ let cacheName = "kz-phone-type"
+ let cachePath = files.joinPath(files.libraryDirectory(), cacheName)
+
+ // If we already cached the phone size, load it.
+ if (files.fileExists(cachePath)) {
+ let typeString = files.readString(cachePath)
+ phone = phone[typeString]
+
+ // Otherwise, prompt the user.
+ } else {
+ message = "你使用什么型号的iPhone?"
+ let types = ["iPhone 12 mini", "iPhone 11 Pro, XS, or X"]
+ let typeIndex = await generateAlert(message, types)
+ let type = (typeIndex == 0) ? "mini" : "x"
+ phone = phone[type]
+ files.writeString(cachePath, type)
+ }
+}
+
+// Prompt for widget size and position.
+message = "您想要创建什么尺寸的小部件?"
+let sizes = ["小号","中号","大号"]
+let size = await generateAlert(message,sizes)
+let widgetSize = sizes[size]
+
+message = "您想它应用在什么位置?"
+message += (height == 1136 ? " (请注意,您的设备仅支持两行小部件,因此中间和底部选项相同。)" : "")
+
+// Determine image crop based on phone size.
+let crop = { w: "", h: "", x: "", y: "" }
+if (widgetSize == "小号") {
+ crop.w = phone.小号
+ crop.h = phone.小号
+ let positions = ["顶部 左边","顶部 右边","中间 左边","中间 右边","底部 左边","底部 右边"]
+ let position = await generateAlert(message,positions)
+
+ // Convert the two words into two keys for the phone size dictionary.
+ let keys = positions[position].toLowerCase().split(' ')
+ crop.y = phone[keys[0]]
+ crop.x = phone[keys[1]]
+
+} else if (widgetSize == "中号") {
+ crop.w = phone.中号
+ crop.h = phone.小号
+
+ // 中号 and 大号 widgets have a fixed x-value.
+ crop.x = phone.左边
+ let positions = ["顶部","中间","底部"]
+ let position = await generateAlert(message,positions)
+ let key = positions[position].toLowerCase()
+ crop.y = phone[key]
+
+} else if(widgetSize == "大号") {
+ crop.w = phone.中号
+ crop.h = phone.大号
+ crop.x = phone.左边
+ let positions = ["顶部","底部"]
+ let position = await generateAlert(message,positions)
+
+ // 大号 widgets at the 底部 have the "中间" y-value.
+ crop.y = position ? phone.中间 : phone.顶部
+}
+
+// Prompt for blur style.
+message = "您想要一个完全透明的小部件,还是半透明的模糊效果?"
+let blurOptions = ["透明背景","浅色模糊","深色模糊","完全模糊"]
+let blurred = await generateAlert(message,blurOptions)
+
+// We always need the cropped image.
+let imgCrop = cropImage(img)
+
+// If it's blurred, set the blur style.
+if (blurred) {
+ const styles = ["", "light", "dark", "none"]
+ const style = styles[blurred]
+ imgCrop = await blurImage(img,imgCrop,style)
+}
+
+message = "您的小部件背景已准备就绪。选择保存图像的位置:"
+const exportPhotoOptions = ["导出到相册","导出到文件"]
+const exportToFiles = await generateAlert(message,exportPhotoOptions)
+
+if (exportToFiles) {
+ await DocumentPicker.exportImage(imgCrop)
+} else {
+ Photos.save(imgCrop)
+}
+
+Script.complete()
+
+// Generate an alert with the provided array of options.
+async function generateAlert(message,options) {
+
+ let alert = new Alert()
+ alert.message = message
+
+ for (const option of options) {
+ alert.addAction(option)
+ }
+
+ let response = await alert.presentAlert()
+ return response
+}
+
+// Crop an image into the specified rect.
+function cropImage(image) {
+
+ let draw = new DrawContext()
+ let rect = new Rect(crop.x,crop.y,crop.w,crop.h)
+ draw.size = new Size(rect.width, rect.height)
+
+ draw.drawImageAtPoint(image,new Point(-rect.x, -rect.y))
+ return draw.getImage()
+}
+
+async function blurImage(img,imgCrop,style) {
+ const js = `
+ /*
+
+ StackBlur - a fast almost Gaussian Blur For Canvas
+
+ Version: 0.5
+ Author: Mario Klingemann
+ Contact: mario@quasimondo.com
+ Website: http://quasimondo.com/StackBlurForCanvas/StackBlurDemo.html
+ Twitter: @quasimondo
+
+ In case you find this class useful - especially in commercial projects -
+ I am not totally unhappy for a small donation to my PayPal account
+ mario@quasimondo.de
+
+ Or support me on flattr:
+ https://flattr.com/thing/72791/StackBlur-a-fast-almost-Gaussian-Blur-Effect-for-CanvasJavascript
+
+ Copyright (c) 2010 Mario Klingemann
+
+ 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:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ 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.
+ */
+
+ var mul_table = [
+ 512,512,456,512,328,456,335,512,405,328,271,456,388,335,292,512,
+ 454,405,364,328,298,271,496,456,420,388,360,335,312,292,273,512,
+ 482,454,428,405,383,364,345,328,312,298,284,271,259,496,475,456,
+ 437,420,404,388,374,360,347,335,323,312,302,292,282,273,265,512,
+ 497,482,468,454,441,428,417,405,394,383,373,364,354,345,337,328,
+ 320,312,305,298,291,284,278,271,265,259,507,496,485,475,465,456,
+ 446,437,428,420,412,404,396,388,381,374,367,360,354,347,341,335,
+ 329,323,318,312,307,302,297,292,287,282,278,273,269,265,261,512,
+ 505,497,489,482,475,468,461,454,447,441,435,428,422,417,411,405,
+ 399,394,389,383,378,373,368,364,359,354,350,345,341,337,332,328,
+ 324,320,316,312,309,305,301,298,294,291,287,284,281,278,274,271,
+ 268,265,262,259,257,507,501,496,491,485,480,475,470,465,460,456,
+ 451,446,442,437,433,428,424,420,416,412,408,404,400,396,392,388,
+ 385,381,377,374,370,367,363,360,357,354,350,347,344,341,338,335,
+ 332,329,326,323,320,318,315,312,310,307,304,302,299,297,294,292,
+ 289,287,285,282,280,278,275,273,271,269,267,265,263,261,259];
+
+
+ var shg_table = [
+ 9, 11, 12, 13, 13, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 17,
+ 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19,
+ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20,
+ 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21,
+ 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
+ 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22,
+ 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
+ 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23,
+ 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+ 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+ 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
+ 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+ 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+ 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+ 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+ 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24 ];
+
+ function stackBlurCanvasRGB( id, top_x, top_y, width, height, radius )
+ {
+ if ( isNaN(radius) || radius < 1 ) return;
+ radius |= 0;
+
+ var canvas = document.getElementById( id );
+ var context = canvas.getContext("2d");
+ var imageData;
+
+ try {
+ try {
+ imageData = context.getImageData( top_x, top_y, width, height );
+ } catch(e) {
+
+ // NOTE: this part is supposedly only needed if you want to work with local files
+ // so it might be okay to remove the whole try/catch block and just use
+ // imageData = context.getImageData( top_x, top_y, width, height );
+ try {
+ netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
+ imageData = context.getImageData( top_x, top_y, width, height );
+ } catch(e) {
+ alert("Cannot access local image");
+ throw new Error("unable to access local image data: " + e);
+ return;
+ }
+ }
+ } catch(e) {
+ alert("Cannot access image");
+ throw new Error("unable to access image data: " + e);
+ }
+
+ var pixels = imageData.data;
+
+ var x, y, i, p, yp, yi, yw, r_sum, g_sum, b_sum,
+ r_out_sum, g_out_sum, b_out_sum,
+ r_in_sum, g_in_sum, b_in_sum,
+ pr, pg, pb, rbs;
+
+ var div = radius + radius + 1;
+ var w4 = width << 2;
+ var widthMinus1 = width - 1;
+ var heightMinus1 = height - 1;
+ var radiusPlus1 = radius + 1;
+ var sumFactor = radiusPlus1 * ( radiusPlus1 + 1 ) / 2;
+
+ var stackStart = new BlurStack();
+ var stack = stackStart;
+ for ( i = 1; i < div; i++ )
+ {
+ stack = stack.next = new BlurStack();
+ if ( i == radiusPlus1 ) var stackEnd = stack;
+ }
+ stack.next = stackStart;
+ var stackIn = null;
+ var stackOut = null;
+
+ yw = yi = 0;
+
+ var mul_sum = mul_table[radius];
+ var shg_sum = shg_table[radius];
+
+ for ( y = 0; y < height; y++ )
+ {
+ r_in_sum = g_in_sum = b_in_sum = r_sum = g_sum = b_sum = 0;
+
+ r_out_sum = radiusPlus1 * ( pr = pixels[yi] );
+ g_out_sum = radiusPlus1 * ( pg = pixels[yi+1] );
+ b_out_sum = radiusPlus1 * ( pb = pixels[yi+2] );
+
+ r_sum += sumFactor * pr;
+ g_sum += sumFactor * pg;
+ b_sum += sumFactor * pb;
+
+ stack = stackStart;
+
+ for( i = 0; i < radiusPlus1; i++ )
+ {
+ stack.r = pr;
+ stack.g = pg;
+ stack.b = pb;
+ stack = stack.next;
+ }
+
+ for( i = 1; i < radiusPlus1; i++ )
+ {
+ p = yi + (( widthMinus1 < i ? widthMinus1 : i ) << 2 );
+ r_sum += ( stack.r = ( pr = pixels[p])) * ( rbs = radiusPlus1 - i );
+ g_sum += ( stack.g = ( pg = pixels[p+1])) * rbs;
+ b_sum += ( stack.b = ( pb = pixels[p+2])) * rbs;
+
+ r_in_sum += pr;
+ g_in_sum += pg;
+ b_in_sum += pb;
+
+ stack = stack.next;
+ }
+
+
+ stackIn = stackStart;
+ stackOut = stackEnd;
+ for ( x = 0; x < width; x++ )
+ {
+ pixels[yi] = (r_sum * mul_sum) >> shg_sum;
+ pixels[yi+1] = (g_sum * mul_sum) >> shg_sum;
+ pixels[yi+2] = (b_sum * mul_sum) >> shg_sum;
+
+ r_sum -= r_out_sum;
+ g_sum -= g_out_sum;
+ b_sum -= b_out_sum;
+
+ r_out_sum -= stackIn.r;
+ g_out_sum -= stackIn.g;
+ b_out_sum -= stackIn.b;
+
+ p = ( yw + ( ( p = x + radius + 1 ) < widthMinus1 ? p : widthMinus1 ) ) << 2;
+
+ r_in_sum += ( stackIn.r = pixels[p]);
+ g_in_sum += ( stackIn.g = pixels[p+1]);
+ b_in_sum += ( stackIn.b = pixels[p+2]);
+
+ r_sum += r_in_sum;
+ g_sum += g_in_sum;
+ b_sum += b_in_sum;
+
+ stackIn = stackIn.next;
+
+ r_out_sum += ( pr = stackOut.r );
+ g_out_sum += ( pg = stackOut.g );
+ b_out_sum += ( pb = stackOut.b );
+
+ r_in_sum -= pr;
+ g_in_sum -= pg;
+ b_in_sum -= pb;
+
+ stackOut = stackOut.next;
+
+ yi += 4;
+ }
+ yw += width;
+ }
+
+
+ for ( x = 0; x < width; x++ )
+ {
+ g_in_sum = b_in_sum = r_in_sum = g_sum = b_sum = r_sum = 0;
+
+ yi = x << 2;
+ r_out_sum = radiusPlus1 * ( pr = pixels[yi]);
+ g_out_sum = radiusPlus1 * ( pg = pixels[yi+1]);
+ b_out_sum = radiusPlus1 * ( pb = pixels[yi+2]);
+
+ r_sum += sumFactor * pr;
+ g_sum += sumFactor * pg;
+ b_sum += sumFactor * pb;
+
+ stack = stackStart;
+
+ for( i = 0; i < radiusPlus1; i++ )
+ {
+ stack.r = pr;
+ stack.g = pg;
+ stack.b = pb;
+ stack = stack.next;
+ }
+
+ yp = width;
+
+ for( i = 1; i <= radius; i++ )
+ {
+ yi = ( yp + x ) << 2;
+
+ r_sum += ( stack.r = ( pr = pixels[yi])) * ( rbs = radiusPlus1 - i );
+ g_sum += ( stack.g = ( pg = pixels[yi+1])) * rbs;
+ b_sum += ( stack.b = ( pb = pixels[yi+2])) * rbs;
+
+ r_in_sum += pr;
+ g_in_sum += pg;
+ b_in_sum += pb;
+
+ stack = stack.next;
+
+ if( i < heightMinus1 )
+ {
+ yp += width;
+ }
+ }
+
+ yi = x;
+ stackIn = stackStart;
+ stackOut = stackEnd;
+ for ( y = 0; y < height; y++ )
+ {
+ p = yi << 2;
+ pixels[p] = (r_sum * mul_sum) >> shg_sum;
+ pixels[p+1] = (g_sum * mul_sum) >> shg_sum;
+ pixels[p+2] = (b_sum * mul_sum) >> shg_sum;
+
+ r_sum -= r_out_sum;
+ g_sum -= g_out_sum;
+ b_sum -= b_out_sum;
+
+ r_out_sum -= stackIn.r;
+ g_out_sum -= stackIn.g;
+ b_out_sum -= stackIn.b;
+
+ p = ( x + (( ( p = y + radiusPlus1) < heightMinus1 ? p : heightMinus1 ) * width )) << 2;
+
+ r_sum += ( r_in_sum += ( stackIn.r = pixels[p]));
+ g_sum += ( g_in_sum += ( stackIn.g = pixels[p+1]));
+ b_sum += ( b_in_sum += ( stackIn.b = pixels[p+2]));
+
+ stackIn = stackIn.next;
+
+ r_out_sum += ( pr = stackOut.r );
+ g_out_sum += ( pg = stackOut.g );
+ b_out_sum += ( pb = stackOut.b );
+
+ r_in_sum -= pr;
+ g_in_sum -= pg;
+ b_in_sum -= pb;
+
+ stackOut = stackOut.next;
+
+ yi += width;
+ }
+ }
+
+ context.putImageData( imageData, top_x, top_y );
+
+ }
+
+ function BlurStack()
+ {
+ this.r = 0;
+ this.g = 0;
+ this.b = 0;
+ this.a = 0;
+ this.next = null;
+ }
+
+ // https://gist.github.com/mjackson/5311256
+
+ function rgbToHsl(r, g, b){
+ r /= 255, g /= 255, b /= 255;
+ var max = Math.max(r, g, b), min = Math.min(r, g, b);
+ var h, s, l = (max + min) / 2;
+
+ if(max == min){
+ h = s = 0; // achromatic
+ }else{
+ var d = max - min;
+ s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
+ switch(max){
+ case r: h = (g - b) / d + (g < b ? 6 : 0); break;
+ case g: h = (b - r) / d + 2; break;
+ case b: h = (r - g) / d + 4; break;
+ }
+ h /= 6;
+ }
+
+ return [h, s, l];
+ }
+
+ function hslToRgb(h, s, l){
+ var r, g, b;
+
+ if(s == 0){
+ r = g = b = l; // achromatic
+ }else{
+ var hue2rgb = function hue2rgb(p, q, t){
+ if(t < 0) t += 1;
+ if(t > 1) t -= 1;
+ if(t < 1/6) return p + (q - p) * 6 * t;
+ if(t < 1/2) return q;
+ if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
+ return p;
+ }
+
+ var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
+ var p = 2 * l - q;
+ r = hue2rgb(p, q, h + 1/3);
+ g = hue2rgb(p, q, h);
+ b = hue2rgb(p, q, h - 1/3);
+ }
+
+ return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
+ }
+
+ function lightBlur(hsl) {
+
+ // Adjust the luminance.
+ let lumCalc = 0.35 + (0.3 / hsl[2]);
+ if (lumCalc < 1) { lumCalc = 1; }
+ else if (lumCalc > 3.3) { lumCalc = 3.3; }
+ const l = hsl[2] * lumCalc;
+
+ // Adjust the saturation.
+ const colorful = 2 * hsl[1] * l;
+ const s = hsl[1] * colorful * 1.5;
+
+ return [hsl[0],s,l];
+
+ }
+
+ function darkBlur(hsl) {
+
+ // Adjust the saturation.
+ const colorful = 2 * hsl[1] * hsl[2];
+ const s = hsl[1] * (1 - hsl[2]) * 3;
+
+ return [hsl[0],s,hsl[2]];
+
+ }
+
+ // Set up the canvas.
+ const img = document.getElementById("blurImg");
+ const canvas = document.getElementById("mainCanvas");
+
+ const w = img.naturalWidth;
+ const h = img.naturalHeight;
+
+ canvas.style.width = w + "px";
+ canvas.style.height = h + "px";
+ canvas.width = w;
+ canvas.height = h;
+
+ const context = canvas.getContext("2d");
+ context.clearRect( 0, 0, w, h );
+ context.drawImage( img, 0, 0 );
+
+ // Get the image data from the context.
+ var imageData = context.getImageData(0,0,w,h);
+ var pix = imageData.data;
+
+ // Set the image function, if any.
+ var imageFunc;
+ var style = "${style}";
+ if (style == "dark") { imageFunc = darkBlur; }
+ else if (style == "light") { imageFunc = lightBlur; }
+
+ for (let i=0; i < pix.length; i+=4) {
+
+ // Convert to HSL.
+ let hsl = rgbToHsl(pix[i],pix[i+1],pix[i+2]);
+
+ // Apply the image function if it exists.
+ if (imageFunc) { hsl = imageFunc(hsl); }
+
+ // Convert back to RGB.
+ const rgb = hslToRgb(hsl[0], hsl[1], hsl[2]);
+
+ // Put the values back into the data.
+ pix[i] = rgb[0];
+ pix[i+1] = rgb[1];
+ pix[i+2] = rgb[2];
+
+ }
+
+ // Draw over the old image.
+ context.putImageData(imageData,0,0);
+
+ // Blur the image.
+ stackBlurCanvasRGB("mainCanvas", 0, 0, w, h, ${blur});
+
+ // Perform the additional processing for dark images.
+ if (style == "dark") {
+
+ // Draw the hard light box over it.
+ context.globalCompositeOperation = "hard-light";
+ context.fillStyle = "rgba(55,55,55,0.2)";
+ context.fillRect(0, 0, w, h);
+
+ // Draw the soft light box over it.
+ context.globalCompositeOperation = "soft-light";
+ context.fillStyle = "rgba(55,55,55,1)";
+ context.fillRect(0, 0, w, h);
+
+ // Draw the regular box over it.
+ context.globalCompositeOperation = "source-over";
+ context.fillStyle = "rgba(55,55,55,0.4)";
+ context.fillRect(0, 0, w, h);
+
+ // Otherwise process light images.
+ } else if (style == "light") {
+ context.fillStyle = "rgba(255,255,255,0.4)";
+ context.fillRect(0, 0, w, h);
+ }
+
+ // Return a base64 representation.
+ canvas.toDataURL();
+ `
+
+ // Convert the images and create the HTML.
+ let blurImgData = Data.fromPNG(img).toBase64String()
+ let html = `
+
+
+ `
+
+ // Make the web view and get its return value.
+ let view = new WebView()
+ await view.loadHTML(html)
+ let returnValue = await view.evaluateJavaScript(js)
+
+ // Remove the data type from the string and convert to data.
+ let imageDataString = returnValue.slice(22)
+ let imageData = Data.fromBase64String(imageDataString)
+
+ // Convert to image and crop before returning.
+ let imageFromData = Image.fromData(imageData)
+ return cropImage(imageFromData)
+}
+
+// Pixel sizes and positions for widgets on all supported phones.
+function phoneSizes() {
+ let phones = {
+
+ // 12 Pro Max
+ "2778": {
+ 小号: 510,
+ 中号: 1092,
+ 大号: 1146,
+ 左边: 96,
+ 右边: 678,
+ 顶部: 246,
+ 中间: 882,
+ 底部: 1518
+ },
+
+ // 12 and 12 Pro
+ "2532": {
+ 小号: 474,
+ 中号: 1014,
+ 大号: 1062,
+ 左边: 78,
+ 右边: 618,
+ 顶部: 231,
+ 中间: 819,
+ 底部: 1407
+ },
+
+ // 11 Pro Max, XS Max
+ "2688": {
+ 小号: 507,
+ 中号: 1080,
+ 大号: 1137,
+ 左边: 81,
+ 右边: 654,
+ 顶部: 228,
+ 中间: 858,
+ 底部: 1488
+ },
+
+ // 11, XR
+ "1792": {
+ 小号: 338,
+ 中号: 720,
+ 大号: 758,
+ 左边: 54,
+ 右边: 436,
+ 顶部: 160,
+ 中间: 580,
+ 底部: 1000
+ },
+
+
+ // 11 Pro, XS, X, 12 mini
+ "2436": {
+
+ x: {
+ 小号: 465,
+ 中号: 987,
+ 大号: 1035,
+ 左边: 69,
+ 右边: 591,
+ 顶部: 213,
+ 中间: 783,
+ 底部: 1353,
+ },
+
+ mini: {
+ 小号: 465,
+ 中号: 987,
+ 大号: 1035,
+ 左边: 69,
+ 右边: 591,
+ 顶部: 231,
+ 中间: 801,
+ 底部: 1371,
+ }
+
+ },
+
+ // Plus phones
+ "2208": {
+ 小号: 471,
+ 中号: 1044,
+ 大号: 1071,
+ 左边: 99,
+ 右边: 672,
+ 顶部: 114,
+ 中间: 696,
+ 底部: 1278
+ },
+
+ // SE2 and 6/6S/7/8
+ "1334": {
+ 小号: 296,
+ 中号: 642,
+ 大号: 648,
+ 左边: 54,
+ 右边: 400,
+ 顶部: 60,
+ 中间: 412,
+ 底部: 764
+ },
+
+
+ // SE1
+ "1136": {
+ 小号: 282,
+ 中号: 584,
+ 大号: 622,
+ 左边: 30,
+ 右边: 332,
+ 顶部: 59,
+ 中间: 399,
+ 底部: 399
+ },
+
+ // 11 and XR in Display Zoom mode
+ "1624": {
+ 小号: 310,
+ 中号: 658,
+ 大号: 690,
+ 左边: 46,
+ 右边: 394,
+ 顶部: 142,
+ 中间: 522,
+ 底部: 902
+ },
+
+ // Plus in Display Zoom mode
+ "2001" : {
+ 小号: 444,
+ 中号: 963,
+ 大号: 972,
+ 左边: 81,
+ 右边: 600,
+ 顶部: 90,
+ 中间: 618,
+ 底部: 1146
+ },
+ }
+ return phones
+}