Merge pull request #2745 from stweedo/master

+settings for UI, less IO r/w, rm timeout from eval
master
Gordon Williams 2023-05-12 10:43:41 +01:00 committed by GitHub
commit 01d4cea940
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 244 additions and 106 deletions

View File

@ -30,14 +30,12 @@ Graphics.prototype.setFontRighteous = function() {
);
};
// Load and set default appSettings
let teletextColors = ["#000", "#f00", "#0f0", "#ff0", "#00f", "#f0f", "#0ff", "#fff"];
let defaultAppSettings = Object.assign({
color: teletextColors[6],
theme: 'light',
enableSuffix: true,
enableLeadingZero: false,
}, require('Storage').readJSON("shadowclk.json", true) || {});
let appSettings = require("Storage").readJSON("shadowclk.json", 1) || {};
let settings = require("Storage").readJSON("setting.json", 1) || {};
let is12Hour = settings["12hour"] !== undefined ? settings["12hour"] : false;
let color = appSettings.color !== undefined ? appSettings.color : "#0ff";
let enableLeadingZero = appSettings.enableLeadingZero !== undefined ? appSettings.enableLeadingZero : false;
let enableSuffix = appSettings.enableSuffix !== undefined ? appSettings.enableSuffix : true;
// Draw the time and date
(function () {
@ -48,36 +46,35 @@ let defaultAppSettings = Object.assign({
var y = g.getHeight() / 2;
g.reset().clearRect(Bangle.appRect);
var date = new Date();
var appSettings = require("Storage").readJSON("shadowclk.json", 1) || defaultAppSettings;
var settings = require("Storage").readJSON("setting.json", 1) || {};
var is12HourFormat = settings["12hour"];
var hour = date.getHours();
var minutes = String(date.getMinutes()).padStart(2, '0');
// Handle 12-hour format
if (is12HourFormat) {
if (is12Hour) {
hour = hour % 12 || 12; // Convert 0 to 12 for 12-hour format
} else {
// If the leading zero option is enabled and hour is less than 10, add leading zero
if (appSettings.enableLeadingZero && hour < 10) {
if (enableLeadingZero && hour < 10) {
hour = '0' + hour;
}
}
var timeStr = hour + ':' + minutes;
// Handle midnight in 12-hour format specifically
if (is12HourFormat && hour === 0) {
if (is12Hour && hour === 0) {
timeStr = '12' + timeStr.substring(2);
}
// Print time in selected color and then the outline
var color = appSettings.color;
g.setFontAlign(0, 0).setFont("LondrinaSolid").setColor(color).drawString(timeStr, x - 1, y);
g.reset().setFontAlign(0, 0).setFont("LondrinaShadow").drawString(timeStr, x - 1, y);
// Get full date and format it
var locale = require("locale");
var dayOfMonth = date.getDate();
var month = locale.month(date, 1).slice(0, 1).toUpperCase() + locale.month(date, 1).slice(1).toLowerCase();
var year = date.getFullYear();
var dayOfMonthStr = dayOfMonth.toString();
if (appSettings.enableSuffix) {
if (enableSuffix) {
var suffix = "";
if (dayOfMonth === 1 || dayOfMonth === 21 || dayOfMonth === 31) {
suffix = "st";
@ -90,11 +87,10 @@ let defaultAppSettings = Object.assign({
}
dayOfMonthStr += suffix;
}
// Combine and print date string
var dayOfWeek = locale.dow(date, 0).slice(0, 1).toUpperCase() + locale.dow(date, 0).slice(1).toLowerCase();
var dateStr = month + " " + dayOfMonthStr + ", " + year + "\n" + dayOfWeek;
g.setFontAlign(0, 0).setFont("Righteous").drawString(dateStr, x, y + 56);
// Time interval set to redraw every 60 seconds
if (drawTimeout) clearTimeout(drawTimeout);
drawTimeout = setTimeout(() => {
drawTimeout = undefined;

View File

@ -6,14 +6,30 @@
<link rel="stylesheet" href="../../css/spectre.min.css">
<link href="https://fonts.googleapis.com/css2?family=Londrina+Solid&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Londrina+Shadow&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Righteous&display=swap" rel="stylesheet"> <title>3-Bit Color Picker</title>
<link href="https://fonts.googleapis.com/css2?family=Righteous&display=swap" rel="stylesheet">
<title>Shadow Clock Customizer</title>
<style>
.underlined-heading {
position: relative;
padding-bottom: 5px;
}
.underlined-heading::after {
content: '';
position: absolute;
left: 0;
bottom: 0;
width: 100%;
border-bottom: 5px solid;
}
.main-container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100vh;
padding-bottom: 100px;
}
.color-button {
@ -71,12 +87,39 @@
display: block;
}
#toggle-bg {
margin-top: 20px;
.button-container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 360px;
margin-top: 10px;
}
.button-row {
display: flex;
justify-content: space-between;
width: 100%;
margin-top: 5px;
}
.btn {
flex-grow: 1;
flex-shrink: 1;
flex-basis: 0;
margin: 5px;
width: 160px;
}
#upload {
width: 150px;
}
#upload-container {
margin-top: 20px;
display: flex;
justify-content: center;
width: 160px;
}
#message-container {
@ -87,23 +130,43 @@
</style>
</head>
<body>
<script src="../../core/lib/interface.js"></script>
<div class="main-container">
<h1>3-Bit Color Picker</h1>
<h1 class="underlined-heading">Clock Customizer</h1>
<div id="color-buttons-container"></div>
<button id="toggle-bg" class="btn btn-primary" onclick="toggleBackground()">Light/Dark</button>
<div class="button-container">
<div class="button-row">
<button id="toggle-hour-format" class="btn btn-primary" onclick="toggleHourFormat()">Time Mode: 24 Hour</button>
<button id="toggle-bg" class="btn btn-primary" onclick="toggleBackground()">Theme: Light</button>
</div>
<div class="button-row">
<button id="toggle-leading-zero" class="btn btn-primary" onclick="toggleLeadingZero()">Leading Zero:
OFF</button>
<button id="toggle-suffix" class="btn btn-primary" onclick="toggleSuffix()">Suffix: ON</button>
</div>
</div>
<div id="preview-box">
<canvas id="preview-canvas" width="176" height="176"></canvas>
</div>
<div id="upload-container">
<button id="upload" class="btn btn-primary">Upload</button>
</div>
<div id="message-container">
<div id="message"></div>
</div>
</div>
<script>
const messageDiv = document.getElementById('message');
// Initialize app and system settings
let selectedColor = "#0ff";
let isDarkBg = false;
let leadingZero = false;
let prevLeadingZeroState = false;
let suffix = true;
let is12Hour = false;
// Create and add color buttons to the UI
let colors = ['#000', '#f00', '#0f0', '#ff0', '#00f', '#f0f', '#0ff', '#fff'];
let colorButtonsContainer = document.getElementById('color-buttons-container');
@ -120,25 +183,88 @@
});
});
// Format the current time in the desired format
let leadingZeroButton = document.getElementById('toggle-leading-zero');
let hourFormatButton = document.getElementById('toggle-hour-format');
let suffixButton = document.getElementById('toggle-suffix');
let bgButton = document.getElementById('toggle-bg');
// Function to update the button text based on the current state
function updateButtonState() {
if (leadingZeroButton.disabled) {
leadingZeroButton.textContent = prevLeadingZeroState ? 'Leading Zero: ON' : 'Leading Zero: OFF';
} else {
leadingZeroButton.textContent = leadingZero ? 'Leading Zero: ON' : 'Leading Zero: OFF';
}
hourFormatButton.textContent = is12Hour ? 'Time Mode: 12 Hour' : 'Time Mode: 24 Hour';
suffixButton.textContent = suffix ? 'Suffix: ON' : 'Suffix: OFF';
bgButton.textContent = isDarkBg ? 'Theme: Dark' : 'Theme: Light';
if (is12Hour) {
prevLeadingZeroState = leadingZero; // Store the state before disabling
leadingZeroButton.disabled = true;
leadingZeroButton.textContent = prevLeadingZeroState ? 'Leading Zero: ON' : 'Leading Zero: OFF';
} else {
leadingZero = prevLeadingZeroState; // Retrieve the stored state
leadingZeroButton.disabled = false;
leadingZeroButton.textContent = leadingZero ? 'Leading Zero: ON' : 'Leading Zero: OFF';
}
}
function toggleLeadingZero() {
if (!is12Hour) { // Only allow toggle if in 24-hour mode
leadingZero = !leadingZero;
prevLeadingZeroState = leadingZero; // Update previous state on each toggle
updateButtonState();
drawText(selectedColor);
}
}
function toggleHourFormat() {
is12Hour = !is12Hour;
updateButtonState(); // This will also correctly update leadingZero
drawText(selectedColor);
}
// Toggle the background color between dark and light
function toggleBackground() {
isDarkBg = !isDarkBg; // Toggle the background state
let previewBox = document.getElementById("preview-box");
previewBox.style.backgroundColor = isDarkBg ? "black" : "white";
updateButtonState();
drawText(selectedColor); // Redraw the text with updated color
}
function toggleSuffix() {
suffix = !suffix;
document.getElementById("toggle-suffix").textContent = `Suffix: ${suffix ? 'On' : 'Off'}`;
updateButtonState();
drawText(selectedColor);
}
function formatTime(date) {
let hours = date.getHours();
let minutes = date.getMinutes();
let formattedHours = hours < 10 ? `${hours}` : `${hours}`;
// If 12 hour format is selected, adjust hours
if (is12Hour) {
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12' in 12h format
}
let formattedHours = (!is12Hour && leadingZero && hours < 10) ? `0${hours}` : `${hours}`;
let formattedMinutes = minutes < 10 ? `0${minutes}` : `${minutes}`;
return `${formattedHours}:${formattedMinutes}`;
}
// Get the current date as a formatted string
function getCurrentDate() {
function getCurrentDate(suffix) {
let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
let suffixes = ["st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "st"];
let date = new Date();
let month = months[date.getMonth()];
let day = date.getDate();
let suffix = suffixes[day - 1];
let suffixString = suffix ? suffixes[day - 1] : '';
let year = date.getFullYear();
return `${month} ${day}${suffix}, ${year}`;
return `${month} ${day}${suffixString}, ${year}`;
}
// Get the current day of the week as a string
@ -148,14 +274,6 @@
return days[date.getDay()];
}
// Toggle the background color between dark and light
function toggleBackground() {
isDarkBg = !isDarkBg; // Toggle the background state
let previewBox = document.getElementById("preview-box");
previewBox.style.backgroundColor = isDarkBg ? "black" : "white";
drawText(selectedColor); // Redraw the text with updated color
}
// Draw the time, date, and day of the week on the canvas
function drawText(color) {
let canvas = document.getElementById("preview-canvas");
@ -198,10 +316,10 @@
ctx.fillText(currentTime, xPos, yPos);
// Set the font for the date
ctx.font = "16px Righteous";
ctx.font = "13px Righteous";
// Get the current date
let currentDate = getCurrentDate();
let currentDate = getCurrentDate(suffix);
// Measure the date width and calculate the horizontal position
let dateWidth = ctx.measureText(currentDate).width;
@ -219,7 +337,7 @@
xPos = (canvas.width - dayWidth) / 2;
// Draw the day of the week
ctx.fillText(currentDay, xPos, yPos + 18);
ctx.fillText(currentDay, xPos, yPos + 12);
}
// Converts a hexadecimal color code to a 16-bit integer value.
@ -257,7 +375,7 @@
}
// Save the provided theme to Bangle.js storage and set Shadow Clock as the default clock
function saveThemeToSettings(theme) {
function saveThemeToSettings(themeColors) {
Puck.eval('[require("Storage").readJSON("setting.json", true)]', (dataArray) => {
let data = dataArray ? dataArray[0] : null;
if (data) {
@ -266,10 +384,13 @@
data.theme = {};
}
// Save all theme values
for (let key in theme) {
data.theme[key] = theme[key];
for (let key in themeColors) {
data.theme[key] = themeColors[key];
}
data.clock = "shadowclk.app.js"; // Set Shadow Clock as default
// Save settings for 12 or 24 hour mode
data["12hour"] = is12Hour;
// Set Shadow Clock as default
data.clock = "shadowclk.app.js";
Puck.write(`require("Storage").write("setting.json", ${JSON.stringify(data)});\n`, (result) => {
console.log('Theme saved:', result);
});
@ -277,42 +398,31 @@
});
}
// Initialize color and theme settings
let selectedColor = "#0ff";
let isDarkBg = false;
// Load settings from Bangle.js storage
function loadSettings(callback) {
// Set a timeout for loading the settings
const timeout = new Promise((_, reject) =>
setTimeout(() => reject(new Error("Timeout occurred")), 1000)
);
// Load settings from Bangle.js storage
const loadSettingsFromStorage = new Promise((resolve) => {
Puck.eval('[require("Storage").readJSON("shadowclk.json", true)]', (dataArray) => {
let data = dataArray ? dataArray[0] : null;
if (data) {
// Apply color and theme from JSON
const { color, theme } = data;
selectedColor = color;
isDarkBg = theme === "dark";
// Apply color, theme, enableLeadingZero, enableSuffix and timeMode from JSON
let { color, theme, enableLeadingZero, enableSuffix, enable12Hour } = data;
selectedColor = color !== undefined ? color : selectedColor;
isDarkBg = theme !== undefined ? (theme === "dark") : isDarkBg;
// Use the JSON values if they exist, otherwise use the current values
leadingZero = enableLeadingZero !== undefined ? enableLeadingZero : leadingZero;
prevLeadingZeroState = leadingZero; // Store the current state
suffix = enableSuffix !== undefined ? enableSuffix : suffix;
is12Hour = enable12Hour !== undefined ? enable12Hour : is12Hour; // Update the time mode from the settings
displayMessage("Previous settings loaded.", 3000);
} else {
// Use default values if there is no data for color and theme
selectedColor = "#0ff";
isDarkBg = false;
// If no JSON data, load defaults
selectedColor = selectedColor;
isDarkBg = isDarkBg;
leadingZero = leadingZero;
prevLeadingZeroState = leadingZero;
suffix = suffix;
is12Hour = is12Hour;
displayMessage("Defaults loaded.", 3000);
}
resolve();
});
});
// Execute the callback after loading the settings, or use default values in case of a timeout or error
Promise.race([loadSettingsFromStorage, timeout])
.then(() => callback())
.catch((error) => {
console.error(error);
// Use default values in case of a timeout or error
selectedColor = "#0ff";
isDarkBg = false;
updateButtonState(); // Update button state regardless
callback();
});
}
@ -341,19 +451,25 @@
}, timeout);
}
// Attach an event listener to the 'upload' button to save theme and color settings to Bangle.js storage
// Attach an event listener to the 'upload' button to save color and theme settings to Bangle.js storage
document.getElementById("upload").addEventListener("click", function () {
// Save theme settings to Bangle.js
let themeColors = createThemeColors(isDarkBg);
saveThemeToSettings(themeColors);
// Save Shadow Clock color setting
// Save Shadow Clock app setting
let data = {
color: selectedColor,
theme: isDarkBg ? "dark" : "light"
theme: isDarkBg ? "dark" : "light",
enableLeadingZero: leadingZero,
enableSuffix: suffix,
enable12Hour: is12Hour
};
// Write the updated settings back to shadowclk.json
Puck.write(`require("Storage").write("shadowclk.json", ${JSON.stringify(data)});\n`, (result) => {
console.log('Color saved:', result);
console.log('App settings saved:', result);
});
// Display the message using displayMessage function
displayMessage('Configuration sent...<br>Hold button on Bangle.js', 5000);
});
@ -363,7 +479,7 @@
return Promise.all([
document.fonts.load('81px Londrina Solid'),
document.fonts.load('81px Londrina Shadow'),
document.fonts.load('16px Righteous')
document.fonts.load('13px Righteous')
]);
}

View File

@ -1,6 +1,7 @@
(function(back) {
let teletextColors = ["#000", "#f00", "#0f0", "#ff0", "#00f", "#f0f", "#0ff", "#fff"];
let teletextColorNames = ["Black", "Red", "Green", "Yellow", "Blue", "Magenta", "Cyan", "White"];
let sysSettings = require('Storage').readJSON("setting.json", 1) || {};
// Load and set default settings
let appSettings = Object.assign({
@ -8,14 +9,9 @@
theme: 'light',
enableSuffix: true,
enableLeadingZero: false,
enable12Hour: '24hour' // default time mode
}, require('Storage').readJSON("shadowclk.json", true) || {});
// Save settings to storage
function writeSettings() {
require('Storage').writeJSON("shadowclk.json", appSettings);
}
// Colors from 'Light BW' and 'Dark BW' themes
function createThemeColors(mode) {
let cl = x => g.setColor(x).getColor();
@ -69,15 +65,36 @@
// Read the current system theme
function getCurrentTheme() {
let s = require('Storage').readJSON("setting.json", 1) || {};
if (!s.theme) {
if (!sysSettings.theme) {
return appSettings.theme; // fallback to appSettings.theme (light or dark)
}
return s.theme.dark ? 'dark' : 'light';
return sysSettings.theme.dark ? 'dark' : 'light';
}
// Read the current time mode
function getCurrentTimeMode() {
if (!sysSettings['12hour']) {
return appSettings.enable12Hour; // fallback to appSettings.enable12Hour
}
return sysSettings['12hour'] ? '12hour' : '24hour';
}
// Save settings to storage
function writeSettings() {
appSettings.enable12Hour = appSettings.enable12Hour === '12hour' ? '12hour' : '24hour';
require('Storage').writeJSON("shadowclk.json", appSettings);
}
// Save time mode to system settings
function writeTimeModeSetting() {
sysSettings['12hour'] = appSettings.enable12Hour === '12hour';
require('Storage').writeJSON("setting.json", sysSettings);
}
function showMenu() {
appSettings.theme = getCurrentTheme();
appSettings.enable12Hour = getCurrentTimeMode();
E.showMenu({
"": {
"title": "Shadow Clock"
@ -115,6 +132,15 @@
appSettings.enableLeadingZero = v;
writeSettings();
}
},
'Time Mode:': {
value: (appSettings.enable12Hour === '12hour'),
format: v => v ? '12 Hr' : '24 Hr',
onchange: v => {
appSettings.enable12Hour = v ? '12hour' : '24hour';
writeSettings();
writeTimeModeSetting();
}
}
});
}