### Starting a Simple HTTP Server - $server - JavaScript Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/network/server.md Shows how to start a simple HTTP server directly using $server.start(), serving files from a specified path and executing a handler function upon startup. Requires the $server and $app modules. ```JavaScript const server = $server.start({ port: 6060, path: "assets/website", handler: () => { $app.openURL("http://localhost:6060/index.html"); } }); ``` -------------------------------- ### Starting a Local Web Server with $http.startServer Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/foundation/network.md Starts a local HTTP server within JSBox, allowing it to serve local files and provide HTTP interfaces. Configurable by port and root path. ```js $http.startServer({ port: 5588, // port number path: "", // script root path handler: function(result) { const url = result.url; } }) ``` -------------------------------- ### Running an Addin by Name - JSBox $addin.run - JavaScript Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/addin/method.md Executes an installed addin (script) by its name. This starts the script's execution. ```javascript $addin.run("New Script") ``` -------------------------------- ### Perform HTTP GET Request (JSBox) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/quickstart/sample.md Executes an HTTP GET request to a specified URL using the JSBox HTTP API. Includes a handler function to process the response data. ```javascript $http.get({ url: 'https://docs.xteko.com', handler: function(resp) { const data = resp.data; } }) ``` -------------------------------- ### Show UI Alert (JSBox) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/quickstart/sample.md Displays a simple alert box to the user using the JSBox UI API. This is a basic example of interacting with the user interface. ```javascript // Show alert $ui.alert("Hello, World!") ``` -------------------------------- ### Handling Web View didStart Event Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/component/web.md Example of the `didStart` event handler, called when the web view begins loading a page. ```JavaScript didStart: function(sender, navigation) { } ``` -------------------------------- ### Example Proxy Configuration for $http Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/foundation/network.md Example JSON object structure for configuring proxy settings within an $http request. ```json { "proxy": { "HTTPEnable": true, "HTTPProxy": "", "HTTPPort": 0, "HTTPSEnable": true, "HTTPSProxy": "", "HTTPSPort": 0 } } ``` -------------------------------- ### Example Query Object Structure (JSBox JSON) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/context/method.md An example of the object structure returned by $context.query when the script is launched with URL parameters like `jsbox://runjs?file=demo.js&text=test`. ```json { "file": "demo.js", "text": "test" } ``` -------------------------------- ### Example Output Structure for ifa_data - JSON Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/foundation/network.md An example of the JSON structure returned by $network.ifa_data, showing byte counts for various network interfaces. ```json { "en0" : { "received" : 2581234688, "sent" : 469011456 }, "awdl0" : { "received" : 2231296, "sent" : 8180736 }, "utun0" : { "received" : 0, "sent" : 0 }, "pdp_ip1" : { "received" : 2048, "sent" : 2048 }, "pdp_ip0" : { "received" : 2215782400, "sent" : 211150848 }, "en2" : { "received" : 5859328, "sent" : 6347776 }, "utun2" : { "received" : 0, "sent" : 0 }, "lo0" : { "received" : 407684096, "sent" : 407684096 }, "utun1" : { "received" : 628973568, "sent" : 35312640 } } ``` -------------------------------- ### Starting Motion Updates with $motion in JavaScript Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/sdk/motion.md Starts tracking device motion updates using the $motion object. Configurable with an interval and a handler function to receive data updates. ```js $motion.startUpdates({ interval: 0.1, handler: function(resp) { } }) ``` -------------------------------- ### Example prefs.json Structure Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/foundation/prefs.md This example demonstrates the basic structure of a prefs.json file, including defining groups and various item types like string, boolean, and child nodes. It shows how to set titles, keys, types, and default values for preference items. ```json { "title": "SETTINGS", "groups": [ { "title": "GENERAL", "items": [ { "title": "USER_NAME", "type": "string", "key": "user.name", "value": "default user name" }, { "title": "AUTO_SAVE", "type": "boolean", "key": "auto.save", "value": true }, { "title": "OTHERS", "type": "child", "value": { "title": "OTHERS", "groups": [ ] } } ] } ] } ``` -------------------------------- ### Getting Installed Extensions with $file in JSBox Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/file/method.md Returns a list of all installed scripts or extensions. ```js const extensions = $file.extensions; ``` -------------------------------- ### Creating a New Server Instance - $server - JavaScript Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/network/server.md Demonstrates how to create a new server instance using $server.new() and start it with basic options like port. Requires the $server module. ```JavaScript const server = $server.new(); const options = { port: 6060, // Required bonjourName: "", // Optional bonjourType: "", // Optional }; server.start(options); ``` -------------------------------- ### Create UI Button (JSBox) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/quickstart/sample.md Renders a simple button element on the screen using the JSBox UI API. Defines its properties, layout constraints, and a tap event handler. ```javascript $ui.render({ views: [ { type: "button", props: { title: "Button" }, layout: function(make, view) { make.center.equalTo(view.super) make.width.equalTo(64) }, events: { tapped: function(sender) { $ui.toast("Tapped") } } } ] }) ``` -------------------------------- ### $calendar.create - Create Calendar Event - JavaScript Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/sdk/calendar.md Creates a new event in the system calendar. The example demonstrates creating an event with a title, start date, duration (3 hours), and notes. ```javascript $calendar.create({ title: "Hey!", startDate: new Date(), hours: 3, notes: "Hello, World!", handler: function(resp) { } }) ``` -------------------------------- ### Full UI Example with Web View $notify Communication in JSBox Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/component/web.md A comprehensive example building a simple image search UI with an input, button, and web view. It demonstrates how $notify is used within the web view's injected script to send data (image URL) back to a native events handler, which then downloads and shares the image. Includes basic search logic and UI layout. ```JavaScript $ui.render({ props: { title: "Doutu" }, views: [ { type: "button", props: { title: "Search" }, layout: function(make) { make.right.top.inset(10) make.size.equalTo($size(64, 32)) }, events: { tapped: function(sender) { search() } } }, { type: "input", props: { placeholder: "Please input keywords" }, layout: function(make) { make.top.left.inset(10) make.right.equalTo($("button").left).offset(-10) make.height.equalTo($("button")) }, events: { returned: function(sender) { search() } } }, { type: "web", props: { script: "for(var images=document.getElementsByTagName(\"img\"),i=0;i { const method = rules.method; const url = rules.url; // rules.headers, rules.path, rules.query; return "data"; // default, data, file, multipart, urlencoded } // Handler response handler.response = request => { const method = request.method; const url = request.url; return { type: "data", // default, data, file, error props: { html: "Hello!" // json: { // "status": 1, // "values": ["a", "b", "c"] // } } }; } // Handler async response handler.asyncResponse = (request, completion) => { const method = request.method; const url = request.url; completion({ type: "data", // default, data, file, error props: { html: "Hello!" // json: { // "status": 1, // "values": ["a", "b", "c"] // } } }); } ``` -------------------------------- ### Complete Web View Interaction Example (JSBox) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/component/web.md Provides a comprehensive example of building a UI with input, button, and web views. It illustrates how a script injected into the web view uses $notify to trigger a 'share' event in the native JSBox script, which then downloads and shares content. It also shows updating the web view URL from native code. ```JavaScript $ui.render({ props: { title: "斗图啦" }, views: [ { type: "button", props: { title: "搜索" }, layout: function(make) { make.right.top.inset(10) make.size.equalTo($size(64, 32)) }, events: { tapped: function(sender) { search() } } }, { type: "input", props: { placeholder: "输入关键字" }, layout: function(make) { make.top.left.inset(10) make.right.equalTo($("button").left).offset(-10) make.height.equalTo($("button")) }, events: { returned: function(sender) { search() } } }, { type: "web", props: { script: "for(var images=document.getElementsByTagName(\"img\"),i=0;i

