Skip to content

Commit

Permalink
feat: web-socket component
Browse files Browse the repository at this point in the history
  • Loading branch information
alkoleft committed Dec 23, 2024
1 parent ab80185 commit 1179223
Show file tree
Hide file tree
Showing 15 changed files with 634 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -303,13 +303,13 @@

Если Форма.Открыта() Тогда
Попытка
Если ЭтоУправляемаяФорма Тогда
Форма.ОбновитьОтображениеДанных();
Иначе
Форма.Обновить();
КонецЕсли;
Исключение
ВызватьИсключение;
Если ЭтоУправляемаяФорма Тогда
Форма.ОбновитьОтображениеДанных();
Иначе
Форма.Обновить();
КонецЕсли;
Исключение
ВызватьИсключение;
КонецПопытки;

Форма.Модифицированность = Ложь;
Expand Down
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<mdclass:CommonTemplate xmlns:mdclass="http://g5.1c.ru/v8/dt/metadata/mdclass" uuid="c5a802be-2d54-43ca-b00c-bdff0c4b4e2d">
<name>ЮТWebSocket</name>
<synonym>
<key>ru</key>
<value>Web socket</value>
</synonym>
<templateType>BinaryData</templateType>
</mdclass:CommonTemplate>
1 change: 1 addition & 0 deletions exts/yaxunit/src/Configuration/Configuration.mdo
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
<commonTemplates>CommonTemplate.ЮТ_СловарьПодражателя_Люди_МужскиеФамилии_ru</commonTemplates>
<commonTemplates>CommonTemplate.ЮТRegEx1CAddin</commonTemplates>
<commonTemplates>CommonTemplate.ЮТV8UnpackWS</commonTemplates>
<commonTemplates>CommonTemplate.ЮТWebSocket</commonTemplates>
<commonTemplates>CommonTemplate.ЮТYaxUnitAddIn</commonTemplates>
<commonTemplates>CommonTemplate.ЮТИнформацияОбОшибке</commonTemplates>
<commonTemplates>CommonTemplate.ЮТОписаниеМетаданных</commonTemplates>
Expand Down
File renamed without changes.
13 changes: 13 additions & 0 deletions tools/build-websocket-template.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
#!/bin/bash

CURRENT_PATH=$(pwd)
SCRIPTPATH="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"

cd ${SCRIPTPATH}/web-socket

yarn install && yarn build
cd dist

zip -r -9 ../web-socket.zip ./
mv ../web-socket.zip ../../../exts/yaxunit/src/CommonTemplates/ЮТWebSocket/Template.bin
cd ${CURRENT_PATH}
24 changes: 24 additions & 0 deletions tools/web-socket/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
16 changes: 16 additions & 0 deletions tools/web-socket/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<!doctype html>
<html lang="en">

<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>

<body>
<div id="app"></div>
<button id='V8WebAppEventRequestForwarder' style="display: 'none'"></button>
<button id='V8WebAppEventResponseForwarder' style="display: 'none'"></button>
<script type="module" src="/src/main.ts"></script>
</body>

</html>
19 changes: 19 additions & 0 deletions tools/web-socket/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"name": "web-socket",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview"
},
"devDependencies": {
"typescript": "~5.6.2",
"vite": "^6.0.3",
"vite-plugin-singlefile": "^2.1.0"
},
"dependencies": {
"websocket-ts": "^2.1.5"
}
}
102 changes: 102 additions & 0 deletions tools/web-socket/src/V8Proxy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
class FetchResponse {
_value: any

constructor(value: any) {
this._value = value
}

/**
* text
*/
public text() {
return String(this._value)
}

/**
* name
*/
public json() {
return JSON.parse(this._value)
}

/**
* blob
*/
public blob() {
let sliceSize = 1024;
let byteCharacters = atob(this._value);
let bytesLength = byteCharacters.length;
let slicesCount = Math.ceil(bytesLength / sliceSize);
let byteArrays = new Array(slicesCount);

for (let sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
let begin = sliceIndex * sliceSize;
let end = Math.min(begin + sliceSize, bytesLength);

let bytes = new Array(end - begin);
for (let offset = begin, i = 0; offset < end; ++i, ++offset) {
bytes[i] = (byteCharacters[offset] as string).charCodeAt(0);
}
byteArrays[sliceIndex] = new Uint8Array(bytes);
}
return new Blob(byteArrays);
}
}

