Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/jquery.enjoyhint.css
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
font-weight: normal;
font-style: normal;
}

.enjoyhint {
position: fixed;
width: 100%;
Expand Down Expand Up @@ -321,6 +322,9 @@

.enjoy_hint_label {
position: absolute;
max-width: 90%;
max-height: 90%;
overflow: hidden;
color: white;
z-index: 107;
font-size: 22px;
Expand Down
83 changes: 74 additions & 9 deletions src/jquery.enjoyhint.js
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,7 @@ CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
that.hide();
that.options.onSkipClick();
});

that.$next_btn = $("<div>", { class: that.cl.next_btn })
.appendTo(that.enjoyhint)
.html("Next")
Expand Down Expand Up @@ -254,7 +255,7 @@ CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
this.attrs.height,
this.attrs.radius
);
ctx.fillStyle = "red";

ctx.fill();

ctx.globalCompositeOperation = def_comp;
Expand Down Expand Up @@ -635,7 +636,7 @@ CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
var label_left = label.offset().left;
var label_right = label.offset().left + label_w;
var label_top = label.offset().top - $(document).scrollTop();
var label_bottom = label.offset().top + label_h;
var label_bottom = label.offset().top - $(document).scrollTop() + label_h;

var margin = 10;

Expand Down Expand Up @@ -919,9 +920,28 @@ CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
var bottom_offset = body_size.h - (data.center_y + half_h);
var left_offset = data.center_x - half_w;
var right_offset = body_size.w - (data.center_x + half_w);

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Этот алгоритм определения положения лейбла не достаточно хорошо определяет позиции куда лучше всего поставить label.
Например если лейбл очень узкий и высокий, а места сверху больше, чем места справа, но недостаточно для отображения лейбла (и при этом места справа хоть и меньше чем сверху, но достаточно чтоб отобразить лейбл) - то лейбл будет отображен по середине, хотя по логике должен быть отображен справа. Пример такой ситуации:

размеры лейбла: ширина=50 высота=500
Оффсеты:

//          400
//      ___________
//      |         |
//  60  |  20x200 |  20
//      |_________|
//          20

Прогони такой кейс по своему коду и увидишь что код будет пытаться разместить лейбл сверху, он не влезет и будет размещен по центру, хотя справа предостаточно места чтоб его отобразить.

Я могу предложить примерно такое решение (его к стати можно расширить чтоб и позицию по вертикали хорошо определять если надо):

// Массив возможных для размещения лейбла областей:
var areasForLabel = [
    {name: 'right', width: right_offset, height: window.innerHeight},
    {name: 'left', width: left_offset, height: window.innerHeight},
    {name: 'center', width: window.innerWidth, height: window.innerHeight}
];

// Определяем приоритеты по областям для размещения лейбла (от большей области к меньшей), типа:
// ['left', 'right']
var areasPriority = areasForLabel
    .sort((area1, area2) => area2.width - area1.width)
    .map(area => area.name);

// Сохраним величину пространства по горизонтали которое нужно лейблу для отображения:
var label_horizontal_space_required = label_width + label_margin;
var label_vertical_space_required = label_shift_with_label_height;

// Определяем где рендерить лейбл: идем по каждой стороне и пытаемся всунуть лейбл,
// eсли влазит - значит туда и станет.
// По умолчанию предполагается что лейбл вобще никуда не влезет (oversized):
var label_hor_side = 'oversized';
for (var i = 0; i < areasPriority.length; i++) {
    const areaName = areasPriority[i];
    const area = areasForLabel.find(area => area.name === areaName);
    if (area.width > label_horizontal_space_required && area.height > label_vertical_space_required) {
        label_hor_side = areaName;
        break;
    }
}

switch(label_hor_side) {
    case 'center':
        label_x = window.innerWidth / 2 - label_width / 2;
        break;
    case 'left':
        label_x = data.width ?
            data.center_x - label_width - data.width/2 - 20 :
            data.center_x - label_width - data.radius/2 - 20;
        break;
    case 'right':
        label_x = data.width ?
            data.center_x + data.width/2 + 20 :
            data.center_x + data.radius/2 + 20;
        break;
    case 'oversized':
        setTimeout(function(){
            $('.enjoy_hint_label').css({
                'border-radius': '40px',
                '-webkit-border-radius': '40px',
                '-moz-border-radius': '40px',
                'background-color': '#272A26',
                '-webkit-transition': 'background-color ease-out 0.5s',
                '-moz-transition': 'background-color ease-out 0.5s',
                '-o-transition': 'background-color ease-out 0.5s',
                'transition': 'background-color ease-out 0.5s'
            })
        }, 500)
        label_x = window.innerWidth / 2 - label_width / 2;
        break;
}

