Skip to content

Commit

Permalink
refactor(core&api): hide internal functions and resuse them in api.js
Browse files Browse the repository at this point in the history
ref: #7756
  • Loading branch information
amrbashir committed Oct 2, 2023
1 parent 1bce739 commit 0de1429
Show file tree
Hide file tree
Showing 16 changed files with 149 additions and 178 deletions.
120 changes: 60 additions & 60 deletions core/tauri/scripts/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,48 +7,46 @@
return window.crypto.getRandomValues(new Uint32Array(1))[0]
}

if (!window.__TAURI__) {
Object.defineProperty(window, '__TAURI__', {
value: {}
})
}

const osName = __TEMPLATE_os_name__

window.__TAURI__.convertFileSrc = function convertFileSrc(filePath, protocol = 'asset') {
const path = encodeURIComponent(filePath)
return osName === 'windows' || osName === 'android'
? `http://${protocol}.localhost/${path}`
: `${protocol}://localhost/${path}`
}
Object.defineProperties(window.__TAURI__.__INTERNALS__, 'convertFileSrc', {
value: function (filePath, protocol = 'asset') {
const path = encodeURIComponent(filePath)
return osName === 'windows' || osName === 'android'
? `http://${protocol}.localhost/${path}`
: `${protocol}://localhost/${path}`
}
})

window.__TAURI__.transformCallback = function transformCallback(
callback,
once
) {
var identifier = uid()
var prop = `_${identifier}`
Object.defineProperties(window.__TAURI__.__INTERNALS__, 'transformCallback', {
value: function transformCallback(
callback,
once
) {
var identifier = uid()
var prop = `_${identifier}`

Object.defineProperty(window, prop, {
value: (result) => {
if (once) {
Reflect.deleteProperty(window, prop)
}
Object.defineProperty(window, prop, {
value: (result) => {
if (once) {
Reflect.deleteProperty(window, prop)
}

return callback && callback(result)
},
writable: false,
configurable: true
})
return callback && callback(result)
},
writable: false,
configurable: true
})

return identifier
}
return identifier
}
});

const ipcQueue = []
let isWaitingForIpc = false

function waitForIpc() {
if ('__TAURI_IPC__' in window) {
if (window.__TAURI__?.__INTERNALS__?.ipc) {
for (const action of ipcQueue) {
action()
}
Expand All @@ -57,35 +55,37 @@
}
}

window.__TAURI_INVOKE__ = function invoke(cmd, payload = {}, options) {
return new Promise(function (resolve, reject) {
const callback = window.__TAURI__.transformCallback(function (r) {
resolve(r)
delete window[`_${error}`]
}, true)
const error = window.__TAURI__.transformCallback(function (e) {
reject(e)
delete window[`_${callback}`]
}, true)
Object.defineProperties(window.__TAURI__.__INTERNALS__, 'invoke', {
value: function (cmd, payload = {}, options) {
return new Promise(function (resolve, reject) {
const callback = window.__TAURI__.__INTERNALS__.transformCallback(function (r) {
resolve(r)
delete window[`_${error}`]
}, true)
const error = window.__TAURI__.__INTERNALS__.transformCallback(function (e) {
reject(e)
delete window[`_${callback}`]
}, true)

const action = () => {
window.__TAURI_IPC__({
cmd,
callback,
error,
payload,
options
})
}
if (window.__TAURI_IPC__) {
action()
} else {
ipcQueue.push(action)
if (!isWaitingForIpc) {
waitForIpc()
isWaitingForIpc = true
const action = () => {
window.window.__TAURI__.__INTERNALS__.ipc({
cmd,
callback,
error,
payload,
options
})
}
}
})
}
if (window.__TAURI__?.__INTERNALS__?.ipc) {
action()
} else {
ipcQueue.push(action)
if (!isWaitingForIpc) {
waitForIpc()
isWaitingForIpc = true
}
}
})
}
})
})()
23 changes: 18 additions & 5 deletions core/tauri/scripts/init.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,39 @@
// SPDX-License-Identifier: MIT