const V8Proxy = {

fetch: (eventName: string, value: any = undefined) => {

let v8uuid = String(Math.floor(Math.random() * 1000000))
let v8type = 'undefined'

switch (typeof (value)) {
case 'string':
v8type = 'string'
break
case 'boolean':
v8type = 'bool'
break
case 'number':
v8type = 'number'
break
case 'object':
v8type = 'json'
break
case 'bigint':
v8type = 'blob'
break
}

return new Promise<FetchResponse>((resolve) => {
console.debug(`V8Proxy.fetch(V8Proxy.fetch(${v8uuid}): ${eventName} ${v8type} ${String(value)}`)

let res = document.getElementById('V8WebAppEventResponseForwarder') as HTMLButtonElement
const handle = function () {
if (res.getAttribute('v8uuid') === v8uuid) {
res.removeEventListener('click', handle)

console.debug(`V8Proxy.fetch(${v8uuid} resolve: ${res.value}`)

resolve(new FetchResponse(res.value))
}
}
res.addEventListener('click', handle)

let req = document.getElementById('V8WebAppEventRequestForwarder') as HTMLButtonElement
req.setAttribute('v8eventname', eventName)
req.setAttribute('v8uuid', v8uuid)
req.setAttribute('v8type', v8type)
req.value = JSON.stringify(value)
req.click();
})
},
sendResponse: (v8uuid: string, value: string) => {
let res = document.getElementById('V8WebAppEventResponseForwarder') as HTMLButtonElement
res.setAttribute('v8uuid', v8uuid)
res.value = value;
res.click();
}
}

export default V8Proxy
36 changes: 36 additions & 0 deletions tools/web-socket/src/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import {
WebsocketBuilder, ArrayQueue,
ConstantBackoff, WebsocketEvent, Websocket
} from 'websocket-ts'
import V8Proxy from './V8Proxy'

let ws: Websocket;

function connect(endPoint: string) {
ws = new WebsocketBuilder(endPoint)
.withBuffer(new ArrayQueue()) // buffer messages when disconnected
.withBackoff(new ConstantBackoff(1000)) // retry every 1s
.onOpen(() => fire('open'))
.onReconnect(() => fire('reconnect'))
.onClose(() => fire('close'))
.onError(() => fire('error'))
.onMessage((_, ev) => fire('message', ev.data))
.build();
// Add event listeners
ws.addEventListener(WebsocketEvent.open, () => fire("open"));
ws.addEventListener(WebsocketEvent.close, () => console.log("closed!"));
ws.addEventListener(WebsocketEvent.message, (...args) => console.log('message', ...args));
ws.addEventListener(WebsocketEvent.error, (...args) => console.log('error', ...args));

ws.send('pending')
}

function send (data: any){
ws.send(data)
}
function fire(eventName: string, data?: any) {
V8Proxy.fetch('socket.' + eventName, data)
}

(window as any).connect = connect;
(window as any).send = send;
1 change: 1 addition & 0 deletions tools/web-socket/src/vite-env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/// <reference types="vite/client" />
23 changes: 23 additions & 0 deletions tools/web-socket/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"target": "ES2015",
"useDefineForClassFields": true,
"module": "ESNext",
// "lib": ["ES2020", "DOM", "DOM.Iterable"],
"skipLibCheck": true,

/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,

/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}
6 changes: 6 additions & 0 deletions tools/web-socket/vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { defineConfig } from "vite"
import { viteSingleFile } from "vite-plugin-singlefile"

export default defineConfig({
plugins: [viteSingleFile()],
})
Loading

0 comments on commit 1179223

Please sign in to comment.