Hey, there!

``` -------------------------------- ### Log to Console (JavaScript) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/quickstart/sample.md Logs a message to the console using the standard JavaScript console.info method. Useful for debugging and outputting information. ```javascript // Log to console console.info("Hello, World!") ``` -------------------------------- ### Getting All Preferences in JSBox Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/foundation/prefs.md This JavaScript code demonstrates how to retrieve all stored preference key-value pairs as an object using the $prefs.all() method. ```javascript const prefs = $prefs.all(); ``` -------------------------------- ### Rendering a Basic Button in JSBox (JavaScript) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/uikit/intro.md Demonstrates how to use `$ui.render` to create a simple button view in JSBox. The view object includes properties for type, title, layout using Masonry-like DSL, and a tap event handler. ```JavaScript $ui.render({ views: [ { type: "button", props: { title: "Button" }, layout: function(make, view) { make.center.equalTo(view.super) make.width.equalTo(64) }, events: { tapped: function(sender) { $ui.toast("Tapped") } } } ] }) ``` -------------------------------- ### Main Script Entry Point (main.js) Example Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/package/intro.md This JavaScript snippet demonstrates how the `main.js` file, serving as the main entry point for a JSBox package, can load other script modules located in the `scripts/` folder using the `require()` function and then call functions defined within those modules. ```JavaScript const app = require('./scripts/app'); app.sayHello(); ``` -------------------------------- ### Using $input.text for Quick Text Input (JSBox) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/component/input.md Provides an example of using the `$input.text` helper function to quickly prompt the user for text input via a popup, specifying keyboard type, placeholder, and a handler function for the result. ```JavaScript $input.text({ type: $kbType.number, placeholder: "Input a number", handler: function(text) { } }) ``` -------------------------------- ### Running an Addin with Query Parameters - JSBox $addin.run - JavaScript Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/addin/method.md Executes an installed addin by providing an object containing the addin's name and optional query parameters. The query parameters will be available in the running script via $context.query. ```javascript $addin.run({ name: "New Script", query: { "a": "b" } }) ``` -------------------------------- ### Opening Another Extension in JSBox (JavaScript) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/foundation/app.md Launches another installed JSBox script or extension using its filename or identifier. ```JavaScript $app.openExtension("demo.js") ``` -------------------------------- ### Get Installed Addins - JSBox $addin - JavaScript Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/addin/method.md Retrieves a list of all currently installed scripts (addins) in JSBox. The returned value is an array of objects, each representing a script with properties like name, category, url, data, etc. ```JavaScript const addins = $addin.list; ``` -------------------------------- ### Starting Network Pinging (JSBox $network) - JavaScript Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/foundation/network.md Initiates a ping operation to a specified host with configurable parameters like timeout, period, payload size, and TTL. Includes callback functions for various ping events. ```js $network.startPinging({ host: "google.com", timeout: 2.0, // default period: 1.0, // default payloadSize: 56, // default ttl: 49, // default didReceiveReply: function(summary) { }, didReceiveUnexpectedReply: function(summary) { }, didSendPing: function(summary) { }, didTimeout: function(summary) { }, didFail: function(error) { }, didFailToSendPing: function(response) { } }) ``` -------------------------------- ### Delete Addin by Name - JSBox $addin - JavaScript Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/addin/method.md Deletes an installed script from JSBox based on its name. This will remove the script created in the previous example. ```JavaScript $addin.delete("New Script") ``` -------------------------------- ### Opening URL with $quicklook (JavaScript) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/media/quicklook.md Opens a file preview from a given URL. An optional handler function can be provided to react when the preview is dismissed. ```javascript $quicklook.open({ url: "", handler: function() { // Handle dismiss action, optional } }) ``` -------------------------------- ### Zipping a Directory with $archiver in JSBox Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/extend/archiver.md Demonstrates the basic structure for compressing an entire directory into a ZIP file using the `directory` parameter. This is a placeholder example showing the required parameters (`directory`, `dest`, `handler`). ```JavaScript $archiver.zip({ directory: "", dest: "", handler: function(success) { } }) ``` -------------------------------- ### Rendering a Basic Button UI in JSBox Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/uikit/intro.md Demonstrates how to use `$ui.render` to create a simple UI containing a button. It shows how to define the view type, set properties like title, configure layout using the Masonry-like system, and handle tap events to display a toast message. ```JavaScript $ui.render({ views: [ { type: "button", props: { title: "Button" }, layout: function(make, view) { make.center.equalTo(view.super) make.width.equalTo(64) }, events: { tapped: function(sender) { $ui.toast("Tapped") } } } ] }) ``` -------------------------------- ### Preview Clipboard Content (JSBox) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/quickstart/sample.md Previews the current content of the clipboard using the JSBox UI API. It converts the clipboard items into a JSON string for display. ```javascript $ui.preview({ text: JSON.stringify($clipboard.items) }) ``` -------------------------------- ### Opening List of Items with $quicklook (JavaScript) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/media/quicklook.md Previews a list of items. All items in the list should be of the same type, either file paths or URLs. ```javascript $quicklook.open({ list: ["", "", ""] }) ``` -------------------------------- ### Using $props to Get Object Properties (JSBox) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/data/object.md Shows a simple example of calling the `$props` function, which is used in JSBox to retrieve all enumerable and non-enumerable own properties and inherited properties of a given object. ```JavaScript const props = $props("string"); ``` -------------------------------- ### Handling Web View didFail Event Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/component/web.md Example of the `didFail` event handler, triggered when the web view encounters an error during loading. ```JavaScript didFail: function(sender, navigation, error) { } ``` -------------------------------- ### Opening HTML Content with $quicklook (JavaScript) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/media/quicklook.md Previews an HTML string, rendering it as a web page. ```javascript $quicklook.open({ html: "

