smooth ladder dragging!

This commit is contained in:
Tim
2024-02-12 01:14:33 -04:00
parent 00ac45dafc
commit 4c5267d279
5 changed files with 155 additions and 159 deletions

View File

@@ -1,28 +1,20 @@
import {useChartOrderStore} from "@/orderbuild.js"; import {useChartOrderStore} from "@/orderbuild.js";
import {invokeCallbacks, prototype} from "@/common.js"; import {invokeCallbacks, prototype} from "@/common.js";
import datafeed from "./datafeed.js";
export let widget = null export let widget = null
export let chart = null export let chart = null
export let crosshairPoint = null export let crosshairPoint = null
const subscribeEvents = [ const subscribeEvents = [
'activeChartChanged', 'add_compare', 'chart_load_requested', 'chart_loaded', 'compare_add', 'drawing', 'toggle_sidebar', 'indicators_dialog', 'toggle_header', 'edit_object_dialog', 'chart_load_requested',
'drawing_event', 'edit_object_dialog', 'indicators_dialog', 'layout_about_to_be_changed', 'layout_changed', 'chart_loaded', 'mouse_down', 'mouse_up', 'drawing', 'study', 'undo', 'redo', 'undo_redo_state_changed',
'load_study_template', 'mouse_down', 'mouse_up', 'onAutoSaveNeeded', 'onMarkClick', 'onPlusClick', 'reset_scales', 'compare_add', 'add_compare', 'load_study_template', 'onTick', 'onAutoSaveNeeded',
'onScreenshotReady', 'onSelectedLineToolChanged', 'onTick', 'onTimescaleMarkClick', 'panes_height_changed', 'onScreenshotReady', 'onMarkClick', 'onPlusClick', 'onTimescaleMarkClick', 'onSelectedLineToolChanged',
'panes_order_changed', 'redo', 'reset_scales', 'series_event', 'series_properties_changed', 'study', 'study_event', 'layout_about_to_be_changed', 'layout_changed', 'activeChartChanged', 'series_event', 'study_event',
'study_properties_changed', 'toggle_header', 'toggle_sidebar', 'undo', 'undo_redo_state_changed', 'drawing_event', 'study_properties_changed', 'series_properties_changed', 'panes_height_changed',
'panes_order_changed',
] ]
function mouseDown() {
// console.log('mouseDown')
// console.log('selection', chart.selection().allSources())
}
function crosshairMoved({time,price}) {
console.log('crosshair', time, price)
}
export function initWidget(el) { export function initWidget(el) {
widget = window.tvWidget = new TradingView.widget({ widget = window.tvWidget = new TradingView.widget({
@@ -37,17 +29,19 @@ export function initWidget(el) {
// datafeed: datafeed, // use this for ohlc // datafeed: datafeed, // use this for ohlc
locale: "en", locale: "en",
disabled_features: [], disabled_features: [],
enabled_features: [], enabled_features: ['saveload_separate_drawings_storage'],
drawings_access: {type: 'white', tools: [],}, // show no tools drawings_access: {type: 'white', tools: [],}, // show no tools
}); });
// debug dump all events
// for( const event of subscribeEvents )
// widget.subscribe(event, ()=>console.log('event', event, arguments))
widget.subscribe('drawing_event', handleDrawingEvent) widget.subscribe('drawing_event', handleDrawingEvent)
widget.subscribe('onSelectedLineToolChanged', onSelectedLineToolChanged) widget.subscribe('onSelectedLineToolChanged', onSelectedLineToolChanged)
widget.onChartReady(initChart)
widget.subscribe('mouse_down', mouseDown) widget.subscribe('mouse_down', mouseDown)
widget.subscribe('mouse_up', mouseUp)
// for( const event of subscribeEvents ) widget.onChartReady(initChart)
// widget.subscribe(event, ()=>console.log(event, arguments))
} }
@@ -55,41 +49,26 @@ export function initWidget(el) {
function initChart() { function initChart() {
console.log('init chart') console.log('init chart')
chart = widget.activeChart() chart = widget.activeChart()
chart.crossHairMoved().subscribe(null, (point)=>{ chart.crossHairMoved().subscribe(null, (point)=>setTimeout(()=>handleCrosshairMovement(point),0) )
crosshairPoint=point
const co = useChartOrderStore()
invokeCallbacks(co.drawingCallbacks, 'onRedraw')
})
useChartOrderStore().chartReady = true useChartOrderStore().chartReady = true
} }
// noinspection JSUnusedLocalSymbols // noinspection JSUnusedLocalSymbols
export const ShapeCallback = { export const ShapeCallback = {
onDraw: () => { onDraw: () => {}, // start drawing a new shape for the builder
}, // start drawing a new shape for the builder onRedraw: () => {}, // the mouse moved while in drawing mode
onRedraw: () => { onUndraw: () => {}, // drawing was canceled by clicking on a different tool
}, // the mouse moved while in drawing mode onAddPoint: () => {}, // the user clicked a point while drawing (that point is added to the points list)
onUndraw: () => { onCreate: (shapeId, points, props) => {}, // the user has finished creating all the control points. drawing mode is exited and the initial shape is created.
}, // drawing was canceled by clicking on a different tool onPoints: (shapeId, points) => {}, // the control points of an existing shape were changed
onAddPoint: () => { onProps: (shapeId, props) => {}, // the display properties of an existing shape were changed
}, // the user clicked a point while drawing (that point is added to the points list) onMove: (shapeId, points) => {}, // the entire shape was moved without dragging control points
onCreate: (shapeId, points, props) => { onDrag: (shapeId, points) => {}, // the shape is being dragged: this gets called on every mouse movement update during a drag
}, // the user has finished creating all the control points. drawing mode is exited and the initial shape is created. onHide: (shapeId, props) => {},
onPoints: (shapeId, points) => { onShow: (shapeId, props) => {},
}, // the control points of an existing shape were changed onClick: (shapeId) => {}, // the shape was selected
onProps: (shapeId, props) => { onDelete: (shapeId) => {},
}, // the display properties of an existing shape were changed
onMove: (shapeId, points) => {
}, // the entire shape was moved. todo same as onPoints?
onHide: (shapeId, props) => {
},
onShow: (shapeId, props) => {
},
onClick: (shapeId) => {
}, // the shape was selected
onDelete: (shapeId) => {
},
} }
@@ -103,6 +82,7 @@ export const VerboseCallback = prototype(ShapeCallback, {
onPoints: (shapeId, points)=>{console.log('onPoints')}, onPoints: (shapeId, points)=>{console.log('onPoints')},
onProps: (shapeId, props)=>{console.log('onProps')}, onProps: (shapeId, props)=>{console.log('onProps')},
onMove: (shapeId, points)=>{console.log('onMove')}, onMove: (shapeId, points)=>{console.log('onMove')},
onDrag: (shapeId, points) => {console.log('onDrag')},
onHide: (shapeId, props)=>{console.log('onHide')}, onHide: (shapeId, props)=>{console.log('onHide')},
onShow: (shapeId, props)=>{console.log('onShow')}, onShow: (shapeId, props)=>{console.log('onShow')},
onClick: (shapeId)=>{console.log('onClick')}, onClick: (shapeId)=>{console.log('onClick')},
@@ -110,23 +90,6 @@ export const VerboseCallback = prototype(ShapeCallback, {
}) })
export const BuilderUpdateCallback = prototype(ShapeCallback,{
onCreate(shapeId, points, props) {
this.builder.shapes[this.tag] = shapeId;
},
onPoints(shapeId, points) {
this.builder.points[this.tag] = points;
},
onProps(shapeId, props) {
this.builder.props[this.tag] = props;
},
onMove(shapeId, points) {
this.builder.points[this.tag] = points;
},
})
export function drawShape(shapeType, ...callbacks) { export function drawShape(shapeType, ...callbacks) {
// puts the chart into a line-drawing mode for a new shape // puts the chart into a line-drawing mode for a new shape
console.log('drawShape', callbacks, shapeType.name, shapeType.code) console.log('drawShape', callbacks, shapeType.name, shapeType.code)
@@ -155,7 +118,7 @@ export function createShape(shapeType, points, options={}, ...callbacks) {
shapeId = chart.createMultipointShape(points, options) shapeId = chart.createMultipointShape(points, options)
if( callbacks.length ) if( callbacks.length )
shapeCallbacks[shapeId] = callbacks shapeCallbacks[shapeId] = callbacks
console.log('created shape', shapeId) console.log(`created ${shapeType.name}`, shapeId)
const props = chart.getShapeById(shapeId).getProperties() const props = chart.getShapeById(shapeId).getProperties()
invokeCallbacks(callbacks, 'onCreate', shapeId, points, props) invokeCallbacks(callbacks, 'onCreate', shapeId, points, props)
return shapeId return shapeId
@@ -171,33 +134,6 @@ export function cancelDrawing() {
} }
export function builderUpdater(builder, tag='a') {
return prototype(BuilderUpdateCallback, {builder,tag})
}
export function builderShape(builder, tag, shapeType, ...callbacks) {
const updater = builderUpdater(builder, tag)
console.log('updater', updater)
drawShape(shapeType, updater, ...callbacks)
}
export function setPoints( shapeId, points ) {
if( points.time || points.price )
points = [points]
console.log('setting points', shapeId, points)
let shape
try {
shape = chart.getShapeById(shapeId)
}
catch (e) {
return
}
shape.setPoints(points)
}
const shapeCallbacks = {} const shapeCallbacks = {}
function onSelectedLineToolChanged() { function onSelectedLineToolChanged() {
@@ -207,12 +143,65 @@ function onSelectedLineToolChanged() {
cancelDrawing(); cancelDrawing();
} }
export let dragging = false
function mouseDown() {
// console.log('mouseDown')
dragging = true
}
function mouseUp() {
// console.log('mouseUp')
dragging = false
draggingShapeIds = []
}
export let draggingShapeIds = []
function handleCrosshairMovement(point) {
crosshairPoint = point
const co = useChartOrderStore()
if (co.drawing)
invokeCallbacks(co.drawingCallbacks, 'onRedraw')
else if (dragging) {
draggingShapeIds = chart.selection().allSources();
// console.log('dragging selected', draggingShapeIds)
for (const shapeId of draggingShapeIds) {
const shape = chart.getShapeById(shapeId);
const points = shape.getPoints();
// console.log(`dragging ${shapeId}`, shape, points1, points2, points3)
// invokeCallbacks(shapeCallbacks[shapeId], 'onDrag', shapeId, points)
// console.log('calling onPoints')
invokeCallbacks(shapeCallbacks[shapeId], 'onPoints', shapeId, points)
}
}
else if (draggingShapeIds.length > 0) {
draggingShapeIds = []
}
}
let drawingEventQueue = []
function handleDrawingEvent(id, event) { function handleDrawingEvent(id, event) {
setTimeout(()=>doHandleDrawingEvent(id,event), 0) // it's important to decouple our actions from the TV thread. we must wait until the TV loop is completed
// before interacting with the chart
if (drawingEventQueue.length===0)
setTimeout(drawingEventWorker,0)
drawingEventQueue.push([id,event])
}
function drawingEventWorker() {
const queue = drawingEventQueue
drawingEventQueue = []
for (const [id,event] of queue)
doHandleDrawingEvent(id,event)
} }
function doHandleDrawingEvent(id, event) { function doHandleDrawingEvent(id, event) {
console.log('drawing event', arguments) // console.log('drawing event', arguments)
const shape = event === 'remove' ? null : chart.getShapeById(id); const shape = event === 'remove' ? null : chart.getShapeById(id);
if (event === 'create') { if (event === 'create') {
const co = useChartOrderStore(); const co = useChartOrderStore();
@@ -267,6 +256,6 @@ function doHandleDrawingEvent(id, event) {
export function deleteShapeId(id) { export function deleteShapeId(id) {
if( id in shapeCallbacks ) if( id in shapeCallbacks )
delete shapeCallbacks[id] delete shapeCallbacks[id]
console.log('removing entity', id) // console.log('removing entity', id)
chart.removeEntity(id) chart.removeEntity(id)
} }

View File

@@ -1,7 +1,7 @@
// noinspection JSPotentiallyInvalidUsageOfThis // noinspection JSPotentiallyInvalidUsageOfThis
import {invokeCallback} from "@/common.js"; import {invokeCallback} from "@/common.js";
import {chart, createShape, deleteShapeId, drawShape} from "@/charts/chart.js"; import {chart, createShape, deleteShapeId, dragging, draggingShapeIds, drawShape} from "@/charts/chart.js";
// //
@@ -69,7 +69,6 @@ class Shape {
// programatically create the shape using the current this.points // programatically create the shape using the current this.points
const points = this.pointsFromModel() const points = this.pointsFromModel()
if( points && points.length ) { if( points && points.length ) {
console.log(`create ${this.type.name}`)
this.doCreate(points) this.doCreate(points)
} }
} }
@@ -89,8 +88,12 @@ class Shape {
} }
tvShape() {
return this.id === null ? null : chart.getShapeById(this.id);
}
setModel(model) { setModel(model) {
console.log('setModel', model, this.id)
for( const [k,v] of Object.entries(model)) for( const [k,v] of Object.entries(model))
this.model[k] = v this.model[k] = v
this.setPoints(this.pointsFromModel()); this.setPoints(this.pointsFromModel());
@@ -99,23 +102,32 @@ class Shape {
setPoints(points) { setPoints(points) {
// invokeCallback(this, 'onPoints', points)
if (points !== null && points.length) { if (points !== null && points.length) {
if (this.id === null) if (this.id === null)
this.doCreate(points) this.doCreate(points)
else { else {
const s = this.tvShape();
if (!dragging) {
this.pointsLock++ this.pointsLock++
chart.getShapeById(this.id).setPoints(points) s.setPoints(points)
}
else {
// quiet setPoints doesn't disturb tool editing mode
const i = s._pointsConverter.apiPointsToDataSource(points)
// s._model.startChangingLinetool(this._source)
s._model.changeLinePoints(s._source, i)
// s._model.endChangingLinetool(!0)
s._source.createServerPoints()
}
} }
} }
} }
setProps(props) { setProps(props) {
// invokeCallback(this, 'onProps', props)
if(this.id) { if(this.id) {
this.propsLock++ this.propsLock++
chart.getShapeById(this.id).setProperties(props) this.tvShape().setProperties(props)
} }
} }
@@ -126,6 +138,11 @@ class Shape {
} }
beingDragged() {
return draggingShapeIds.indexOf(this.id) !== -1
}
delete() { delete() {
// console.log('shape.delete', this.id) // console.log('shape.delete', this.id)
if (this.id === null) return if (this.id === null) return
@@ -165,6 +182,7 @@ class Shape {
onPoints(points) {} // the control points of an existing shape were changed onPoints(points) {} // the control points of an existing shape were changed
onProps(props) {} // the display properties of an existing shape were changed onProps(props) {} // the display properties of an existing shape were changed
onMove(points) {} // the shape was moved by dragging a drawing element not the control point onMove(points) {} // the shape was moved by dragging a drawing element not the control point
onDrag(points) {}
onHide(props) {} onHide(props) {}
onShow(props) {} onShow(props) {}
onClick() {} // the shape was selected onClick() {} // the shape was selected
@@ -201,17 +219,14 @@ class ShapeTVCallbacks {
} }
onPoints(shapeId, points) { onPoints(shapeId, points) {
console.log(`shapetvcb ${shapeId} onPoints`, points, this.shape.lock)
this.shape.points = points this.shape.points = points
if( this.shape.pointsLock ) { if( this.shape.pointsLock ) {
this.shape.pointsLock-- this.shape.pointsLock--
return return
} }
setTimeout(()=>{
this.shape.onPoints(points) this.shape.onPoints(points)
this.shape.pointsToModel() this.shape.pointsToModel()
this.shape.onModel(this.shape.model) this.shape.onModel(this.shape.model)
}, 0)
} }
onProps(shapeId, props) { onProps(shapeId, props) {
@@ -220,11 +235,9 @@ class ShapeTVCallbacks {
this.shape.propsLock-- this.shape.propsLock--
return return
} }
setTimeout(()=>{
this.shape.onProps(props) this.shape.onProps(props)
this.shape.propsToModel() this.shape.propsToModel()
this.shape.onModel(this.shape.model) this.shape.onModel(this.shape.model)
}, 0)
} }
onDraw() { onDraw() {
@@ -252,6 +265,11 @@ class ShapeTVCallbacks {
invokeCallback(this.shape, 'onMove',points) invokeCallback(this.shape, 'onMove',points)
} }
onDrag(_shapeId, points) {
if( this.shape.lock ) return
invokeCallback(this.shape, 'onDrag', points)
}
onHide(_shapeId, props) { onHide(_shapeId, props) {
if( this.shape.lock ) return if( this.shape.lock ) return
invokeCallback(this.shape, 'onHide',props) invokeCallback(this.shape, 'onHide',props)
@@ -283,12 +301,10 @@ export class HLine extends Shape {
pointsFromModel() { pointsFromModel() {
if (this.model.price === null) return null if (this.model.price === null) return null
const time = this.points !== null && this.points.length > 0 ? this.points[0].time : 0 const time = this.points !== null && this.points.length > 0 ? this.points[0].time : 0
console.log(`pointsFromModel ${this.id}`, this.model.price)
return [{time:time, price:this.model.price}] return [{time:time, price:this.model.price}]
} }
pointsToModel() { pointsToModel() {
console.log(`pointsToModel ${this.id}`, this.points[0].price)
this.model.price = this.points[0].price this.model.price = this.points[0].price
} }
@@ -298,5 +314,15 @@ export class HLine extends Shape {
propsToModel() {this.model.color=this.props.linecolor} propsToModel() {this.model.color=this.props.linecolor}
onDrag(points) {
const s = this.tvShape();
console.log('shape', s)
console.log('currentMovingPoint', s._source.currentMovingPoint())
console.log('startMovingPoint', s._source.startMovingPoint())
console.log('isBeingEdited', s._source.isBeingEdited())
console.log('state', s._source.state())
}
} }

View File

@@ -117,7 +117,7 @@ function checkVault() {
ensureVault() ensureVault()
} }
setTimeout(checkVault, 1) setTimeout(checkVault, 0)
</script> </script>

View File

@@ -1,4 +1,5 @@
<template> <template>
{{JSON.stringify(lineA.props)}}
<!-- todo extract builder-panel --> <!-- :builder="builder" color-tag="limit" --> <!-- todo extract builder-panel --> <!-- :builder="builder" color-tag="limit" -->
<v-sheet dense :color="faintColor" class="d-flex align-content-stretch" style="overflow-y: hidden"> <v-sheet dense :color="faintColor" class="d-flex align-content-stretch" style="overflow-y: hidden">
<div :style="colorStyle" style="width:1em">&nbsp;</div> <div :style="colorStyle" style="width:1em">&nbsp;</div>
@@ -59,7 +60,7 @@
<script setup> <script setup>
import {computed} from "vue"; import {computed} from "vue";
import {chart} from "@/charts/chart.js"; import {chart, draggingShapeIds} from "@/charts/chart.js";
import {useChartOrderStore} from "@/orderbuild.js"; import {useChartOrderStore} from "@/orderbuild.js";
import Color from "color"; import Color from "color";
import {HLine} from "@/charts/shape.js"; import {HLine} from "@/charts/shape.js";
@@ -98,10 +99,9 @@ const lineAPrice = computed({
const lineA = new HLine( const lineA = new HLine(
{price:null,color:null}, {price:null,color:null},
(line)=>{props.builder.priceA = line.price; props.builder.color = line.color; adjustShapes()}, function (line) {props.builder.priceA = line.price; props.builder.color = line.color; adjustShapes()},
deleteBuilder deleteBuilder
) )
lineA.onMove = (points)=>console.log('move', points)
const lineBPrice = computed({ const lineBPrice = computed({
get() { return props.builder.priceB }, get() { return props.builder.priceB },
@@ -123,14 +123,11 @@ let interiorLines = []
function createInteriorLine(price) { function createInteriorLine(price) {
const line = new HLine({price: price, color: props.builder.color}, const line = new HLine({price: price, color: props.builder.color},
function (line) { function (line) {
console.log('interior onModel', line.price)
props.builder.color = line.color // todo adjust for saturation props.builder.color = line.color // todo adjust for saturation
}, },
deleteBuilder) deleteBuilder)
line.onPoints = function (points) { line.onPoints = function (points) {
console.log('interior onPoints', points)
const delta = points[0].price - this.model.price const delta = points[0].price - this.model.price
console.log('moving delta', delta)
if (delta !== 0) { if (delta !== 0) {
props.builder.priceA += delta props.builder.priceA += delta
props.builder.priceB += delta props.builder.priceB += delta
@@ -268,9 +265,9 @@ let priceRangeId = null
function adjustShapes() { function adjustShapes() {
// console.log('limit adjust shapes')
const limits = prices.value const limits = prices.value
console.log('limits', limits) // console.log('limits', limits)
const colorStrings = colors.value
if( limits.length === 0 ) { if( limits.length === 0 ) {
lineA.delete() lineA.delete()
lineB.delete() lineB.delete()
@@ -282,39 +279,22 @@ function adjustShapes() {
// //
// SINGLE LINE // SINGLE LINE
// //
if (!lineA.beingDragged())
lineA.setModel({price:limits[0], color: colors.value[0]}) lineA.setModel({price:limits[0], color: colors.value[0]})
lineB.delete() lineB.delete()
if (interiorLines.length) {
for( const line of interiorLines ) for( const line of interiorLines )
line.delete() line.delete()
interiorLines = [] interiorLines = []
} }
}
else { else {
// //
// PRICE RANGE // PRICE RANGE
// //
// todo price range shape if (!lineA.beingDragged())
// first set the price range shaded background
// const rangePoints = [
// {time: start.value, price: lineAPrice.value},
// {time: end.value, price: lineBPrice.value},
// ];
//
// if (priceRangeId !== null)
// setPoints(priceRangeId, rangePoints)
// else {
// priceRangeId = createShape(ShapeType.PriceRange, rangePoints, {
// disableSave: true, disableSelection: true, disableUndo: true, lock: true,
// // https://www.tradingview.com/charting-library-docs/latest/customization/overrides/Shapes-and-Overrides
// overrides: {
// fillLabelBackground: false,
// lineccolor: props.builder.color,
// backgroundColor: faintColor.value,
// },
// })
// }
const colorStrings = colors.value
lineA.setModel({price:limits[0], color: colorStrings[0]}) lineA.setModel({price:limits[0], color: colorStrings[0]})
if (!lineB.beingDragged())
lineB.setModel({price:limits[limits.length-1], color: colorStrings[colorStrings.length-1]}) lineB.setModel({price:limits[limits.length-1], color: colorStrings[colorStrings.length-1]})
const numInterior = Math.max(0,limits.length-2); const numInterior = Math.max(0,limits.length-2);
@@ -327,10 +307,11 @@ function adjustShapes() {
const limit = limits[1+i] const limit = limits[1+i]
if (i === interiorLines.length) if (i === interiorLines.length)
createInteriorLine(limit) createInteriorLine(limit)
else else if (!interiorLines[i].beingDragged())
interiorLines[i].setModel({price:limit, color: colorStrings[1+i]}) interiorLines[i].setModel({price:limit, color: colorStrings[1+i]})
} }
} }
} }

View File

@@ -16,7 +16,7 @@ export class SingletonCoroutine {
invoke(/*arguments*/) { invoke(/*arguments*/) {
this.args = arguments this.args = arguments
console.log('invoke', arguments) // console.log('invoke', arguments)
if( this.timeout === null ) if( this.timeout === null )
this.timeout = setTimeout(this.onTimeout, this.delay, this) this.timeout = setTimeout(this.onTimeout, this.delay, this)
} }