; (function () {
if (!window.__TAURI__) {
Object.defineProperty(window, '__TAURI__', {
value: {}
})
}

if (!window.__TAURI__.__INTERNALS__) {
Object.defineProperty(window.__TAURI__, '__INTERNALS__', {
value: {}
})
}

__RAW_freeze_prototype__

__RAW_pattern_script__

__RAW_ipc_script__
; (function () {
__RAW_bundle_script__
})()

__RAW_listen_function__

__RAW_core_script__

__RAW_event_initialization_script__

; (function () {
__RAW_bundle_script__
})()

if (window.ipc) {
window.__TAURI_INVOKE__('__initialized', { url: window.location.href })
window.__TAURI__.__INTERNALS__.invoke('__initialized', { url: window.location.href })
} else {
window.addEventListener('DOMContentLoaded', function () {
window.__TAURI_INVOKE__('__initialized', { url: window.location.href })
window.__TAURI__.__INTERNALS__.invoke('__initialized', { url: window.location.href })
})
}

Expand Down
4 changes: 2 additions & 2 deletions core/tauri/scripts/ipc-protocol.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
const fetchChannelDataCommand = __TEMPLATE_fetch_channel_data_command__
const useCustomProtocol = __TEMPLATE_use_custom_protocol__

Object.defineProperty(window, '__TAURI_POST_MESSAGE__', {
Object.defineProperty(window.__TAURI__.__INTERNALS__, 'postMessage', {
value: (message) => {
const {
cmd,
Expand Down Expand Up @@ -36,7 +36,7 @@
contentType,
data
} = processIpcMessage(payload)
fetch(window.__TAURI__.convertFileSrc(cmd, 'ipc'), {
fetch(window.__TAURI__.__INTERNALS__.convertFileSrc(cmd, 'ipc'), {
method: 'POST',
body: data,
headers: {
Expand Down
8 changes: 4 additions & 4 deletions core/tauri/scripts/ipc.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
/**
* @type {string}
*/
const pattern = window.__TAURI_PATTERN__.pattern
const pattern = window.__TAURI__.__INTERNALS__.__TAURI_PATTERN__.pattern

/**
* @type {string}
Expand Down Expand Up @@ -90,12 +90,12 @@
)
}

Object.defineProperty(window, '__TAURI_IPC__', {
Object.defineProperty(window.__TAURI__.__INTERNALS__, 'ipc', {
// todo: JSDoc this function
value: Object.freeze((message) => {
switch (pattern) {
case 'brownfield':
window.__TAURI_POST_MESSAGE__(message)
window.__TAURI__.__INTERNALS__.postMessage(message)
break

case 'isolation':
Expand Down Expand Up @@ -152,7 +152,7 @@
}

if (isIsolationMessage(event)) {
window.__TAURI_POST_MESSAGE__(event.data)
window.__TAURI__.__INTERNALS__.postMessage(event.data)
}
},
false
Expand Down
2 changes: 1 addition & 1 deletion core/tauri/scripts/pattern.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
return Object.freeze(object)
}

Object.defineProperty(window, '__TAURI_PATTERN__', {
Object.defineProperty(window.__TAURI__.__INTERNALS__, '__TAURI_PATTERN__', {
value: __tauriDeepFreeze(__TEMPLATE_pattern__)
})
})()
4 changes: 2 additions & 2 deletions core/tauri/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -974,7 +974,7 @@ pub struct Builder<R: Runtime> {
/// The JS message responder.
invoke_responder: Option<Arc<InvokeResponder<R>>>,

/// The script that initializes the `window.__TAURI_POST_MESSAGE__` function.
/// The script that initializes the `window.__TAURI__.__INTERNALS__.postMessage` function.
invoke_initialization_script: String,

/// The setup hook.
Expand Down Expand Up @@ -1092,7 +1092,7 @@ impl<R: Runtime> Builder<R> {
///
/// The `responder` is a function that will be called when a command has been executed and must send a response to the JS layer.
///
/// The `initialization_script` is a script that initializes `window.__TAURI_POST_MESSAGE__`.
/// The `initialization_script` is a script that initializes `window.__TAURI__.__INTERNALS__.postMessage`.
/// That function must take the `(message: object, options: object)` arguments and send it to the backend.
#[must_use]
pub fn invoke_system<F>(mut self, initialization_script: String, responder: F) -> Self
Expand Down
2 changes: 1 addition & 1 deletion core/tauri/src/ipc/channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ impl Channel {
.unwrap()
.insert(data_id, body);
window.eval(&format!(
"__TAURI_INVOKE__('{FETCH_CHANNEL_DATA_COMMAND}', null, {{ headers: {{ '{CHANNEL_ID_HEADER_NAME}': '{data_id}' }} }}).then(window['_' + {}]).catch(console.error)",
"window.__TAURI__.__INTERNALS__.invoke('{FETCH_CHANNEL_DATA_COMMAND}', null, {{ headers: {{ '{CHANNEL_ID_HEADER_NAME}': '{data_id}' }} }}).then(window['_' + {}]).catch(console.error)",
callback.0
))
})
Expand Down
17 changes: 11 additions & 6 deletions core/tauri/src/manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -568,17 +568,22 @@ impl<R: Runtime> WindowManager<R> {
.initialization_script(&self.inner.invoke_initialization_script)
.initialization_script(&format!(
r#"
Object.defineProperty(window, '__TAURI_METADATA__', {{
Object.defineProperty(window.__TAURI__.__INTERNALS__, 'metadata', {{
value: {{
__windows: {window_labels_array}.map(function (label) {{ return {{ label: label }} }}),
__currentWindow: {{ label: {current_window_label} }}
windows: {window_labels_array}.map(function (label) {{ return {{ label: label }} }}),
currentWindow: {{ label: {current_window_label} }}
}}
}})
"#,
window_labels_array = serde_json::to_string(&window_labels)?,
current_window_label = serde_json::to_string(&label)?,
))
.initialization_script(&self.initialization_script(&ipc_init.into_string(),&pattern_init.into_string(),&plugin_init, is_init_global)?);
.initialization_script(&self.initialization_script(
&ipc_init.into_string(),
&pattern_init.into_string(),
&plugin_init,
is_init_global,
)?);

#[cfg(feature = "isolation")]
if let Pattern::Isolation { schema, .. } = self.pattern() {
Expand Down Expand Up @@ -814,7 +819,7 @@ impl<R: Runtime> WindowManager<R> {
"eventName".into(),
0,
None,
"window['_' + window.__TAURI__.transformCallback(cb) ]".into()
"window['_' + window.__TAURI__.__INTERNALS__.transformCallback(cb) ]".into()
)
),
core_script: &CoreJavascript {
Expand Down Expand Up @@ -1275,7 +1280,7 @@ fn on_window_event<R: Runtime>(
let windows = windows_map.values();
for window in windows {
window.eval(&format!(
r#"(function () {{ const metadata = window.__TAURI_METADATA__; if (metadata != null) {{ metadata.__windows = window.__TAURI_METADATA__.__windows.filter(w => w.label !== "{label}"); }} }})()"#,
r#"(function () {{ const metadata = window.__TAURI__.__INTERNALS__.metadata; if (metadata != null) {{ metadata.windows = window.__TAURI__.__INTERNALS__.metadata.windows.filter(w => w.label !== "{label}"); }} }})()"#,
))?;
}
}
Expand Down
14 changes: 8 additions & 6 deletions core/tauri/src/path/init.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

if (!('path' in window.__TAURI__)) {
window.__TAURI__.path = {}
}

window.__TAURI__.path.__sep = __TEMPLATE_sep__
window.__TAURI__.path.__delimiter = __TEMPLATE_delimiter__
Object.defineProperty(window.__TAURI__.__INTERNALS__, 'path', {
value: {
path: {
sep: __TEMPLATE_sep__,
delimiter: __TEMPLATE_delimiter__
}
}
})
2 changes: 1 addition & 1 deletion core/tauri/src/window.rs
Original file line number Diff line number Diff line change
Expand Up @@ -425,7 +425,7 @@ impl<'a, R: Runtime> WindowBuilder<'a, R> {
crate::vibrancy::set_window_effects(&window, Some(effects))?;
}
self.manager.eval_script_all(format!(
"window.__TAURI_METADATA__.__windows = {window_labels_array}.map(function (label) {{ return {{ label: label }} }})",
"window.__TAURI__.__INTERNALS__.metadata.windows = {window_labels_array}.map(function (label) {{ return {{ label: label }} }})",
window_labels_array = serde_json::to_string(&self.manager.labels())?,
))?;

Expand Down
Loading

0 comments on commit 0de1429

Please sign in to comment.