Skip to content

Commit

Permalink
Merge pull request #288 from justinmaurerdotdev/fix-url-length-calcul…
Browse files Browse the repository at this point in the history
…ations

Fix URL length calculations for long Permalinks
  • Loading branch information
jeffpaul committed Oct 27, 2023
2 parents 4fd281f + c2539e4 commit 8941a58
Show file tree
Hide file tree
Showing 5 changed files with 200 additions and 91 deletions.
216 changes: 142 additions & 74 deletions assets/js/admin-autoshare-for-twitter-classic-editor.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
*
* @todo soooo much dependency :facepalm:
*/
(function($) {
(function ($) {
'use strict';

var $tweetPost = $('#autoshare-for-twitter-enable'),
Expand All @@ -12,10 +12,16 @@
$editLink = $('#autoshare-for-twitter-edit'),
$editBody = $('#autoshare-for-twitter-override-body'),
$hideLink = $('.cancel-tweet-text'),
$allowTweetImage = $('#autoshare-for-twitter-tweet-allow-image'),
errorMessageContainer = document.getElementById('autoshare-for-twitter-error-message'),
counterWrap = document.getElementById('autoshare-for-twitter-counter-wrap'),
allowTweetImageWrap = $('.autoshare-for-twitter-tweet-allow-image-wrap'),
$allowTweetImage = $('#autoshare-for-twitter-tweet-allow-image'),
errorMessageContainer = document.getElementById(
'autoshare-for-twitter-error-message'
),
counterWrap = document.getElementById(
'autoshare-for-twitter-counter-wrap'
),
allowTweetImageWrap = $(
'.autoshare-for-twitter-tweet-allow-image-wrap'
),
limit = 280;
const { __, sprintf } = wp.i18n;

Expand All @@ -29,23 +35,26 @@
$tweetText.change(handleRequest);
$tweetPost.change(toggleVisibility);
$allowTweetImage.change(handleRequest);
$editLink.on('click', function() {
$editLink.on('click', function () {
$editBody.slideToggle();
updateRemainingField();
$(this).hide();
});
$tweetText.on('keyup', function() {
$tweetText.on('keyup', function () {
updateRemainingField();
});
$hideLink.on('click', function(e) {
$hideLink.on('click', function (e) {
e.preventDefault();
$('#autoshare-for-twitter-override-body').slideToggle();
$editLink.show();
});
$('input.autoshare-for-twitter-account-checkbox').on('change', handleRequest);
$('input.autoshare-for-twitter-account-checkbox').on(
'change',
handleRequest
);

// Runs on page load to auto-enable posts to be tweeted
window.onload = function(event) {
window.onload = function (event) {
if ('' === adminAutoshareForTwitter.currentStatus) {
handleRequest(event, true);
}
Expand Down Expand Up @@ -77,12 +86,15 @@
function handleRequest(event, status = $tweetPost.prop('checked')) {
let data = {};
let enabledAccounts = [];
$('input.autoshare-for-twitter-account-checkbox:checked').each(function() {
enabledAccounts.push($(this).val());
});
$('input.autoshare-for-twitter-account-checkbox:checked').each(
function () {
enabledAccounts.push($(this).val());
}
);
data[adminAutoshareForTwitter.enableAutoshareKey] = status;
data[adminAutoshareForTwitter.tweetBodyKey] = $tweetText.val();
data[adminAutoshareForTwitter.allowTweetImageKey] = $allowTweetImage.prop('checked');
data[adminAutoshareForTwitter.allowTweetImageKey] =
$allowTweetImage.prop('checked');
data[adminAutoshareForTwitter.tweetAccountsKey] = enabledAccounts;
$('#publish').prop('disabled', true);

Expand All @@ -92,14 +104,14 @@
method: 'POST',
parse: false, // We'll check the response for errors.
})
.then(function(response) {
.then(function (response) {
if (!response.ok) {
throw response;
}

return response.json();
})
.then(function(data) {
.then(function (data) {
errorMessageContainer.innerText = '';

$icon.removeClass('pending');
Expand All @@ -125,15 +137,38 @@
}

/**
* Updates the counter
* Calculates the permalink length
*/
function updateRemainingField() {
function getPermalinkLength() {
let permalinkLength = 0;
if ( $('#sample-permalink').length ) {
permalinkLength = $('#sample-permalink').text().length
if ($('#sample-permalink').length) {
if (
! adminAutoshareForTwitter.isLocalSite &&
! isNaN( adminAutoshareForTwitter.twitterURLLength )
) {
// According to this page https://developer.twitter.com/en/docs/counting-characters, all URLs are transformed to a uniform length
permalinkLength = Number(
adminAutoshareForTwitter.twitterURLLength
);
} else {
// Calculate the permalink length.
const slug = jQuery('#editable-post-name-full').text();
const aTagContents = jQuery('#sample-permalink > a')[0].innerHTML;
const permalinkPrefix = 'string' === typeof aTagContents ? aTagContents.split('<span')[0] : '';
const permalink = permalinkPrefix + slug + '/';
permalinkLength = permalink.length;
}
}
// +5 because of the space between body and URL and the ellipsis.
permalinkLength += 5;
return permalinkLength;
}

/**
* Updates the counter
*/
function updateRemainingField() {
const permalinkLength = getPermalinkLength();

var count = $tweetText.val().length + permalinkLength;
$tweetText.attr('maxlength', limit - permalinkLength);
Expand All @@ -145,20 +180,27 @@
counterWrap.classList.remove('near-limit');
counterWrap.classList.add('over-limit');
/* translators: %d is tweet message character count */
$(counterWrap).text( sprintf( __( '%d - Too Long!', 'autoshare-for-twitter' ), count ) );
$(counterWrap).text(
sprintf(__('%d - Too Long!', 'autoshare-for-twitter'), count)
);
} else if (240 <= count) {
counterWrap.classList.remove('over-limit');
counterWrap.classList.add('near-limit');
/* translators: %d is tweet message character count */
$(counterWrap).text( sprintf( __( '%d - Getting Long!', 'autoshare-for-twitter' ), count ) );
$(counterWrap).text(
sprintf(
__('%d - Getting Long!', 'autoshare-for-twitter'),
count
)
);
} else {
counterWrap.classList.remove('near-limit');
counterWrap.classList.remove('over-limit');
}
}

// Update the counter when the permalink is changed.
$( '#titlediv' ).on( 'focus', '.edit-slug', function() {
$('#titlediv').on('focus', '.edit-slug', function () {
updateRemainingField();
});

Expand All @@ -172,21 +214,25 @@
}

// Show/Hide "Use featured image in Tweet" checkbox.
if ( allowTweetImageWrap && wp.media.featuredImage ) {
if (allowTweetImageWrap && wp.media.featuredImage) {
toggleAllowImageVisibility();
// Listen event for add/remove featured image.
wp.media.featuredImage.frame().on( 'select', toggleAllowImageVisibility );
$('#postimagediv').on( 'click', '#remove-post-thumbnail', toggleAllowImageVisibility );
wp.media.featuredImage.frame().on('select', toggleAllowImageVisibility);
$('#postimagediv').on(
'click',
'#remove-post-thumbnail',
toggleAllowImageVisibility
);
}

/**
* Show/Hide accounts and visibility options.
*/
function toggleVisibility( event ) {
toggleAllowImageVisibility( event );
function toggleVisibility(event) {
toggleAllowImageVisibility(event);
const autoshareEnabled = $tweetPost.prop('checked');
const accountsWrap = $('.autoshare-for-twitter-accounts-wrapper');
if ( autoshareEnabled ) {
if (autoshareEnabled) {
accountsWrap.show();
} else {
accountsWrap.hide();
Expand All @@ -196,74 +242,96 @@
/**
* Show/Hide "Use featured image in Tweet" checkbox.
*/
function toggleAllowImageVisibility( event ) {
function toggleAllowImageVisibility(event) {
let hasMedia = wp.media.featuredImage.get();
// Handle remove post thumbnail click
if( event && event.target && 'remove-post-thumbnail' === event.target.id && 'click' === event.type ) {
if (
event &&
event.target &&
'remove-post-thumbnail' === event.target.id &&
'click' === event.type
) {
hasMedia = -1;
}

const tweetNow = $('#tweet_now').length;
const autoshareEnabled = $tweetPost.prop('checked');
// Autoshare is enabled and post has featured image.
if ( hasMedia > 0 && ( autoshareEnabled || tweetNow ) ) {
if (hasMedia > 0 && (autoshareEnabled || tweetNow)) {
allowTweetImageWrap.show();
} else {
allowTweetImageWrap.hide();
}
}

// Tweet Now functionality.
$('#tweet_now').on('click', function() {
$("#autoshare-for-twitter-error-message").html('');
$(this).addClass("disabled");
$(".autoshare-for-twitter-tweet-now-wrapper span.spinner").addClass("is-active");
$('#tweet_now').on('click', function () {
$('#autoshare-for-twitter-error-message').html('');
$(this).addClass('disabled');
$('.autoshare-for-twitter-tweet-now-wrapper span.spinner').addClass(
'is-active'
);

const postId = $("#post_ID").val();
const postId = $('#post_ID').val();
const body = new FormData();
body.append( 'action', adminAutoshareForTwitter.retweetAction );
body.append( 'nonce', adminAutoshareForTwitter.nonce );
body.append( 'post_id', postId );
body.append( 'is_classic', 1 );
body.append('action', adminAutoshareForTwitter.retweetAction);
body.append('nonce', adminAutoshareForTwitter.nonce);
body.append('post_id', postId);
body.append('is_classic', 1);

// Send request to Tweet now.
fetch( ajaxurl, {
fetch(ajaxurl, {
method: 'POST',
body,
} )
.then((response) => response.json())
.then((response) => {
if (
response && response.data &&
( ( response.success && response.data.message ) || ( false === response.success && false === response.data.is_retweeted) )
) {
$('.autoshare-for-twitter-status-logs-wrapper').html(response.data.message);
if ( response.data.is_retweeted ) {
$tweetText.val(''); // Reset the tweet text.
}
} else {
$("#autoshare-for-twitter-error-message").html(adminAutoshareForTwitter.unknownErrorText);
}
})
.catch((error) => {
if(error.message){
$("#autoshare-for-twitter-error-message").html(error.message);
} else {
$("#autoshare-for-twitter-error-message").html(adminAutoshareForTwitter.unknownErrorText);
}
})
.finally(() => {
$(this).removeClass("disabled");
$(".autoshare-for-twitter-tweet-now-wrapper span.spinner").removeClass("is-active");
});
.then((response) => response.json())
.then((response) => {
if (
response &&
response.data &&
((response.success && response.data.message) ||
(false === response.success &&
false === response.data.is_retweeted))
) {
$('.autoshare-for-twitter-status-logs-wrapper').html(
response.data.message
);
if (response.data.is_retweeted) {
$tweetText.val(''); // Reset the tweet text.
}
} else {
$('#autoshare-for-twitter-error-message').html(
adminAutoshareForTwitter.unknownErrorText
);
}
})
.catch((error) => {
if (error.message) {
$('#autoshare-for-twitter-error-message').html(
error.message
);
} else {
$('#autoshare-for-twitter-error-message').html(
adminAutoshareForTwitter.unknownErrorText
);
}
})
.finally(() => {
$(this).removeClass('disabled');
$(
'.autoshare-for-twitter-tweet-now-wrapper span.spinner'
).removeClass('is-active');
});
});

// Toggle Tweet Now panel
jQuery("#autoshare_for_twitter_metabox .tweet-now-button").on("click", function(e){
e.preventDefault();
$editBody.show();
jQuery(this).find('span').toggleClass('dashicons-arrow-up-alt2');
jQuery(".autoshare-for-twitter-tweet-now-wrapper").slideToggle();
});

jQuery('#autoshare_for_twitter_metabox .tweet-now-button').on(
'click',
function (e) {
e.preventDefault();
$editBody.show();
jQuery(this).find('span').toggleClass('dashicons-arrow-up-alt2');
jQuery('.autoshare-for-twitter-tweet-now-wrapper').slideToggle();
}
);
})(jQuery);
6 changes: 4 additions & 2 deletions autoshare-for-twitter.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
define( 'AUTOSHARE_FOR_TWITTER_URL', plugin_dir_url( __FILE__ ) );
define( 'AUTOSHARE_FOR_TWITTER_PATH', plugin_dir_path( __FILE__ ) );
define( 'AUTOSHARE_FOR_TWITTER_INC', AUTOSHARE_FOR_TWITTER_PATH . 'includes/' );
define( 'AUTOSHARE_FOR_TWITTER_URL_LENGTH', 23 );

/**
* Get the minimum version of PHP required by this plugin.
Expand All @@ -49,14 +50,14 @@ function site_meets_php_requirements() {
if ( ! site_meets_php_requirements() ) {
add_action(
'admin_notices',
function() {
function () {
?>
<div class="notice notice-error">
<p>
<?php
echo wp_kses_post(
sprintf(
/* translators: %s: Minimum required PHP version */
/* translators: %s: Minimum required PHP version */
__( 'Autoshare for Twitter requires PHP version %s or later. Please upgrade PHP or disable the plugin.', 'autoshare-for-twitter' ),
esc_html( minimum_php_requirement() )
)
Expand All @@ -67,6 +68,7 @@ function() {
<?php
}
);

return;
}

Expand Down
3 changes: 3 additions & 0 deletions includes/admin/assets.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use function TenUp\AutoshareForTwitter\Utils\tweet_image_allowed;
use function TenUp\AutoshareForTwitter\Utils\get_tweet_accounts;
use function TenUp\AutoshareForTwitter\Utils\get_default_autoshare_accounts;
use function TenUp\AutoshareForTwitter\Utils\is_local;

use const TenUp\AutoshareForTwitter\Core\Post_Meta\ENABLE_AUTOSHARE_FOR_TWITTER_KEY;
use const TenUp\AutoshareForTwitter\Core\Post_Meta\TWEET_ACCOUNTS_KEY;
Expand Down Expand Up @@ -211,6 +212,8 @@ function localize_data( $handle = SCRIPT_HANDLE ) {
'tweetAccounts' => $tweet_accounts,
'tweetAccountsKey' => TWEET_ACCOUNTS_KEY,
'connectedAccounts' => $accounts ?? [],
'isLocalSite' => is_local(),
'twitterURLLength' => AUTOSHARE_FOR_TWITTER_URL_LENGTH,
];

wp_localize_script( $handle, 'adminAutoshareForTwitter', $localization );
Expand Down

0 comments on commit 8941a58

Please sign in to comment.