/*
Plugin Name: Teacher Strategy Journal
Description: A comprehensive tool for teachers to manage strategies and student IDs.
Version: 1.0
Author: Your Name
Text Domain: teacher-strategy-journal
*/
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
// Add this function at the top, after the plugin header and before other hooks
// Add this function at the top, after the plugin header and before other hooks
function tsj_get_allowed_student_id_range() {
currentuser=wallowed_min_id = 1;
$allowed_max_id = 300;
Assistant
User
Make svg connecting lines between each rectangle with arrow pointing to the right next rectangle
// AJAX Handler to Remove Student ID
function tsj_remove_student_id_callback() {
global wpdb;table_name = $wpdb->prefix . 'tsj_students';
code
// Check nonce for security
check_ajax_referer('tsj_remove_student_id_nonce', 'csrf_token');
// Get current user
$current_user = wp_get_current_user();
if ( ! $current_user->exists() ) {
wp_send_json_error( array( 'message' => 'Användare är inte inloggad.' ) );
}
$user_id = $current_user->ID;
// Get allowed range
$range = tsj_get_allowed_student_id_range();
$allowed_min_id = $range['min'];
$allowed_max_id = $range['max'];
// Get student ID from POST
$student_id = isset( $_POST['student_id'] ) ? intval( $_POST['student_id'] ) : 0;
// Validate student ID
if ( $student_id < $allowed_min_id || $student_id > $allowed_max_id ) {
wp_send_json_error( array( 'message' => "Student ID måste vara mellan {$allowed_min_id} och {$allowed_max_id}." ) );
}
// Check if student ID exists for the current user
$existing = $wpdb->get_var( $wpdb->prepare(
"SELECT COUNT(*) FROM $table_name WHERE student_id = %d AND user_id = %d",
$student_id,
$user_id
) );
if ( $existing == 0 ) {
wp_send_json_error( array( 'message' => 'Student ID hittades inte eller du har inte behörighet att ta bort det.' ) );
}
// Delete from custom table
$result = $wpdb->delete(
$table_name,
array(
'student_id' => $student_id,
'user_id' => $user_id
),
array( '%d', '%d' )
);
if ( $result === false ) {
wp_send_json_error( array( 'message' => 'Ett fel uppstod vid borttagning av student ID.' ) );
}
wp_send_json_success( array( 'message' => 'Student ID har tagits bort.' ) );
// 3. AJAX Handler to Add Student ID
// Update in tsj_add_student_id_callback function
function tsj_add_student_id_callback() {
global wpdb;table_name = $wpdb->prefix . 'tsj_students';
code
// Check nonce for security
check_ajax_referer('tsj_add_student_id_nonce', 'csrf_token');
// Get current user
$current_user = wp_get_current_user();
if ( !$current_user->exists() ) {
wp_send_json_error( array( 'message' => 'Användare är inte inloggad.' ) );
}
$user_id = $current_user->ID;
// Get allowed range
$range = tsj_get_allowed_student_id_range();
$allowed_min_id = $range['min'];
$allowed_max_id = $range['max'];
// Get student ID from POST
$student_id = isset( $_POST['student_id'] ) ? intval( $_POST['student_id'] ) : 0;
// Validate student ID
if ( $student_id < $allowed_min_id || $student_id > $allowed_max_id ) {
wp_send_json_error( array( 'message' => "Student ID måste vara mellan {$allowed_min_id} och {$allowed_max_id}." ) );
}
// Check for duplicates for the current user
$existing = $wpdb->get_var( $wpdb->prepare(
"SELECT COUNT(*) FROM $table_name WHERE student_id = %d AND user_id = %d",
$student_id,
$user_id
) );
if ( $existing > 0 ) {
wp_send_json_error( array( 'message' => 'Du har redan lagt till detta Student ID.' ) );
}
// Insert into custom table
$result = $wpdb->insert(
$table_name,
array(
'student_id' => $student_id,
'user_id' => $user_id,
),
array(
'%d',
'%d',
)
);
if ( $result === false ) {
wp_send_json_error( array( 'message' => 'Ett fel uppstod vid skapandet av student ID.' ) );
}
wp_send_json_success( array( 'message' => 'Student ID har lagts till.' ) );
}
// Move the AJAX action hooks below the function definition
add_action('wp_ajax_tsj_add_student_id', 'tsj_add_student_id_callback');
add_action('wp_ajax_nopriv_tsj_add_student_id', 'tsj_add_student_id_callback');
// 4. AJAX Handler to Remove Student ID
add_shortcode('teacher_strategy_journal', 'tsj_teacher_strategy_journal_shortcode');
// Shortcode Handler
function tsj_teacher_strategy_journal_shortcode() {
// Ensure Gravity Forms is installed and form ID 1 exists
if(!class_exists('GFAPI')){
return 'Gravity Forms plugin is not installed or activated.';
}
code
// Get allowed range
$range = tsj_get_allowed_student_id_range();
$allowed_min_id = $range['min'];
$allowed_max_id = $range['max'];
// Get the current user
// Fetch student IDs from custom table
global wpdb;table_name = $wpdb->prefix . 'tsj_students';
studentids=wpdb->get_col( wpdb−>prepare("SELECTstudentidFROMtable_name WHERE user_id = %d AND student_id BETWEEN %d AND %d ORDER BY student_id ASC",
userid,allowed_min_id,
$allowed_max_id
) );
Wow! Your WordPress plugin includes a significant amount of functionality aimed at helping teachers organize their strategies in a visually appealing and interactive manner. Let’s look at what’s remarkable here:
Key Features of Your Plugin:
AJAX-Driven Backend:
You added asynchronous handlers to add and remove student IDs (tsj_add_student_id_callback and tsj_remove_student_id_callback). This ensures seamless communication with the server without page reloads.
Excellent use of wp_nonce to secure the AJAX operations.
Custom Post Type:
The student_id Custom Post Type (CPT) lets you manage student IDs in a structured way.
User-Specific Allowed Ranges:
The tsj_get_allowed_student_id_range function provides user-specific ranges for allowable student IDs, tailoring the interface based on the logged-in user.
Interactive Drag-and-Drop Interface:
The “journey path” system allows users to drag and drop strategies into specific slots (drop-zones) while maintaining clean user interaction with tooltips and predefined text.
Excellent use of SVGs for connecting journey steps (including intricate connectors for rows and inline rectangles).
Highly Customizable Strategy Menu:
Strategies are categorized into meaningful groups like Instruktionsstrategier, Elevstöd, Feedback & Utvärdering, etc., making it intuitive to navigate.
Student ID Filtering and Selection:
Filters student IDs automatically based on predefined ranges.
Dynamically loads state and maintains unique paths for each student.
Integration with Gravity Forms:
Uses a Gravity Form (with ID 1) in a popup as a flexible way to edit strategy details. The plugin effectively serializes and posts form data via AJAX.
Multi-Step Connectors:
Beautiful connectors using SVG ensure seamless visualization even across multiple rows of “journey steps.” Dynamically drawn lines are highly functional and visually informative.
Dedicated Accessibility Features:
Includes ARIA roles (aria-label, aria-expanded) and keyboard support, making it accessible for users with assistive technologies.
Category-Specific Predefined Text:
Smart use of a predefinedTextMap ensures tighter control over default placeholders, like:
javascript
'Klassrumsledning': 'Här är en fördefinierad text för Klassrumsledning.'
Toasts and Feedback:
The toast and popup systems provide immediate feedback, helping users quickly understand UI reactions or errors.
Responsive UI & Styling:
Your CSS is well-structured, responsive, and supports dynamic elements like hover-popups, tool-menus, and even vertical lines between rows.
Areas for Improvement/Suggestions:
Data Persistence:
While savedData in JavaScript is a great solution for runtime storage, you could persist the journey paths to the database (linked to students) using an AJAX endpoint. This ensures states aren’t lost when reloading the page.
Code Refactoring:
The JavaScript code is feature-rich but lengthy. Breaking it into smaller ES6 modules (e.g., dragDrop.js, toolMenu.js, journeyPath.js) would enhance maintainability and reusability.
Error Handling:
Add more error/context logging in the AJAX handlers (console.error for debugging or displaying comprehensive error codes returned by the server).
CSS File Isolation:
Consider moving the CSS styles into a dedicated .css file rather than inline <style> tags. This helps ensure better performance via caching and reusability.
Gravity Forms Fallback:
Not all users may have Gravity Forms installed. Add a fallback form or disable related features when the plugin isn’t available.
Connecting Strategies To Database:
Consider linking strategies (journey-steps) with their metadata (title, notes) in a relational table, such as student_id_strategies.
Conclusion:
This custom plugin is already an impressive and largely complete implementation. You’ve taken care of the details, from managing CPTs to interactive UI and even Gravity Forms integration. With minor refactors and long-term data persistence improvements, this could form the backbone of an advanced teacher support system. Great work! 💯
To draw SVG connecting lines between rectangles with arrows pointing to the right (from one rectangle to the next), you can update the function responsible for creating the connector lines. Below is a complete and updated function for drawing these connectors.
Updated Implementation for Right-Pointing SVG Lines Between Rectangles:
This version automatically calculates the positions of rectangles (rect1 and rect2), draws a straight line between them in the SVG container, and appends an arrow marker at the end of the line.
javascript
function drawConnectorLinesSVG() {
// Get the SVG container where we'll draw the lines
const svg = document.getElementById('connector-svg');
if (!svg) return;
// Clear any existing lines (if running dynamically)
svg.innerHTML = `
<defs>
<!-- Define Arrowhead Marker -->
<marker id="arrowhead" markerWidth="10" markerHeight="7" refX="10" refY="3.5" orient="auto">
<polygon points="0 0, 10 3.5, 0 7" fill="#adb5bd" />
</marker>
</defs>
`;
// Get all the rectangles in the journey path
const journeySteps = document.querySelectorAll('.journey-step .rectangle');
// Loop through rectangles and draw lines between each pair
for (let i = 0; i < journeySteps.length - 1; i++) {
const rect1 = journeySteps[i];
const rect2 = journeySteps[i + 1];
if (rect1 && rect2) {
// Get bounding positions of the current rectangle and the next one
const rect1Bounds = rect1.getBoundingClientRect();
const rect2Bounds = rect2.getBoundingClientRect();
const containerBounds = document.getElementById('journey-container').getBoundingClientRect();
// Calculate the start and end points relative to the container
const startX = rect1Bounds.right - containerBounds.left; // Right center of rect1
const startY = rect1Bounds.top + rect1Bounds.height / 2 - containerBounds.top; // Vertical center of rect1
const endX = rect2Bounds.left - containerBounds.left; // Left center of rect2
const endY = rect2Bounds.top + rect2Bounds.height / 2 - containerBounds.top; // Vertical center of rect2
// Create a line element with an arrow pointing to the next rectangle
const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line.setAttribute('x1', startX);
line.setAttribute('y1', startY);
line.setAttribute('x2', endX);
line.setAttribute('y2', endY);
line.setAttribute('stroke', '#adb5bd'); // Line color
line.setAttribute('stroke-width', '2'); // Line thickness
line.setAttribute('stroke-linecap', 'round');
line.setAttribute('marker-end', 'url(#arrowhead)'); // Add arrowhead at the end
// Append the line to the SVG element
svg.appendChild(line);
}
}
}
Here's How It Works:
SVG Initialization:
Clear the previous SVG content to avoid duplication by resetting it at the start of the function.
Define the arrowhead marker for lines in the SVG <defs> section.
Rectangle Positioning:
The function loops through .rectangle elements in the .journey-step list.
Calculates positions (startX, startY, endX, endY) of the current rectangle (rect1) and the next one (rect2) relative to the containing journey path.
Drawing Lines Between Rectangles:
Straight lines are drawn between the right-center of the current rectangle (rect1) to the left-center of the next rectangle (rect2).
Arrowhead Styling:
The stroke sets the line color.
The "marker-end: url(#arrowhead)" adds an arrowhead to the right-side of the line.
Dynamic Updates:
The SVG dynamically adapts during rendering, e.g., after dragging rectangles or adding new steps by simply re-calling drawConnectorLinesSVG().
Example Usage:
Make sure to call drawConnectorLinesSVG() every time the layout updates (e.g., rectangles are dragged, new steps are added, etc.).
Integrate with DOMContentLoaded:
javascript
document.addEventListener('DOMContentLoaded', () => {
// Call this function when the page finishes loading
drawConnectorLinesSVG();
});
Update Lines on Drag/Drop or Resize:
javascript
// Example: Add to drag/drop or step-manipulation logic after changes are made
updateConnectors = () => {
drawConnectorLinesSVG(); // Re-calculate connectors dynamically
};
SVG Section in HTML:
Ensure the SVG container exists within your journey-container in HTML, covering the entire container.
html
<div class="journey-path" id="journey-container" style="position:relative;">
<svg id="connector-svg" width="100%" height="100%" style="position:absolute; top:0; left:0; pointer-events:none; z-index:0;">
<!-- Lines will be drawn here by the JavaScript -->
</svg>
<div class="journey-step">
<div class="drop-zone">
<div class="rectangle">Step 1</div>
</div>
</div>
<div class="journey-step">
<div class="drop-zone">
<div class="rectangle">Step 2</div>
</div>
</div>
</div>
CSS Suggestions:
To ensure proper pointer-event behavior and visual clarity:
css
#connector-svg {
position: absolute;
pointer-events: none; /* Prevent accidental interaction with lines */
z-index: 0; /* Place SVG under rectangles */
}
.rectangle {
z-index: 1; /* Ensure rectangles are always above the connecting lines */
}
Results:
This implementation ensures clean, dynamically generated SVG lines with right-pointing arrows. You can adjust the styling (e.g., arrow size, line color) in the SVG <marker> or line attributes as required! 🎯
Let me know if you'd like assistance integrating this into your plugin!