Files
2026-09-23 16:58:21 +02:00

950 lines
42 KiB
HTML

<html>
<head>
<script src='kbd.js' ></script>
<script>window.AFRAME_CDN_ROOT='./assets/'</script>
<link rel="stylesheet" href="https://unpkg.com/keyboard-css@1.2.4/dist/css/main.min.css" />
<script src="https://aframe.io/releases/1.8.0/aframe.min.js"></script>
<script>
// bugfix on AFrame remote hand grabbing, will be merged on next release
const jointPose = new THREE.Matrix4();
const WRIST_INDEX = 0;
AFRAME.components['hand-tracking-controls'].Component.prototype.updateWristObject = function() {
var wristObject3D = this.wristObject3D;
if (!wristObject3D || !this.hasPoses) { return; }
jointPose.fromArray(this.jointPoses, WRIST_INDEX * 16);
// The wrist object is added to the scene root, so apply parent transform
this.el.object3D.updateWorldMatrix(true, false);
jointPose.premultiply(this.el.object3D.matrixWorld);
wristObject3D.position.setFromMatrixPosition(jointPose);
wristObject3D.quaternion.setFromRotationMatrix(jointPose);
}
</script>
</head>
<body>
<canvas id=cam style='display:none;border:solid 1px;z-index:100; position:fixed;' width="512" height="512"></canvas>
<div id=virtualkeyboardoutput style='color:white; background:rgba(1,1,1,0.5);z-index:100; position:fixed; bottom:0;' >
<input size=5 autofocus name='demo mode'/>
<span id=demobuttons></span>
(other keys are also enabled, including numberd moves, see <button popovertarget="popoverUserAction">userActions</button>)
<div style='padding:10px; border-radius: 20px;' popover id="popoverUserAction"></div>
</div>
<div style='background:rgba(1,1,1,0.5);z-index:100; position:fixed; bottom:0;right:0;' width="100%" >
<a target="_blank" href=https://fabien.benetou.fr/pub/home/cursorisyou.pdf>explanation visuals</a>
<button id=desktopbutton onclick=desktopTutorMode()>enable desktop tutor mode</button>
</div>
<a-scene obb-collider="showColliders: true">
<a-entity id="rig" position="0 0 0">
<a-entity id="camera" position="0 1.6 0" camera look-controls>
<a-text scale=".1 .1 .1" position="-0.5 -0.01 -1" font=monoid value="" id=feedbackhud color="gray"></a-text>
<a-text scale=".1 .1 .1" position="-0.5 0.01 -1" font=monoid value="" id=edithud color="black"></a-text>
</a-entity>
<!-- controllers and hands must be in rig otherwise they appear remote while moving rig, which is interesting but weird -->
<a-entity id="leftHand" hand-tracking-controls="hand: left;"></a-entity>
<a-entity id="rightHand" hand-tracking-grab-controls="hand: right;"></a-entity>
<a-entity id=pen6dof logitech-mx-ink-controls="hand: right"></a-entity>
<a-text id=consolehud position="0 0 -6" value="" font="roboto" color="#4CC3D9"></a-text>
</a-entity>
<a-entity id=tests visible=false>
<a-text position="-1 1.5 -1" font=monoid value="use gg to move back\nm* to bookmark the current position\n? for help" color="#4CC3D9">
<a-text id=highlight position="0 0 -.01" font=monoid value="gg" color="#9CCAD9"></a-text>
<a-text font=monoid value="|" animation="property:opacity; from:.2; to:1; loop:true; dir: alternate; easing: easeOutQuad;"
id=carret color="#4CC3D9"></a-text>
</a-text>
<a-text position="1 1.5 -1" font=monoid value="? - press ? to get help on current bindings" color="#4CC3D9"></a-text>
<a-text position="-1 2 -2" value="load json keymap with layout\n(cf past work on typing trainer)" color="#4CC3D9"></a-text>
<a-text position="-3 1 -5" value="" font="roboto" id="layertest" wrap-count=200 color="#4CC3D9"></a-text>Z
<a-box position="-1 0.5 -3" rotation="0 45 0" color="#4CC3D9"></a-box>
<a-sphere position="0 1.25 -5" radius="1.25" color="#EF2D5E"></a-sphere>
<a-cylinder position="1 0.75 -3" radius="0.5" height="1.5" color="#FFC65D"></a-cylinder>
<a-plane id=ground position="0 0 -4" rotation="-90 0 0" width="4" height="4" color="#7BC8A4"></a-plane>
<a-text grabbable position="0 1 -.6" value="move me" font="roboto" color="#4CC3D9"></a-text>
<a-box grabbable position="-.5 1.5 -.5" scale='.2 .2 .2' rotation="0 45 0" color="#4CC3D9"></a-box>
<a-text grabbable position="0 1.2 -.6" value="jxr ground.setAttribute('color', 'pink')" font="roboto" color="#4CC3D9"></a-text>
</a-entity>
<a-text position="0 2 -2" id=syntaxhighlight value="location.reload()" font="roboto"></a-text>
<a-text scale=".1 .1 .1" grabbable position="0 1.7 -5" value="move me after teleportation" font="roboto" color="red"></a-text>
<a-text scale=".1 .1 .1" grabbable position="0 1.4 -.6" id=cmdexample value="jxr location.reload()" font="roboto" color="#4CC3D9"></a-text>
<a-text scale=".1 .1 .1" grabbable position="0 1.6 -.6" id=cmdexample3 value="jxr console.log('not hi')" font="roboto" color="#4CC3D9"></a-text>
<a-text scale=".1 .1 .1" grabbable position="0 1.7 -.6" id=cmdexample2 value="jxr addBindingFromLatestExecutedSnippet()" font="roboto" color="#4CC3D9"></a-text>
<a-text scale=".1 .1 .1" grabbable position="0 1.7 -.6" id=cmdexample6 value="jxr console.log('dropped on head to edit')"
ondrop="nearbyCameraCopyLatestToEditHUD()"
font="roboto" color="red"></a-text>
<a-text scale=".1 .1 .1" grabbable position="0 1.4 -.3" id=cmdexample5 value="jxr console.log( 'on drop demo' )" ondrop="console.log('dropped via attribute')"
font="roboto" color="#4CC3D9"></a-text>
<a-entity id=keyboard position='0 1.2 0' scale='.2 .2 .2' rotation='-50 0 0' ></a-entity>
<a-text visible=false position="0 1 -5" value="hello" font="roboto" id="wordgame" color="red"></a-text>
<a-sky color="#ECECEC"></a-sky>
<a-entity visible=false id=tutor>
<a-plane wireframe=true position="0 0 -1" rotation="-90 0 0" width="1" height="1" color="lightblue"></a-plane>
<a-text position="0 1 -1" value="press j to move forward\n\n(on your right hand feel the keyboard notch,\nunder your index finger)" font="roboto" color="gray"></a-text>
<a-plane position="0 0 -2" rotation="-90 0 0" width="1" height="1" color="lightblue"></a-plane>
<a-text position="0 1 -2" value="press j again" font="roboto" color="gray"></a-text>
<a-plane position="0 0 -3" rotation="-90 0 0" width="1" height="1" color="lightblue"></a-plane>
<a-text position="0 1 -3" value="press k to move backward\n\n(middle finger, next to it)\n then go forward again twice" font="roboto" color="gray"></a-text>
<a-plane position="0 0 -4" rotation="-90 0 0" width="1" height="1" color="lightblue"></a-plane>
<a-text position="0 1 -4" value="l to move left\n\n(ring finger" font="roboto" color="gray"></a-text>
<a-plane position="1 0 -4" rotation="-90 0 0" width="1" height="1" color="lightblue"></a-plane>
<a-text position="1 1 -4" value="j (move forward)" font="roboto" color="gray"></a-text>
<a-plane position="1 0 -5" rotation="-90 0 0" width="1" height="1" color="lightblue"></a-plane>
<a-text position="1 1 -5" value="j (move forward again)" font="roboto" color="gray"></a-text>
<a-plane position="1 0 -6" rotation="-90 0 0" width="1" height="1" color="lightblue"></a-plane>
<a-text position="1 1 -6" value="h (move left)" font="roboto" color="gray"></a-text>
<a-text position="5 1 -8" value=". to repeat last command" font="roboto" color="gray"></a-text>
<a-text position="5 1 -8" value="5j to repeat j 5 times" font="roboto" color="gray"></a-text>
<!-- need to explain the number layer first, tricky, could provide fallback e.g ... press j yourself 5 times -->
<a-text position="10 1 -10" value="reward with richer interactions" font="roboto" color="gray"></a-text>
<a-text position="10 1 -11" value="gg to go back to the initial position and restart" font="roboto" color="gray"></a-text>
</a-entity>
<!-- video fallback with visible keypresses (not just terminal as harder to understand) -->
<a-entity visible=false aid=blocks position="-0.3 1.5 -0.5">
<a-entity notyetgrabbable position="0 -.1 0">
<a-cylinder position="0.02 -0.005 0" rotation='90 90 90' height=0.25 scale=".02 .05 .01"color="red" theta-length="180" side="double"></a-cylinder>
<a-box position="0 -0.005 0" width=.06 height=.02 depth=.01 color="red"></a-box>
<a-cylinder position="-0.02 -0.005 0" rotation='-90 90 90' height=0.25 scale=".02 .05 .01"color="red" theta-length="180" side="double"></a-cylinder>
</a-entity>
<a-entity notyetgrabbable position="0 .3 0">
<a-cylinder rotation='0 90 90' height=0.25 scale=".02 .05 .05"color="orange" theta-length="180" side="double"></a-cylinder>
<a-text position="-0.06 0.0 0.01" scale=".1 .1 .1" font=monoid value="some code" color="white"></a-text>
<a-box position="0 -0.005 0" width=.1 height=.02 depth=.01 color="orange"></a-box>
<a-box position="-0.01 -0.02 0"width=.02 height=.01 depth=.01 color="orange"></a-box>
</a-entity>
<a-entity notyetgrabbable position="0 .1 0">
<a-box position="0.025 0.01 0"width=.05 height=.01 depth=.01 color="blue"></a-box>
<a-box position="-0.035 0.01 0"width=.03 height=.01 depth=.01 color="blue"></a-box>
<a-box position="0 -0.005 0" width=.1 height=.02 depth=.01 color="blue"></a-box>
<a-box position="-0.01 -0.02 0"width=.02 height=.01 depth=.01 color="blue"></a-box>
</a-entity>
<a-entity notyetgrabbable position="0 .2 0">
<a-box position="0.025 0.01 0"width=.05 height=.01 depth=.01 color="green"></a-box>
<a-box position="-0.035 0.01 0"width=.03 height=.01 depth=.01 color="green"></a-box>
<a-box position="0 -0.005 0" width=.1 height=.02 depth=.01 color="green"></a-box>
<a-box position="-0.01 -0.02 0"width=.02 height=.01 depth=.01 color="green"></a-box>
</a-entity>
<a-entity notyetgrabbable position="0 0 0">
<a-box position="0.025 0.01 0"width=.05 height=.01 depth=.01 color="purple"></a-box>
<a-box position="-0.035 0.01 0"width=.03 height=.01 depth=.01 color="purple"></a-box>
<a-box position="0 -0.005 0" width=.1 height=.02 depth=.01 color="purple"></a-box>
<a-box position="-0.01 -0.02 0"width=.02 height=.01 depth=.01 color="purple"></a-box>
</a-entity>
</a-entity>
<a-box grabbable position="0 1.22 -.5" wireframe=true id=touchpad width=.1 height=.01 depth=.1 color="#4FF3D9"></a-box>
<a-sphere position="0 1.22 -.5" segments-height=8 segments-width=8 id=touchpadpointer color="yellow" radius=".01"></a-sphere>
</a-scene>
<script>
'hjkl'.split('').map(k => demobuttons.innerHTML += htmlButtonFromKey(k) )
// positioned content via URL e.g.
// done
// marks
// userActions (untested)
// jxr
// tutorial
// see adding text on tile in addMark(key, pos)
const searchParams = new URLSearchParams( window.location.search )
function parseURL(){
if (searchParams.get('marks')){
let parsedMarks = JSON.parse(searchParams.get('marks'))
parsedMarks.map( m => addMark(m.key, m.pos) )
// example https://localhost:8443/aframe?marks=[{%22key%22:%22y%22,%22pos%22:%220%200%20-4%22}]
// can be typed and tested in the browser
// shortcut but go* then appending in userActions, so can also be done this way
}
if (searchParams.get('userActions')){
let parsedUserActions = JSON.parse(searchParams.get('userActions'))
userActions.push( ... parsedUserActions )
}
// conversaly saving customizations added during a session should be supported
// e.g. location.pathname += '?userActions=' + JSON.stringify(userActions)
}
function clicked(k, el){
userActions.filter(a => a.key == k).map(a => eval(a.action))
// fine for keys but not for sequences or regex, must be refined
let seq = el.getAttribute('seq')
if (seq){
// should add hover on other elements of same sequence then remove in 1sec
//.classList.add("hover")
Array.from( document.querySelectorAll('[seq='+seq+']') ).map( el => el.classList.add("hover") )
setTimeout( _ => {
Array.from( document.querySelectorAll('[seq='+seq+']') ).map( el => el.classList.remove("hover") )
Array.from( document.querySelectorAll('[seq='+seq+']') ).map( el => el.blur() )
}, 1000)
console.log('part of seq', seq)
userActions.filter(a => a.seq == seq).map(a => eval(a.action))
}
}
document.addEventListener('keydown', (ev) => {
const key = ev.key;
const element = document.querySelector(
'[data-keyboard-key="' + key.toUpperCase() + '"]'
);
if (element) element.classList.add('active');
});
document.addEventListener('keyup', (ev) => {
const key = ev.key;
const element = document.querySelector(
'[data-keyboard-key="' + key.toUpperCase() + '"]'
);
if (element) element.classList.remove('active');
});
// from https://shhdharmen.github.io/keyboard-css/
AFRAME.registerComponent("secondcam", {
init: function() {
let canvas = document.querySelector("#cam");
this.ctx = canvas.getContext("2d");
this.secondaryCam = document.querySelector("#rig").components.camera.camera;
},
tick: function() {
if (!this.secondaryCam) return;
// render the secondary camera view
this.el.renderer.render(this.el.sceneEl.object3D, this.secondaryCam);
// draw the render on the canvas
this.ctx.drawImage(this.el.renderer.domElement, 0, 0, 512, 512);
}
});
function measureCharacter(c = ' ', font='monoid', scale='.1 .1 .1'){
// <a-text scale=".1 .1 .1" position="-0.5 -0.01 -1" font=monoid value="" id=feedbackhud color="gray"></a-text>
let el = document.createElement('a-text')
el.setAttribute('position', '0 1 -1')
el.setAttribute('value', c)
el.setAttribute('scale', scale)
el.setAttribute('font', font)
el.id = 'measureCharacterTest'
AFRAME.scenes[0].appendChild( el )
setTimeout( _ => {
el.object3D.updateWorldMatrix( true, false )
let bb = new THREE.Box3()
bb.setFromObject( el.object3D, true )
// setting from its children also does not work, getting infinity
AFRAME.scenes[0].emit('charsize', bb )
// actually also not working via the inspector
console.log( bb.min, bb.max )
}, 500)
}
const jsReservedKeywords = 'break do instanceof typeof case else new var catch finally return void continue for switch while debugger function this with default if throw delete in try'.split(' ')
function colorizeString(el = syntaxhighlight){
// must use a monospace font e.g. el.setAttribute('font', 'monoid')
let content = el.getAttribute('value')
el.setAttribute('value','')
let parts = content.split('.')
let newEl = el.cloneNode(true)
newEl.setAttribute('color', 'green')
newEl.setAttribute('value', parts[0] )
newEl.setAttribute('position', '0 0 0')
el.appendChild(newEl)
newEl = el.cloneNode(true)
newEl.setAttribute('color', 'blue')
newEl.setAttribute('value', parts[1] )
// must shift it based on width of prevous one
newEl.setAttribute('position', parts[0].length * .1 + ' 0 0')
// .1 here being a lucky heuristic
el.appendChild(newEl)
}
// consider touchpad mode, for fixed keyboard on table position
// can then do side of touchpad scrolling, a la KDE
// add a jxr command that will define its center from a 5cm radius and fixed y coordinates
// could then project on another plane
// consider also the position of the keyboard parts
// can be tested in MR/AR
// need to setup AFrame component accordingly
setInterval( _ => {
// check if right hand index fingertip within a visible volume
if (!AFRAME.scenes[0]) return
if (!AFRAME.scenes[0].object3D.getObjectByName("r_handMeshNode") ) return
let rift = AFRAME.scenes[0].object3D.getObjectByName("r_handMeshNode").parent.getObjectByName("index-finger-tip")
// via https://www.w3.org/TR/webxr-hand-input-1/ and gesture exploration in xrsh
const targetY = touchpad.object3D.position.y
const tpos = touchpad.object3D.position
const d = Number( touchpad.getAttribute('depth') )
const w = Number( touchpad.getAttribute('width') )
// easier to consider an obb at this point...
if ( rift.position.y > targetY * .99 && rift.position.y < targetY * 1.01 ){
//&& rift.position.z > tpos.z - depth/2 && rift.position.z < tpos.z + depth/2
//&& rift.position.x > tpos.x - width/2 && rift.position.x < tpos.x + width/2){
// todo fix
// simplifying, assuming scale of 1
// console.log( rift.position.x, rift.position.y, rift.position.z )
touchpadpointer.object3D.position.copy( rift.position )
// can then move another object which itself could be the children of another plannar object
// should make touchpad axis align or at least no rotation on y and z, only x
}
}, 10)
const layout = [
{ "x": 0.0, "y": 1.0 }, { "x": 1.0, "y": 0.25 }, { "x": 2.0, "y": 0.0 }, { "x": 3.0, "y": 0.25 }, { "x": 4.0, "y": 0.35 }, { "x": 8.5, "y": 0.35 }, { "x": 9.5, "y": 0.25 }, { "x": 10.5, "y": 0.0 }, { "x": 11.5, "y": 0.25 }, { "x": 12.5, "y": 1.0 },
{ "x": 0.0, "y": 2.0 }, { "x": 1.0, "y": 1.25 }, { "x": 2.0, "y": 1.0 }, { "x": 3.0, "y": 1.25 }, { "x": 4.0, "y": 1.35 }, { "x": 8.5, "y": 1.35 }, { "x": 9.5, "y": 1.25 }, { "x": 10.5, "y": 1.0 }, { "x": 11.5, "y": 1.25 }, { "x": 12.5, "y": 2.0 },
{ "x": 0.0, "y": 3.0 }, { "x": 1.0, "y": 2.25 }, { "x": 2.0, "y": 2.0 }, { "x": 3.0, "y": 2.25 }, { "x": 4.0, "y": 2.35 }, { "x": 8.5, "y": 2.35 }, { "x": 9.5, "y": 2.25 }, { "x": 10.5, "y": 2.0 }, { "x": 11.5, "y": 2.25 }, { "x": 12.5, "y": 3.0 },
{ "x": 2.8, "y": 3.6, }, { "x": 4.1, "y": 3.5, }, { "x": 5.45, "y": 3.7, },
{ "x": 7.1, "y": 3.89, }, { "x": 8.45, "y": 3.6, }, { "x": 9.75, "y": 3.5, }
]
const scale = 1/10
layout.map( (k,n) => {
let el = document.createElement('a-box')
el.id = 'key'+n
el.setAttribute('scale', '.05 .04 .01')
el.setAttribute('position', (-.6+scale*k.x) + ' ' + (1-scale*k.y) + ' -1')
keyboard.appendChild( el )
})
// ideally would be referenced by keymap instead e.g. keyj
// cheating a bit for tutor only used keys
const keyj = key16
keyj.setAttribute('color', 'pink')
// pants mode
//keyboard.setAttribute('rotation', '180 0 0')
// could be in rig to move with person
// rotation on y could match the camera
document.addEventListener("keydown", function(event) {
let p = keymap.indexOf(event.key.toLowerCase())
if (p > -1) document.getElementById('key'+p).setAttribute('color', 'red')
})
document.addEventListener("keyup", function(event) {
let p = keymap.indexOf(event.key.toLowerCase())
if (p > -1) document.getElementById('key'+p).setAttribute('color', 'white')
})
// easily testable in insert mode, not having to move around
let keymap = "qwertyuiopasdfghjkl'zxcvbnm,./"
// see instead ...
function parseLayers(layers){
// called via the event emitted after getting keymap.txt
console.log(layers)
// could then update on keymap but with a different structure, e.g
// e.g. layers[0].map(e=>e.map(n=>n.replace(/.* /,''))).join()
}
keymap.split('').map( (k,n) => {
let el = document.createElement('a-text')
el.setAttribute('position', '-.4 0 .51')
el.setAttribute('value', k)
el.setAttribute('color', 'black')
el.setAttribute('scale', '3 3 3')
let p = keymap.indexOf(k.toLowerCase())
if (p > -1) document.getElementById('key'+p).appendChild( el )
})
// special keys typically requires more than 1 character name, e.g. Tab or F11
// e.g. keymap.split('').concat('Escape','Tab',' ', 'Enter', 'Backspace', 'MuteToggle').indexOf('a') // still works
// note that MuteToggle is not an actual key name, used instead of be descriptive without getting a hit
// empty layer Array(36).fill('trans')
// very challenging UX
let dict = ['world', 'peace', 'relax', 'test', 'try', 'happy']
setInterval( _ => {
wordgame.object3D.translateZ(.1)
if ( wordgame.object3D.position.z > camera.object3D.position.z ){
console.log('hit')
wordgame.object3D.translateZ(-6)
wordgame.setAttribute('value', dict.at(dict.length*Math.random()) )
wordgame.object3D.translateY( 2*Math.random() - 1 )
wordgame.object3D.translateX( 2*Math.random() - 1 )
}
if ( edithud.getAttribute('value') == wordgame.getAttribute('value') ){
console.log('cleared')
wordgame.object3D.translateZ(-6)
wordgame.setAttribute('value', dict.at(dict.length*Math.random()) )
edithud.setAttribute('value', '')
wordgame.object3D.translateY( 2*Math.random() - 1 )
wordgame.object3D.translateX( 2*Math.random() - 1 )
}
}, 100)
// switching between keyboard and physical navigation is equivalent do DPI snipping mode
// see https://bstiq.github.io/bstiqbstkbd.github.io/fw/dilemma-features.html#sniping
// namely fast distant motion is done on keyboard but precise spatial motion is done physically, walking and with hands
/*
Vim-like in XR discovery game with zombie like, type to remove enemy e.g. https://playglyphica.com
integrate microgestures in multiple inputs demo https://github.com/aframevr/aframe/issues/5716
Tested Surface typing, includes gestures, setup with hands places over flat surface https://www.meta.com/en-gb/help/quest/1589938228821220/
*/
// Source - https://stackoverflow.com/a/11403129
// Posted by Tomasz Nurkiewicz, modified by community. See post 'Timeline' for change history
// Retrieved 2026-09-06, License - CC BY-SA 4.0
const oldlog = console.log
const oldwarn = console.warn
const oldinfo = console.info
const olderror = console.error
const maxLines = 10
window.console = {
log : function(...data) {
oldlog(...data)
consolehud.setAttribute('value', consolehud.getAttribute('value').split('\n').slice(-maxLines).join('\n') + '\n' + data.join(' ') )
// coerce to string and lost type thus coloring as done in browser console
// clear maximum length
},
info : function(msg) {// incorrect , assumes single parameter TODO fix, see example above
oldinfo(msg)
},
warn : function(msg) {
oldwarn(msg)
},
error : function(msg) {
olderror(msg)
},
}
// done as component so can be added to any existing page, e.g. Biggu's Gate, past work, etc
// can pre-load 3 tabs with different demo files that can be overwritten by URL to get e.g WebDAV files
// completion
// textForCompletion.split(' ').filter(w=>w.startsWith('hel'))
// used for insert mode based on
// means also being able to do shortcuts while in insert mode, e.g. Ctrl+n
// interactions like past work, right hand to move, left hand to execute
/*
let grabbables = Array.from( document.querySelectorAll('[grabbable]') )
grabbables.map( (el, n) => {
el.addEventListener('obbcollisionstarted', event => {
hud.setAttribute('value', 'obbcollisionstarted on\ngrabbable ' + n)
} )
})
*/
// shortcuts
let cl = console.log
let executionsHistory = []
let movedSnippets = []
let timeClearingFeedbackHUD
function nearbyCameraCopyLatestToEditHUD(){
let el = movedSnippets.at(-1)
if (el.object3D.position.distanceTo( camera.object3D.position ) < .2 )
copyLatestToEditHUD()
}
function copyLatestToEditHUD(){
// should check distance to camera first
edithud.setAttribute('value', movedSnippets.at(-1).getAttribute('value') )
}
let grabAppend = true
let grabAppendInterval
let lastAddedSnippetEl = null
// see https://aframe.io/docs/1.8.0/components/logitech-mx-ink-controls.html#events
pen6dof.addEventListener('frontdown', event => {
let el = document.createElement('a-sphere')
el.setAttribute('position', AFRAME.utils.coordinates.stringify( pen6dof.getAttribute('position') ) )
// might need el.object3D.getWorldPosition(pos)
el.setAttribute('radius', .01)
AFRAME.scenes[0].appendChild( el )
} )
rightHand.addEventListener('grabstarted', event => {
let el = event.detail.grabbedEl
// magnetism mode
clearInterval( grabAppendInterval )
let grabbables = Array.from( document.querySelectorAll('[grabbable]') )
// useful to do this again in case new ones have been added since the page loaded first, e.g typed
let pos = new THREE.Vector4()
if (grabAppend) grabAppendInterval = setInterval( _ => {
// pull a snippet
//grabbables.filter( sel => sel.getAttribute('value') && sel.getAttribute('value').startsWith('jxr ') ).map( (snippetEl) => {
el.object3D.updateMatrixWorld(true)
el.object3D.getWorldPosition(pos)
grabbables.filter( snippetEl => snippetEl != el ).map( (snippetEl) => {
// if while moving it, it gets close enough to another, append a copy of that one to the moving one
if ( snippetEl.object3D.position.distanceTo( pos) < .05 ) {
if ( lastAddedSnippetEl == null || (lastAddedSnippetEl && lastAddedSnippetEl != snippetEl)){
el.setAttribute('value', el.getAttribute('value') + '\n' + snippetEl.getAttribute('value').replace('jxr ','') )
lastAddedSnippetEl = snippetEl
// timed based
setTimeout( _ => lastAddedSnippetEl = null, 1000)
}
}
} )
// could benefit from a remove last line snippet or even a shortcut
// could also consider executing on grabbing through
// a la rings exploration for Sloan
}, 50 )
} )
rightHand.addEventListener('grabended', event => {
clearInterval( grabAppendInterval )
let el = event.detail.grabbedEl
console.log( 'grabended ' + el.id )
movedSnippets.push( el )
// via https://github.com/aframevr/aframe/blob/master/src/components/hand-tracking-grab-controls.js#L97
// does not seem documented as of sept 2026
let ondrop = el.getAttribute('ondrop')
if (ondrop) eval( el.getAttribute('ondrop').replace('jxr ', '') )
} )
function printFeedbackThenClearFeedbackHUD( feedback ){
feedbackhud.setAttribute('value', feedback )
clearTimeout( timeClearingFeedbackHUD )
timeClearingFeedbackHUD = setTimeout( _ => feedbackhud.setAttribute('value', ''), 2000 )
}
const distanceThreshold = .05
leftHand.addEventListener('pinchstarted', event => {
let grabbables = Array.from( document.querySelectorAll('[grabbable]') )
// useful to do this again in case new ones have been added since the page loaded first, e.g typed
grabbables.map( (el ) => {
if ( el.object3D.position.distanceTo( event.detail.position ) < .05 ) {
printFeedbackThenClearFeedbackHUD( 'should execute ' + el.getAttribute('value') )
eval( el.getAttribute('value').replace('jxr ', '') )
executionsHistory.push( el.getAttribute('value').replace('jxr ', '') )
}
} )
} )
// hand prop scale idea https://mastodon.pirateparty.be/@utopiah/117217734968868844
const handScaling = false
if (handScaling) setInterval( _ => {
rightHand.object3D.scale.setScalar( 1 / (1 + rightHand.object3D.position.distanceTo( camera.object3D.position ) ) )
// to clarify, could have "normal" range instead, e.g. exponential away from 1m distance
leftHand.object3D.scale.setScalar( 1 / leftHand.object3D.position.distanceTo( camera.object3D.position ) )
}, 60)
// M* to mark positions to later go back there with e.g. go*, possibly also gn* as that's what I usually use
// store positions and key, could directly manipulate userActions to add/update(remove then add) matching ones.
// requires pattern matchin instead
// ? on by default by hidden, displaying the content of userActions (insuring it is XR compatible)
// vim / tridactyl tutor mode, showing bindings in context with demonstration
// sequences, e.g. gg, captured then ondrop if close enough to jxr, binds to it, so that if doing gg again now does the thing
// allow to rebind, and thus provide mechanism to show snippets already binding to sequences
// extend to gesture binding
// see past work displaying bones
// can record relative poses over time
// crop in time
// limit to specific bones
// see also ~/Prototypes/cursor_is_you/
// training mode could also be with 3rd peson PoV, non XR tutoring mode
// a la https://mastodon.pirateparty.be/@utopiah/117309256633773896
// can be done by scaling down the grid
// https://threejs.org/docs/#CameraHelper
// temporarily remove the id of the rig and move it to the virtual rig with the camera helper
// potentially putting it back
function addVirtualRig(){
document.getElementById('camera').removeAttribute('look-controls')
const camera = new THREE.PerspectiveCamera( 75, 1, 0.1, 1 );
const helper = new THREE.CameraHelper( camera );
let parentEl = document.createElement('a-entity')
parentEl.setAttribute('camera', 'active: false')
parentEl.formerrig = rig
rig.id = 'formerrig'
parentEl.id = 'rig'
parentEl.object3D.add( helper );
parentEl.setAttribute('position', '0 1.6 -1')
AFRAME.scenes[0].appendChild(parentEl)
setTimeout( _ => AFRAME.scenes[0].setAttribute('secondcam',''), 200)
return parentEl
}
function swappingBackRigVirtualRig(){
if (rig.formerrig){
virtualrig = rig
rig.id = 'virtualrig'
virtualrig.formerrig.id = 'rig'
}
}
navigator.xr?.isSessionSupported('immersive-vr').then((supported) => {
if (supported) {
desktopbutton.disabled = true
}
})
function desktopTutorMode(){
// should block this in XR
// can happen to tab to the button, enter, and get stuck out
/*
grid.setAttribute('scale', '.05 .05 .05')
grid.setAttribute('position', '-.25 1.4 -1')
// need to adjust rig position with the new scale though
// breaks the shortcut re-use
*/
rig.setAttribute('position', '10 10 10')
// instead teleporting above
// similar result than scaling
addVirtualRig()
//rig.formerrig.object3D.lookAt( new THREE.Vector3(0,0,0) )
rig.formerrig.setAttribute('rotation', '-20 45 0')
consolehud.setAttribute('value','')
// could show fake keys
cam.style.display = 'block'
}
// consider walls around tiles
// jxr toggle for each could be put at the bottom to raise/lower wall
// could be displayed only once on the current tile to limit visual clutter
// can clone an rotate in order to match the tile color, size, etc
// but need new id and reset opacity
// could also be appended to current tile to have relative position
// could be in 3 vertical positions, e.g. low 0m, mid 1m, high 2m
// could have an outline but inner portion in white or black to improve readibility
function drawWalkableGridForTutor(parentEl=null, tileName = 'tile_', separator = '_'){
if (parentEl == null) {
parentEl = document.createElement('a-entity')
parentEl.id = 'grid'
}
// could be as param
parentEl.setAttribute('position', '-5 0 -5')
for (let y=0; y<10;y++)
for (let x=0; x<10;x++) {
let el = document.createElement('a-box')
el.id = tileName+x+separator+y
el.setAttribute('height', .01)
let g = ((y+1)*9)
if (g < 10) g = 10
let b = ((x+1)*9)
if (b < 10) b = 10
el.setAttribute('color', '#00'+ g + b)
el.setAttribute('width', .9)
el.setAttribute('depth', .9)
el.setAttribute('position', x + ' 0 ' + y)
parentEl.appendChild( el )
}
AFRAME.scenes[0].appendChild( parentEl )
return parentEl
}
function addVerticalTile(x=2, y=2, direction='North', verticalPos=0){
const tileName = 'tile_'
const separator = '_'
let parent = document.getElementById(tileName + x + separator + y )
let el = document.createElement('a-box')
el.id = 'tile_'+y+'_'+x+'_'+direction+'_'+verticalPos
el.setAttribute('width', .01)
el.setAttribute('depth', .9)
el.setAttribute('height', .9)
el.setAttribute('color', parent.getAttribute('color') )
let g = ((y+1)*9)
if (g < 10) g = 10
let b = ((x+1)*9)
if (b < 10) b = 10
el.setAttribute('color', '#00'+ g + b)
switch (direction) {
case 'North' :
el.setAttribute('rotation', '0 90 0')
el.object3D.translateZ( -.5)
break
case 'South' :
el.setAttribute('rotation', '0 90 0')
el.object3D.translateZ( .5)
break
case 'East' :
el.object3D.translateX( .5)
break
case 'West' :
el.object3D.translateX(- .5)
break
}
el.object3D.translateY(verticalPos + .5)
parent.appendChild( el )
}
function lightPathOnGrid(path=[], attribute='opacity', value=.7){
tileName = 'tile_',
separator = '_'
path.map( p => document.getElementById(tileName + p[0] + separator + p[1] ).setAttribute(attribute,value) )
}
setTimeout( _ => {
colorizeString()
drawWalkableGridForTutor()
lightPathOnGrid([ [0,0], [1,0], [2,0], [3,0], [4,0], [5,0], [5,1], [5,2], [5,3], [5,4], [5,5] ])
// tile the north wall, bottom
for (let y=0; y<10;y++) addVerticalTile(y,0)
// to go up for
for (let y=0;y<10;y++) addVerticalTile(y,0, 'North', 1)
for (let y=0;y<10;y++) addVerticalTile(y,0, 'North', 2)
//addMark("x", rig.getAttribute("position"))
// useful for testing, could add some in corners
parseURL()
popoverUserAction.innerHTML = '<h2>userActions</h2>' + userActions.map( a => {
return `
${a.key?htmlButtonFromKey(a.key)+':':''}
${a.seq?a.seq.split('').map(k=>htmlButtonFromKey(k, a.seq))+':':''}
${a.regex?a.regex+':':''}
${a.action}`
//return `${a.key?a.key+':':''}${a.regex?a.regex+':':''}${a.action}`
// unfortunately sequences can't just be played back...
}).join('<br>')
}, 600)
function htmlButtonFromKey(k, seq=''){
return `<button onclick=clicked('${k}',this) class="kbc-button" ${seq?'seq='+seq:''} data-keyboard-key="${k.toUpperCase()}">${k.toUpperCase()}</button>`
}
// 1-liner for completion
// textForCompletion.split(' ').filter(w=>w.startsWith('hel'))
// to bind to Ctrln aka control+n
// rich sequences aren't supported
// try intersection as tab focus
// e.g. gg without looking at a tab brings back to center
// but gg looking at a tab brings the carret to its top
// can be tested with cursor component
// might prefer explicit selection first, e.g. pressing enter while looking at a tab to execute commands on it
// alternative highlight solution
// clone text exactly on top, only change color but no depth offset
// replace higlighted section by " "
// replace non-highlight by " " on clone
// detected keypress also means we know where we are in the physical space
// thus behave accordingly, e.g re-center pose, or not
// can be manually toggled on/off in order to accomodate also for mobile keyboard, e.g. on pants
// also means that keypress with hand tracking let us know where the keyboard is
// 2nd different keypress give us the orientation of they keyboard as keys are fixed with known relative distance
// should warn of executed action via HUD instead of just console
// especially if typing in non default mode (for now, always ex) in order to be able to correct
// should basically display seq.
const fontCharSize = .1225
const stepSize = fontCharSize // should be calculated from letter size of a monospace font
let pos = 0
setInterval( _ => {
pos++
let y = -2 * fontCharSize
carret.setAttribute('position', -fontCharSize/2 + pos * stepSize + ' ' + y + ' 0')
}, 1000)
let x = -fontCharSize/2000 + ('use '.length) * stepSize
let y = 2 * fontCharSize
highlight.setAttribute('position', x + ' ' + y + ' .001')
// could rely on argos as it proves a JSON file but unfortunately numerical values for keys
// might be qmkKeycodesVersion but no idea how to convert
// also note that the configurations between Dilemma and Piantor Pro (used in XR) are nearly identical but not 100% so, e.g bt controls
fetch( 'keymap.txt' ).then( res => res.text() ).then( res => {
// warning : not all layers are in use, see from layer 0
let userLayers = [0, 4, 6, 7, 8, 5] // cf lt keys of layer 0.
// to verify, might have an offset ... the functions keys dont seem right
let parsedLayers = []
userLayers.map( layerNumber => {
l = res.split('\n').at(layerNumber).split('&').slice(1,37).map( c => c.replace('kp ','').trim() )
layers = [l.slice(0,10), l.slice(10,20), l.slice(20,30), l.slice(30,40)]
parsedLayers.push( layers )
txtlayer = layers.join('\n')
console.log( txtlayer )
layertest.setAttribute('value', txtlayer)
// could also split in left/right parts.
})
AFRAME.scenes[0].addEventListener('layersloaded', event => { parseLayers(event.detail) })
AFRAME.scenes[0].emit('layersloaded', parsedLayers)
console.log('emitted layersloaded')
})
function addMark(key, pos){
// assume there is no matching existing one
userActions.push( { seq: 'go'+key, action: 'rig.setAttribute("position", "'
+ AFRAME.utils.coordinates.stringify( pos )
+'")' } )
// visual representation, e.g. label at floor level
let el = document.createElement('a-text')
pos.y += .2
el.setAttribute('position', AFRAME.utils.coordinates.stringify( pos ) )
el.setAttribute('value', 'mark ' + key + '\n(reach using go'+key+')')
el.setAttribute('scale', '.1 .1 .1')
el.setAttribute('font', 'monoid')
el.setAttribute('rotation', '-90 0 0')
el.id = 'mark_' + key
AFRAME.scenes[0].appendChild( el )
// could also be used for tutor
}
function bind(constraintType, value, mods = [], action = 'console.log("no action yet")' ){
let newBinding = {}
newBinding[constraintType] = value
newBinding["action"] = action
userActions.push(newBinding)
console.log('added', userActions.at(-1) )
}
function bindFromLatestExecutedSnippet(){
// use the latest key
// testable with z
// seems to be null, could forcing z for now
if (key == null)
bind('key', 'z', [], executionsHistory.at(-1) )
else
bind('key', key, [], executionsHistory.at(-1) )
// consinder providing the binding as another snipper, made with insert then Enter
// e.g. movedSnippets.at(-1).getAttribute('value')
}
function unbind(k){
// only for key, should also cover mods, seq, regex
userActions = userActions.filter(e => { if (!e.key || (e.key && e.key != k)) return e })
}
// could extend or even replace userActions by a custom Vim in VR one, e.g
userActions = [
{ key: 'n', mods: ['Control'], action: 'console.log("should complete")'}, // overwritten by browser itself it seems
{ key: 'l', mods: ['Control'], action: 'consolehud.setAttribute("value", "")'},
{ seq: 'gg', action: 'rig.setAttribute("position", "0 0 0")' },
// at least one insert mode should be available, e.g. i/a/o/I/A/O to be able to add content, esp. code
// requires edition mode, for that see https://git.benetou.fr/utopiah/text-code-xr-engine
{ seq: 'mx', action: 'addMark("x", rig.getAttribute("position"))' },
// see the regex below instead to generalize it
// gets executed once out of twice, first time doing m then x
// investigate seq value at each keypress, cf console
{ key: 'h', action: 'rig.object3D.translateX(-1)'},
{ key: 'l', action: 'rig.object3D.translateX(1)'},
{ key: 'j', action: 'rig.object3D.translateZ(-1)'},
{ key: 'k', action: 'rig.object3D.translateZ(1)'},
// warning, this does not take into account camera rotation
// we stay on a grid
{ seq: 'G', action: 'rig.setAttribute("position", "0 0 5")' }, // arguable, could set only z
{ seq: '$', action: 'rig.setAttribute("position", "5 0 0")' }, // same
{ seq: '^', action: 'rig.setAttribute("position", "-5 0 0")' }, // same
// let mode = 'default'
{ key: 'i', action: 'mode="insert"'},
{ key: ':', action: 'mode="exec"'}, // not yet implemented
{ key: 'v', action: 'mode="visual"'}, // not yet implemented
// non VR specific, to replace or skip, left there for inspiration
// consider richSeq instead
{ regex: /^m[a-zA-Z0-9_]$/, action: 'console.log("matched regex")'},
{ regex: /^\d+$/, action: 'repeats = Number(seq)'},
{ key: '.', action: 'doAction(actionsExecuted.at(-1))'}, // untested in the extension context, might lack scope
// repeats also motions, bit different
/*
{ seq: 'gtm', action: 'window.open("https://twitter-archive.benetou.fr/")'},
{ key: 'G', mods: ['Shift'], action: 'window.scrollTo(0, document.body.scrollHeight)'},
{ key: 'E', mods: ['Shift'], action: 'window.location += "?action=edit"'},
// this now prevent any binding on g
{ key: 'r', action: 'window.location.reload()'},
{ key: 'x', action: 'autoscroll()'},
{ key: 'e', action: 'loadScript("https://cdn.jsdelivr.net/npm/eruda", "eruda.init()")'},
// does not work as extension but works in testing.html
{ key: 'b', action: 'history.back()'},
{ key: 'B', mods: ['Shift'], action: 'blocked = !blocked'}, // can not be unblocked, need to refresh the page
{ key: 'a', action: 'addWiki()'},
{ key: 'n', action: 'firstTab()'},
{ key: 'P', mods: ['Shift'], action: 'window.open("https://account.proton.me/")'},
{ key: 'i', action: 'window.open("https://fabien.benetou.fr")'},
// could be generalize to any bookmarks but needs to be set first, should not be hardcded like here
// for multiple ones would have to handle successive keys, e.g. gtH for go to Home
// currently handling single key with modifiers
{ key: '?', action: 'alert("r to reload, h for help, etc")'},
{ key: '?', mods: ['Alt'], action: 'alert("modified help!")'},
*/
]
var context = new AudioContext();
// works by clicking anywhere on the page but fails on location.reload() despite immersive mode working
function osc(freq=800,dur=100, type="sine"){
var oscillator = context.createOscillator()
oscillator.type = type
// use anything but sine for something more electronic sounding
// "square", "sawtooth", "triangle"
oscillator.frequency.value = freq
var gainNode = context.createGain()
oscillator.connect(gainNode)
gainNode.gain.value = .1
gainNode.connect(context.destination)
//oscillator.connect(context.destination)
oscillator.start()
// Beep for 500 milliseconds
setTimeout(function () {
oscillator.stop()
}, dur)
}
// started from https://stackoverflow.com/a/29641185
// consider muted (boolean) as a way to mute audio, could be bind to e.g. ^m
// could also expose gain, a single value
// between osc(50, 50) and osc(1000, 500) gives usable values, beyond that probably unpleasant for most
// 261.63 for middle C
let namedSounds = {
beep: [50, 50],
boop: [1000, 500],
bizz: [200, 500, "sawtooth"],
}
// to then call with osc( ...namedSounds.bizz )
// can be used interactively, then saved, then named
</script>
testing kbd.js without being an extension proper (might miss some permissions)
<br>
<br>
this is a <a href=. >link</a> to follow
<br>
and this is another link to the <a href=https://git.benetou.fr/utopiah/keyboard-extension >repository</a> to potentially follow
<br>
this is an input field <input autofocus /> then a text area <br>
<textarea></textarea>
</html>