var label_hor_side;
// find out the biggest side for showing hint
var offsetsObj = {
'top_offset' : top_offset,
'bottom_offset' : bottom_offset,
'right_offset' : right_offset,
'left_offset' : left_offset
};
var sortedOffsets = [];

for(var offset in offsetsObj) {
sortedOffsets.push([offset, offsetsObj[offset]])
}
sortedOffsets.sort(function(a,b){
return a[1] - b[1]
});

(sortedOffsets[3][0] === 'bottom_offset' || sortedOffsets[3][0] === 'top_offset') ?
label_hor_side = 'center' : (sortedOffsets[3][0] === 'right_offset') ?
label_hor_side = 'right' : label_hor_side = 'left';

var label_hor_side =
body_size.w - data.center_x < data.center_x ? "left" : "right";
var label_ver_side =
body_size.h - data.center_y < data.center_y ? "top" : "bottom";
var label_shift = 150;
Expand All @@ -933,12 +953,57 @@ CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
var label_hor_offset = half_w + label_shift;
var label_ver_offset = half_h + label_shift;

//original: var label_x = (label_hor_side == 'left') ? data.center_x - label_hor_offset - label_width : data.center_x + label_hor_offset;
var label_y =
label_ver_side == "top"
? data.center_y - label_ver_offset - label_height
: data.center_y + label_ver_offset;
var label_x = window.innerWidth / 2 - label_width / 2;

var label_x;
// if hint body bigger than available space change hint styles and label position
function changeHintStyles(){
setTimeout(function(){
$('.enjoy_hint_label').css({
'border-radius': '40px',
'-webkit-border-radius': '40px',
'-moz-border-radius': '40px',
'background-color': '#272A26',
'-webkit-transition': 'background-color ease-out 0.5s',
'-moz-transition': 'background-color ease-out 0.5s',
'-o-transition': 'background-color ease-out 0.5s',
'transition': 'background-color ease-out 0.5s'
})
}, 500)
label_x = window.innerWidth / 2 - label_width / 2
}

if(label_hor_side === 'center') {
if(sortedOffsets[3][1] <= label_shift_with_label_height){
changeHintStyles();
}
else {
label_x = window.innerWidth / 2 - label_width / 2
}
}
else if (label_hor_side === 'left') {
if(sortedOffsets[3][1] <= label_width + label_margin){
changeHintStyles();
}
else {
data.width ?
label_x = data.center_x - label_width - data.width/2 - 20 :
label_x = data.center_x - label_width - data.radius/2 - 20;
}
}
else {
if(sortedOffsets[3][1] <= label_width + label_margin){
changeHintStyles();
}
else {
data.width ?
label_x = data.center_x + data.width/2 + 20 :
label_x = data.center_x + data.radius/2 + 20;
}
}

if (
top_offset < label_shift_with_label_height &&
Expand All @@ -957,7 +1022,7 @@ CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {
});

setTimeout(function(){
var summoryButtonWidth = that.$next_btn.width() + that.$skip_btn.width() + 10;
var summoryButtonWidth = that.$next_btn.width() + that.$skip_btn.width() + 20;
var distance = label_x;

if (summoryButtonWidth + label_x > arrowFinishX) {
Expand All @@ -966,7 +1031,7 @@ CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {

that.$next_btn.css({
left: distance,
top: label_y + label_height + 20
top: label_y + label_height + 40
});

var left_skip = distance + that.$next_btn.width() + 10;
Expand All @@ -977,7 +1042,7 @@ CanvasRenderingContext2D.prototype.roundRect = function(x, y, w, h, r) {

that.$skip_btn.css({
left: left_skip,
top: label_y + label_height + 20
top: label_y + label_height + 40
});
}, 0)

Expand Down