HTML

" }) ``` -------------------------------- ### Getting All Addins - JSBox $addin.list - JavaScript Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/addin/method.md Retrieves a list of all installed addins (scripts) in JSBox. The returned value is an array of objects, each representing an addin with properties like name, category, url, data, etc. ```javascript const addins = $addin.list; ``` -------------------------------- ### Handling Web View didFinish Event Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/component/web.md Example of the `didFinish` event handler, called when the web view successfully finishes loading a page. ```JavaScript didFinish: function(sender, navigation) { } ``` -------------------------------- ### Getting Current Playback Time with $audio in JSBox (JavaScript) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/media/audio.md Retrieves the current playback position of the audio in seconds using the JSBox $audio module. Returns a numerical value representing the time elapsed since the start of playback. ```javascript // 获取当前的播放时间 const offset = $audio.offset; ``` -------------------------------- ### Simplified prefs.json Structure Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/foundation/prefs.md This JSON example illustrates a simplified prefs.json structure when there is only a single group of settings. It shows how to define items directly under the root object and introduces the inline attribute for string type items. ```json { "title": "GENERAL", "items": [ { "title": "USER_NAME", "type": "string", "key": "user.name", "value": "default user name", "inline": true // inline edit, default is false } ] } ``` -------------------------------- ### Handling Web View didReceiveServerRedirect Event Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/component/web.md Example of the `didReceiveServerRedirect` event handler, triggered when the web view receives a server redirect. ```JavaScript didReceiveServerRedirect: function(sender, navigation) { } ``` -------------------------------- ### Handling Matrix Reorder Began (JSBox) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/component/matrix.md This function is called when a user initiates a reorder action on a matrix view item. It receives the `indexPath` of the item being reordered, allowing for any necessary setup or visual feedback at the start of the reorder process. ```javascript reorderBegan: function(indexPath) { } ``` -------------------------------- ### Rendering a Basic View with $ui.render (JSBox) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/uikit/view.md Demonstrates how to use the $ui.render function to create and display a simple 'view' component with specified properties (like background color) and layout constraints. Includes basic event handling. ```javascript $ui.render({ views: [ { type: "view", props: { bgcolor: $color("#FF0000") }, layout: function(make, view) { make.center.equalTo(view.super) make.size.equalTo($size(100, 100)) }, events: { tapped: function(sender) { } } } ] }) ``` -------------------------------- ### Listening for Server Events - $server - JavaScript Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/network/server.md Illustrates how to register listeners for various server lifecycle events such as didStart, didConnect, didDisconnect, etc., using the server.listen() method. Requires a server instance and the $delay and $app modules. ```JavaScript server.listen({ didStart: server => { $delay(1, () => { $app.openURL(`http://localhost:${port}`); }); }, didConnect: server => {}, didDisconnect: server => {}, didStop: server => {}, didCompleteBonjourRegistration: server => {}, didUpdateNATPortMapping: server => {} }); ``` -------------------------------- ### $calendar.fetch - Fetch Calendar Events - JavaScript Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/sdk/calendar.md Reads calendar events from the system calendar. Requires user authorization. The example fetches events starting from the current date for the next 3 days. You can specify the duration using 'hours' or calculate and provide 'endDate'. The response contains an 'events' array with detailed event objects. ```javascript $calendar.fetch({ startDate: new Date(), hours: 3 * 24, handler: function(resp) { const events = resp.events; } }) ``` -------------------------------- ### Sending a GET Request with $http.get Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/foundation/network.md Sends an HTTP GET request to a specified URL. This is a simplified version of $http.request where the method is fixed as GET. ```js $http.get({ url: "https://apple.com", handler: function(resp) { const data = resp.data; } }) ``` -------------------------------- ### Replaying Current UI Addin - JSBox $addin.replay - JavaScript Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/addin/method.md Replays the current running addin, specifically designed for UI scripts. This likely re-executes the UI setup or initial logic. ```javascript $addin.replay() ``` -------------------------------- ### Configuring Basic Picker - JSBox JavaScript Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/component/picker.md Shows the basic configuration structure for a 'picker' type in JSBox, including defining items and layout. This example configures three independent wheels suitable for selecting RGB color components. ```JavaScript { type: "picker", props: { items: Array(3).fill(Array.from(Array(256).keys())) }, layout: function(make) { make.left.top.right.equalTo(0) } } ``` -------------------------------- ### Getting Safari Items in Action Extension - JSBox Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/sdk/safari.md Gets items from Safari when using an Action Extension. The result is in JSON format. ```javascript const items = $safari.items; // JSON format ``` -------------------------------- ### Run Addin with Query - JSBox $addin - JavaScript Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/addin/method.md Executes an installed script by name and passes additional parameters via a query object (available from v1.15.0). The parameters will be accessible within the target script via `$context.query`. ```JavaScript $addin.run({ name: "New Script", query: { "a": "b" } }) ``` -------------------------------- ### Scan QR Code with Options and Cancel Handler (JSBox) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/extend/qrcode.md Starts a QR code scan with configurable options like camera selection and flash. Includes separate handlers for successful scan (returning the string) and user cancellation. ```js $qrcode.scan({ useFrontCamera: false, // Optional turnOnFlash: false, // Optional handler(string) { $ui.toast(string) }, cancelled() { $ui.toast("Cancelled") } }) ``` -------------------------------- ### Get Circular Image using $imagekit.circular (JavaScript) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/media/imagekit.md Gets a circular version of the input image. If the original image is not square, it will be centered and cropped. ```JavaScript const output = $imagekit.circular(source); ``` -------------------------------- ### Opening Plain Text with $quicklook (JavaScript) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/media/quicklook.md Previews a plain text string. ```javascript $quicklook.open({ text: "Hello, World!" }) ``` -------------------------------- ### Opening JSON Object with $quicklook (JavaScript) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/media/quicklook.md Previews a JSON string, which will be displayed with syntax highlighting. ```javascript $quicklook.open({ json: "{\"a\": [1, 2, true]}" }) ``` -------------------------------- ### Defining a Script Preference in JSON Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/foundation/prefs.md This JSON example shows how to define a preference item of type "script". Tapping this item in the settings view will execute the JavaScript code specified in the value string. ```json { "title": "TEST", "type": "script", "value": "require('scripts/test').runTest();" } ``` -------------------------------- ### Opening SQLite Database with $sqlite.open (JSBox) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/sqlite/usage.md Demonstrates how to open or create an SQLite database instance using a file path with the $sqlite.open function in JSBox. ```js const db = $sqlite.open("test.db"); ``` -------------------------------- ### Getting and setting keyboard height with $keyboard in JavaScript Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/keyboard/method.md Allows getting the current height of the keyboard or setting a new height. Setting the height should be done before the keyboard UI is displayed. ```JavaScript let height = $keyboard.height; $keyboard.height = 500; ``` -------------------------------- ### Getting Current Running Addin - JSBox $addin.current - JavaScript Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/addin/method.md Retrieves an object representing the addin that is currently running. This can be useful for getting information about the executing script. ```javascript const current = $addin.current; ``` -------------------------------- ### Starting Location Updates Tracking in JSBox Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/sdk/location.md Begins tracking the user's location updates continuously. Requires an options object with a `handler` function that is called whenever the location changes, providing latitude, longitude, and altitude. ```JavaScript $location.startUpdates({ handler: function(resp) { const lat = resp.lat; const lng = resp.lng; const alt = resp.alt; } }) ``` -------------------------------- ### Opening Binary Data with $quicklook (JavaScript) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/media/quicklook.md Previews binary data. It is recommended to specify the file type using the 'type' property (e.g., "jpg") for correct rendering. ```javascript $quicklook.open({ type: "jpg", data }) ``` -------------------------------- ### Uploading a File with $http.upload Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/foundation/network.md Uploads files using an HTTP request, typically for form-data uploads. Includes an example demonstrating picking a photo and uploading it to a service like qiniu. ```js $photo.pick({ handler: function(resp) { const image = resp.image; if (image) { $http.upload({ url: "http://upload.qiniu.com/", form: { token: "" }, files: [ { "image": image, "name": "file", "filename": "file.png" } ], progress: function(percentage) { }, handler: function(resp) { } }) } } }) ``` -------------------------------- ### Playing JSBox Video Playback Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/component/video.md Starts or resumes the playback of the video component selected by the '$("video")' selector. If the video is paused, it will resume from the paused position; if stopped, it will start from the beginning. ```JavaScript $("video").play() ``` -------------------------------- ### Playing Lottie Animation with Completion Handler in JSBox Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/component/lottie.md Starts the Lottie animation playback and registers a callback function using the 'handler' option to be executed when the animation finishes. ```javascript $("lottie").play({ handler: finished => { } }); ``` -------------------------------- ### Previewing Content in JSBox Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/uikit/method.md Shows how to use $ui.preview to quickly display content from a URL, HTML string, or plain text, with an optional title. ```JavaScript $ui.preview({ title: "URL", url: "https://images.apple.com/v/ios/what-is/b/images/performance_large.jpg" }) ``` -------------------------------- ### Accessing Widget Family with $widget.family (JavaScript) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/home-widget/method.md Get the current layout size of the widget (small, medium, large, extra large). While available directly, it's generally recommended to get this from the ctx object in the render function. Can be overridden for testing. ```javascript const family = $widget.family; // 0, 1, 2, 3 ``` ```javascript $widget.family = $widgetFamily.medium; ``` -------------------------------- ### JSBox: Creating UI and Opening URL with Runtime Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/runtime/intro.md This example demonstrates how to leverage Objective-C Runtime in JSBox to define a custom class, create UI elements like a button and label, and interact with iOS APIs (like UIApplication) by invoking methods dynamically. It also shows value conversion between JavaScript and Objective-C. ```JavaScript $define({ type: "MyHelper", classEvents: { open: function(scheme) { const url = $objc("NSURL").invoke("URLWithString", scheme); $objc("UIApplication").invoke("sharedApplication.openURL", url) } } }) $ui.render({ views: [ { type: "button", props: { bgcolor: $objc("UIColor").invoke("blackColor").jsValue(), titleColor: $color("#FFFFFF").ocValue().jsValue(), title: "WeChat" }, layout: function(make, view) { make.center.equalTo(view.super) make.size.equalTo($size(100, 32)) }, events: { tapped: function(sender) { $objc("MyHelper").invoke("open", "weixin://") } } } ] }) const window = $ui.window.ocValue(); const label = $objc("UILabel").invoke("alloc.init"); label.invoke("setTextAlignment", 1) label.invoke("setText", "Runtime") label.invoke("setFrame", { x: $device.info.screen.width * 0.5 - 50, y: 240, width: 100, height: 32 }) window.invoke("addSubview", label) ``` -------------------------------- ### Getting Widget Display Size with $widget.displaySize Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/home-widget/method.md Returns the display size of the current widget instance as an object with width and height. It's generally recommended to get this from the 'ctx' parameter in the render function. Can be simulated for testing by setting $widget.family. ```javascript const size = $widget.displaySize; // size.width, size.height ``` ```javascript $widget.family = $widgetFamily.medium; ``` -------------------------------- ### Get or Set Widget Height (JSBox) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/widget/method.md Demonstrates how to retrieve the current height of the widget using $widget.height and how to set a new height value. Requires the JSBox environment. ```js // Get const height = $widget.height; // Set $widget.height = 400; ``` -------------------------------- ### Creating a Basic JSBox Code View (JavaScript) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/component/code.md Demonstrates how to create a simple code view component using $ui.render, setting its type to "code" and providing initial text content. It fills the available layout space. ```js $ui.render({ views: [ { type: "code", props: { text: "const value = 100" }, layout: $layout.fill } ] }); ``` -------------------------------- ### Retrieving Gallery Subviews in JSBox (JS) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/component/gallery.md This snippet demonstrates how to access the subviews (items) within a gallery view in JSBox. It shows how to get all item views using 'itemViews' and how to get a specific view by its index using 'viewWithIndex(index)'. ```js const views = $("gallery").itemViews; // All views const view = $("gallery").viewWithIndex(0); // The first view ``` -------------------------------- ### Presenting Menu Options in JSBox Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/uikit/method.md Illustrates how to display a menu with a list of string items and define handlers for item selection and dismissal. ```JavaScript $ui.menu({ items: ["A", "B", "C"], handler: function(title, idx) { }, finished: function(cancelled) { } }) ``` -------------------------------- ### Using $input.speech for Speech-to-Text (JSBox) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/component/input.md Demonstrates how to use the `$input.speech` helper function to initiate a speech-to-text session, optionally setting locale and auto-finish behavior, and providing a handler for the transcribed text. ```JavaScript $input.speech({ locale: "en-US", // Optional autoFinish: false, // Optional handler: function(text) { } }) ``` -------------------------------- ### Getting Widget Family Size with $widget.family Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/home-widget/method.md Returns the current size of the widget (0: small, 1: medium, 2: large, 3: extra large on iPadOS 15). It's generally recommended to get this from the 'ctx' parameter in the render function. Can be set for testing in the main app. ```javascript const family = $widget.family; // 0, 1, 2, 3 ``` ```javascript $widget.family = $widgetFamily.medium; ``` -------------------------------- ### Getting the hex code of a color in JSBox Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/object/color.md Retrieves the hexadecimal string representation of a color object. ```javascript const hexCode = color.hexCode; // -> "#00eeee" ``` -------------------------------- ### Defining a Basic Web View in JSBox Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/component/web.md Demonstrates the minimal configuration for rendering a website using the `web` type view in JSBox, specifying the URL in the `props`. ```JavaScript { type: "web", props: { url: "https://www.apple.com" }, layout: $layout.fill } ``` -------------------------------- ### Handling $text.speech Events (JavaScript) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/extend/text.md Shows how to attach event handlers to the $text.speech function to react to different states of the speech synthesis process, such as start, finish, pause, continue, and cancel. ```JavaScript $text.speech({ text: "Hello, World!", events: { didStart: (sender) => {}, didFinish: (sender) => {}, didPause: (sender) => {}, didContinue: (sender) => {}, didCancel: (sender) => {}, } }) ``` -------------------------------- ### Share Content to QQ using $share.qq Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/extend/share.md Shows how to share content (like an image or text) directly to QQ using the dedicated API. The API automatically detects the content type. ```js $share.qq(image) ``` -------------------------------- ### Getting text after cursor with $keyboard in JavaScript Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/keyboard/method.md Retrieves the text located after the current cursor position in the input field. ```JavaScript const textAfterInput = $keyboard.textAfterInput; ``` -------------------------------- ### Getting text before cursor with $keyboard in JavaScript Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/keyboard/method.md Retrieves the text located before the current cursor position in the input field. ```JavaScript const textBeforeInput = $keyboard.textBeforeInput; ``` -------------------------------- ### Creating a Basic Matrix View (JSBox) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/component/matrix.md Demonstrates the basic structure for defining a 'matrix' view in JSBox, including columns, item height, spacing, and a simple template for items with a label. ```js { type: "matrix", props: { columns: 4, itemHeight: 88, spacing: 5, template: { props: {}, views: [ { type: "label", props: { id: "label", bgcolor: $color("#474b51"), textColor: $color("#abb2bf"), align: $align.center, font: $font(32) }, layout: $layout.fill } ] } }, layout: $layout.fill } ``` -------------------------------- ### Getting WLAN Address in JSBox Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/foundation/device.md Retrieves the device's WLAN (Wi-Fi) MAC address. ```javascript const address = $device.wlanAddress; ``` -------------------------------- ### Creating a Range with $range (JavaScript) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/function/index.md Creates a range object with a specified location (start index) and length. ```javascript const range = $range(0, 10); ``` -------------------------------- ### Getting Objective-C Protocol in JSBox Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/function/index.md Retrieves a specific Objective-C protocol definition by its name using the $get_protocol function. ```JavaScript const p = $get_protocol(name); ``` -------------------------------- ### Rendering a Basic View in JSBox Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/uikit/view.md Demonstrates how to use the $ui.render function to create a simple red 'view' component. It includes setting background color, defining layout constraints using Auto Layout syntax, and adding a basic tap event handler. ```javascript $ui.render({ views: [ { type: "view", props: { bgcolor: $color("#FF0000") }, layout: function(make, view) { make.center.equalTo(view.super) make.size.equalTo($size(100, 100)) }, events: { tapped: function(sender) { } } } ] }) ``` -------------------------------- ### Getting Root Path with $file in JSBox Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/file/method.md Returns the absolute path to the application's documents folder. ```js const rootPath = $file.rootPath; ``` -------------------------------- ### Localization Strings File Format Example Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/package/intro.md This snippet shows the key-value format used in `.strings` files within the `strings/` folder for providing localized text. Each line maps an English key (in double quotes) to its localized value (also in double quotes), separated by an equals sign and terminated by a semicolon. ```Localization Strings "OK" = "好的"; "DONE" = "完成"; "HELLO_WORLD" = "你好,世界!"; ``` -------------------------------- ### Getting Absolute Path with $file in JSBox Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/file/method.md Returns the absolute path representation for a given relative path. ```js const absolutePath = $file.absolutePath(path); ``` -------------------------------- ### Creating Color from Hex - JSBox - JavaScript Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/function/index.md Creates a color object from a hexadecimal string representation. The string should start with '#'. ```javascript const color = $color("#00EEEE"); ``` -------------------------------- ### Executing Simple Script with Promise ($browser.exec, JavaScript) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/extend/browser.md Shows a concise way to execute a simple JavaScript expression using `$browser.exec` and handle the result asynchronously with `await` and Promises. ```JavaScript var result = await $browser.exec("return 1 + 1;"); ``` -------------------------------- ### Creating a Basic JSBox Stack View (JS) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/component/stack.md Demonstrates how to create a basic stack view using `$ui.render`. Views intended for the stack must be placed inside the `stack.views` property, not directly under the main `views` array. Configures spacing and distribution. ```javascript $ui.render({ views: [ { type: "stack", props: { spacing: 10, distribution: $stackViewDistribution.fillEqually, stack: { views: [ { type: "label", props: { text: "Left", align: $align.center, bgcolor: $color("silver") } }, { type: "label", props: { text: "Center", align: $align.center, bgcolor: $color("aqua") } }, { type: "label", props: { text: "Right", align: $align.center, bgcolor: $color("lime") } } ] } }, layout: $layout.fill } ] }); ``` -------------------------------- ### Stopping a Local Web Server with $http.stopServer Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/foundation/network.md Stops the local HTTP server previously started by $http.startServer. ```js $http.stopServer() ``` -------------------------------- ### Getting Chart Height (JSBox) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/component/chart.md Asynchronously retrieves the current height of the chart view using the getHeight method. ```js let height = await chart.getHeight(); ``` -------------------------------- ### Injecting JavaScript into Web View via Script Prop Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/component/web.md Demonstrates how to inject and execute JavaScript code after the web page finishes loading using the `script` property in `props`. Examples show using both a function and an escaped string. ```JavaScript props: { script: function() { var images = document.getElementsByTagName("img") for (var i=0; i { return { type: "text", props: { text: "Hello, World!" } } } }); ``` -------------------------------- ### Getting Image Info with $imagekit.info - JSBox Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/media/imagekit.md Retrieves information about an image, including its width, height, orientation, scale, and other properties. ```javascript const info = $imagekit.info(source); // width, height, orientation, scale, props ``` -------------------------------- ### Defining Dynamic Widget Options in JSBox (JSON) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/home-widget/intro.md This JSON structure defines a list of options that will appear in the JSBox widget configuration interface when selecting a script package. Place this structure in a file named 'widget-options.json' at the root of the script package. Each object in the array requires a 'name' for display and a 'value' which will be passed to the script as $widget.inputValue. ```JSON [ { "name": "Option 1", "value": "Value 1" }, { "name": "Option 2", "value": "Value 2" } ] ``` -------------------------------- ### Getting selected text with $keyboard in JavaScript Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/keyboard/method.md Retrieves the text that is currently selected in the input field. This property is only available on iOS 11 and later. ```JavaScript const selectedText = $keyboard.selectedText; ``` -------------------------------- ### Handling the Ready Event for Views in JSBox Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/uikit/view.md Demonstrates how to define a handler function for the 'ready' event, which is triggered when a view is fully initialized and ready. ```JavaScript ready: function(sender) { } ``` -------------------------------- ### Defining Namespace Prefix with $xml (JavaScript) Source: https://github.com/cyanzhong/jsbox-docs/blob/master/docs/en/extend/xml.md Shows how to define a prefix for a namespace on the XML Document object using the definePrefix method, mapping a short prefix to a full namespace URI. ```JavaScript doc.definePrefix({ "prefix": "prefix", "namespace": "namespace" }); ```