Skip to content

Commit

Permalink
Manage Submissions (#2248)
Browse files Browse the repository at this point in the history
* Main Table UI Changes (#1886)

* Start Manage Submissions

* Center checkbox in manage submission table (#1868)

fix checkbox issue

* Main Table UI

* Updates with selecting students and buttons

* Add Score Popup Icon

* Icon spacing and codebase style

---------

Co-authored-by: Michelle Liu <mliuu3259@gmail.com>

* Add sorting icons to new manage submissions (#1890)

* change icon to swap_vert, hide for file and actions headers

* change icon on diff sort

* Adds Score Details (#1893)

* Adds score details without styling

* address general styling for score details

* refactor code

* address pr issues

* Manage submissions rebase to master (#2047)

* Lint views/submissions (#1969)

* Begin linting views/submissions

* finish linting views/submissions

* address issues in code_viewer

* Prevent spoofing the author of an annotation (#1985)

* Prevent spoofing the author of an annotation

(cherry picked from commit d2ab510)

* Remove submitted_by from createAnnotation

* Update link to docs in PR template (#1991)

Fix link to docs

* Hide irrelevant cud fields for students (#1988)

* Show edit CUD button for students

* Hide irrelevant CUD fields from students

* Lint views/autograders, fix help-block gap from input (#1963)

* lint views/autograders, fix help block gap from input

* update form path

* Lint views/announcements and Touch-up UI (#1957)

* lint views/announcements and touch-up UI

* address nits

* Add erblint to overcommit and github actions (#1994)

* update erb-lint config, overcommit config to enable erb-lint as a pre-commit hook, run erblint --lint-all

* update github actions to run erb-lint during linting phase

* update pull request template to include erblint check

* Display Grace Day usage on submission history table, improve management of assessment penalty settings (#1990)

* Display of grace days used

* Fix calculation of effective_late_penalty and effective_version_penalty

* Show course default values when applicable

* Show warning messages when late submissions allowed but config does not make sense

* Fix tests

* Update wording

* Improve formatting

* Revert changes to effective penalties

* Simplify check

* Add toggles

* Update wording on courseFields

* Fix version threshold logic

* Correctly set version threshold to blank when using course default

* Clear / default values when checkbox clicked

* Remove bottom padding

* Improve UI when checkboxes selected

* Address AI nits

* Handle malformed scoreboard results from autograder, fix error handling for scoreboards (#1982)

* begin fixing broken redirects

* add code to check that entries are arrays, return flash error if not valid entry

* fix spacing

* address nit

* Add logging

* Click into submissions from gradebook score (#1998)

* Clickable gradebook scores

* Only scores have links

---------

Co-authored-by: kestertan <kestert@andrew.cmu.edu>

* Switch mossnet clean to use rails root instead of tilde expansion (#1997)

use Rails root join function instead of ~/ to make sure moss clean script works across systems

* Merge pull request from GHSA-h8wq-ghfq-5hfx

* fixes

* Add validation for handout, writeup, and handin_directory

* Avoid use of and

* Check that handout/writeup exists before checking path (#2001)

Move present? check to front

* Adds warning when assessment.rb file upload isn't a .rb file (#1999)

* preliminary working version

* only validates .rb files

---------

Co-authored-by: Damian Ho <damian_ho_xu_yang@yahoo.com>

* Refactor Assessment name rules, remove config file requirement (#1987)

* begin refactoring naming rules for assessments

* continue working on file acceptance

* add testing

* fix autograde

* work on backwards compatibility / revertibility

* keep working on implementing revertability

* Fix some code creating assessmentConfigFile before assessment id created

* Add documentation to naming rules

* add line about assessment name uniqueness

* update error messages

* fix tests

* add error handling code to redirect user in case assessment config file can't be loaded, run robocop

* address AI code review

* remove redundant flash

* Fix text

* Fix reload assessment config button text

* Add more error handling, revamp regex string to better reflect valid ruby module names, add better sanitization for display name -> name conversion, fix docs to reflect actually valid assessment names.

* fix test

* Address nits

* Fix issue where assessment could affect another assessment's config file if they both had names that mapped to pre-PR config file name

* Delete config/oauth_config.yml

* Delete diff.patch

* Delete assessment.patch

* remove unnecessary files

* more removals

* Suppress confirmation dialog on edit assessment page when no changes made (#2004)

* Extract logic, call functions directly

* Remove extraneous space

* Remove another extraneous space

* Display submission version in gradebook (#2005)

* First Commit: version info is on gradebook as new columns

* Second commit: only add a ver column after each assignment

* Delete database.docker.yml

* Delete schema.rb

* Deleted debug code

* change gitignore to original version

* Address nits

* Fix tooltips

* Simplify version logic

* Stop overwriting headerCssClass

* Fix tooltip for not_yet_submitted

* Handle nil aud

* Add version to gradebook CSV export

* Render tooltips onMouseEnter too

* Simplify version header

* Simplify logic

* Increase gradebook width

---------

Co-authored-by: SimonMen65 <jm7828@nyu.edu>
Co-authored-by: Simon Men <60764463+SimonMen65@users.noreply.github.com>

* Don't clear assessment penalty fields on initial load (#2006)

* Don't clear on initial load

* Remove extraneous spaces

* No line breaks when generating base64 strings (#2008)

* fix bug for long strings

* Update base64.js using new TextEncoder

* Show all courses for MOSS (#2015)

* Show all courses, restore filter

* Address AI nits

* Fix use of autocomplete attribute

* Add newline

* Simplify toggleOptions implementation

* Fix style of isArchive checkboxes

* Correct use of javascript_include_tag

* Fix failing test

* Update styling of warning

* Extract dropdown logic, use OR for filtering

* Add newline

* Add spacing between dropdowns

* Use find instead of children, check for selector existence

* Removed name from assessment yml (#1993)

* Removed name from assessment yml

* Modified test after removing name from assessment yml

* Removed unnecessary test for wrong assessment name

* Removed yml name check in assessments_controller

---------

Co-authored-by: Nicholas Clark <nicholas@califoriaclarks.com>

* Account for hooks in viewFeedback instead of feedback output (#2003)

* preliminary working version

* resolve merge conflicts

* use submission.scores instead of feedback array

* don't show non autograded scores in autograded scores tab

* rabbit ai suggestions

* more rabbit.ai nits

* make finishedAutograding not an instance variable

* Remove element overlapping scrollbar hitbox (#2009)

* Remove element overlapping scrollbar hitbox

* Move style to annotation.scss

---------

Co-authored-by: Damian Ho <damian_ho_xu_yang@yahoo.com>

* Attachment categories (#1983)

* Add category_name field and update course attachment UI

* Improve styling of list items

* Remove anchor link for unreleased badge, simplify delete button logic

* Hide assessment attachments from course landing page

* Add release_at field, remove released field

* Fix tests

* Add fixtures

* Simplify variable names

* Remove bullet points

* Group buttons together

* Make font-family consistent

* Hide category for assessment attachments

* Add cancel button, remove delete button, improve styling

* Improve migration to be backwards compatible / reversible

* Use update instead of update_attribute

* Display when attachment will be released

* Update tests

* Simplify code

* Use Time instead of DateTime

* Add download icon for students

* Vertically align icons

* Hide assessment attachments from course attachment index

* Add vertical space above release date

* Passwordless temporary login (#1984)

* Passwordless temporary login created

* Login using devise

* User is not signed in before changing password

* Removing unneeded files

* Removing changes to user.rb

* Removing unneeded files

* Resetting password does not log you out

* Added mailer

* Added/removed newlines

* Changed naming

* Added checks for nil user or params

* Error handling for passwords

* Removed email after password reset

* Added documentation

* Updated documentation

* Moved documentation to features

* Renamed to admin-features

* Added link in mkdocs.yml

* Visual cue for assessments (#2016)

* Add dates to assessment card

* Add CSS formatting for date

* Fix margin and card sizes to be more pretty

* Show all students on gradesheet (#2019)

* add course members with blank info if no submissions found

* add email for no submission users

* update bg color

* Move submission version logic to be handled by AUD (#2024)

* Move submission version logic to be handled by AUD

* update migration variable naming

* fix unit tests, version number for new auds

* fix coderabbit issues

* add version number to schema

* change schema timestamp

* Use ActiveStorage for attachments, add attachment size limit (#2023)

* 1810 Use ActiveStorage for attachments

* 1864 Add backwards compatibility to ActiveStorage Attachments

* 1872 Add size limit to attachments

* Set mime_type

* Remove require

* redirect to index on error

* Rails 6.1.7.6 Migration (#2037)

* Initial update to 6.1.7.6

* Lock fomantic-ui-sass to 2.8.8.1

* Update schema.rb

* Avoid locking setup-ruby version

* Include net-http in Gemfile to avoid errors

* Run rubocop

* Lock uri to 0.10.0

* Fix lint issue

* Fix course_number values for roster export

* Use flash for drop warning

* Properly display submission errors

* Only show invalid assessment warning to instructors

* Ensure gradebook search bar renders correctly for CAs

* Filter by lecture too when CA views section

* Only show missing submissions from section if CA filters by section

* Update tests

* Better handling for submission errors

* More specific error handling for save_entries

* Better error display for statistics page

* Return 404 for popover on non-existent submission

* load Archive in files that use its methods

* Update Ruby to 3.2.2, Misc fixes (#2040)

* Update Ruby to 3.2.2
- update Capybara config so that it works with new ruby version and so that js can be enabled again on selenium test
- update releaseSectionGrades redirect to go to viewGradesheet for CA's section
- add some more status text / more informative flash when instructor drops student
- redact tango key in getjob

* Address nits, update bundler / github integration

* add arm64-darwin-23 to platforms

* fix users nit

* Bump uri from 0.10.0 to 0.10.3 (#2039)

Bumps [uri](https://github.com/ruby/uri) from 0.10.0 to 0.10.3.
- [Release notes](https://github.com/ruby/uri/releases)
- [Commits](ruby/uri@v0.10.0...v0.10.3)

---
updated-dependencies:
- dependency-name: uri
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* Update old migrations for Ruby 3 (#2044)

Use splat on old migrations

* Remove grading deadline (#2014)

* Initial removal of grading_deadline

* Add brackets around arguments to grading_complete?

* Consistency fixes

* Migration to remove grading deadline

* Add guards to migration

* Rename grading_complete? to grades_released?

* Address issues from v2.8.0 testing, misc fixes/changes (#2038)

* Fix command for promoting a user to admin

* Extract aria/collapsible code, switch to path helpers

* Automatically open first accordion

* Fix docs for Tango info endpoint

* Create user directory on autograde_done

* Coalesce accordions, simplify js, remove admin options

* Update doorkeeper translations

* Remove extraneous quotes

* Remove redundant / useless assessment nil check

* Fix error display when calling downloadAll on invalid assessment

* Simplify failure redirect logic for downloadAll

* Deduplicate logic for autograde feedback path and handin file path

* Remove unused ass_dir variable

* Remove redundant gitignores

* Uncoalesce accordions

* Fix redirects for invalid assessment

Previously, calling downloadAll with an invalid assessment led to infinite redirects

* Update the API to allow retrieving group members (#1956)

* Add a param to the index groups api to retriee group members

* Add api show endpoint for groups

* Update docs

* Update api docs for groups#show

* Compact group members api response

* Move fetching group json to a private method

* Remove empty line

---------

Co-authored-by: Damian Ho <damian_ho_xu_yang@yahoo.com>

* Update index and show docs for Groups API (#2045)

Update index and show docs

* Main Table UI Changes (#1886)

* Start Manage Submissions

* Center checkbox in manage submission table (#1868)

fix checkbox issue

* Main Table UI

* Updates with selecting students and buttons

* Add Score Popup Icon

* Icon spacing and codebase style

---------

Co-authored-by: Michelle Liu <mliuu3259@gmail.com>

* Add sorting icons to new manage submissions (#1890)

* change icon to swap_vert, hide for file and actions headers

* change icon on diff sort

* Adds Score Details (#1893)

* Adds score details without styling

* address general styling for score details

* refactor code

* address pr issues

* bring back css

* bring back div

* add back class names

* add back icons

* addressed nits

* address nits

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: Joey Wildman <josephwildman88@gmail.com>
Co-authored-by: Nicholas Myers <32116122+NicholasMy@users.noreply.github.com>
Co-authored-by: Damian Ho <damian_ho_xu_yang@yahoo.com>
Co-authored-by: Kester <kestertan040@gmail.com>
Co-authored-by: kestertan <kestert@andrew.cmu.edu>
Co-authored-by: SimonMen65 <jm7828@nyu.edu>
Co-authored-by: Simon Men <60764463+SimonMen65@users.noreply.github.com>
Co-authored-by: Ugo <7947217+ugogon@users.noreply.github.com>
Co-authored-by: Nicholas AJ Clark <nicholas@californiaclarks.com>
Co-authored-by: Nicholas Clark <nicholas@califoriaclarks.com>
Co-authored-by: lykimchee <lchaeryn5863@gmail.com>
Co-authored-by: Joanna Ge <45646252+jlge@users.noreply.github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Umar Alkafaween <30433769+umar221b@users.noreply.github.com>
Co-authored-by: Victor Huang <victorhuangwq@gmail.com>

* [Manage Submissions] Updated tweak annotations (#1992)

* merge conflicts

* show annotation form on click

* got problems to show up

* got autofill results to show

* consolidate shared functions

* got annotations to save yay

* check if autograded

* deleted console.log statements, fixed bug where manage submissions doesn't show if submissions don't produce scores

* if error grading, show dash for submission instead of hiding

* got edit icon showing up

* updated icons for tweaks

* update tweak after submitting

* revert schema.rb

* address nits

* fixed nits

* [Manage Submissions] Score popup modal styling + fixes (#1952)

* Style fixes

* Fix formatting and styling

* Fix undefined error showing up for all problems and scores

* Strengthened checks and nil case

* Changed styling and removed external stylesheet

* Increased font size and used variables

---------

Co-authored-by: Kester <kestertan040@gmail.com>

* Manage Submissions Button Functionalities (#1903)

* html_safe RuboCop Safety

* Comment out unrelated popover changes (TODO in separate PR)

* Add regrade selected button

* Use datatables toolbar instead of Buttons extension

* Rubocop style fixes

* Rubocop indenting fix

* Make consistent with jquery

* Fixed check all functionality and download all button

* Added excuse all functionality

* Added route for excuseBatch

* Configured excuse and unexcuse popup

* Removed console log and tidied up js code

* Added confirm check for delete batch

* Changed variables and empty check

* addressed nits

* added nil table check and addressed nits and ui issues

* fixed destroy confirm

* Use batch regrade instead of regrade to prevent redirect or ajax

* Removed unecessary comments

* Fixed styling and changed to variables

* Addressed permissions

* Changed colors to variables and made highlight of table lighter

* Fixed all issues due to merge conflicts

---------

Co-authored-by: Kester <kestertan040@gmail.com>

* Merge conflicts for env template and gitignore

* Merge conflicts for style

* Fixed delete confirm button

* Fixed linting

* Fixed tests and linting

* Removed unnecessary duplicate styles

* Added checks for excuse popover

* Removed svn which was deprecated

* Fixed broken final_score and late penalty

* Style fixes and pagination

* Fixes pagination and select all

* Added hover message for unexcuse

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: lykimchee <lchaeryn5863@gmail.com>
Co-authored-by: Michelle Liu <mliuu3259@gmail.com>
Co-authored-by: Victor Huang <victorhuangwq@gmail.com>
Co-authored-by: Joey Wildman <josephwildman88@gmail.com>
Co-authored-by: Nicholas Myers <32116122+NicholasMy@users.noreply.github.com>
Co-authored-by: Damian Ho <damian_ho_xu_yang@yahoo.com>
Co-authored-by: SimonMen65 <jm7828@nyu.edu>
Co-authored-by: Simon Men <60764463+SimonMen65@users.noreply.github.com>
Co-authored-by: Ugo <7947217+ugogon@users.noreply.github.com>
Co-authored-by: Nicholas AJ Clark <nicholas@californiaclarks.com>
Co-authored-by: Nicholas Clark <nicholas@califoriaclarks.com>
Co-authored-by: Joanna Ge <45646252+jlge@users.noreply.github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Umar Alkafaween <30433769+umar221b@users.noreply.github.com>
  • Loading branch information
15 people authored Feb 2, 2025
1 parent 2dc3ce9 commit 320631b
Show file tree
Hide file tree
Showing 32 changed files with 1,947 additions and 441 deletions.
142 changes: 142 additions & 0 deletions app/assets/javascripts/annotations_helpers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
/* following paths/functions for annotations */
var sharedCommentsPath = basePath + "/shared_comments";

var createPath = basePath + ".json";
var updatePath = function (ann) {
return [basePath, "/", ann.id, ".json"].join("");
};
var deletePath = updatePath;

function getSharedCommentsForProblem(problem_id) {
return localCache['shared_comments'][problem_id]?.map(
(annotation) => {
return {label: annotation.comment ?? annotation, value: annotation}
}
)
}

var selectAnnotation = box => (e, ui) => {
const {value} = ui.item;

const score = value.value ?? 0;
box.find('#comment-score').val(score);

const $textarea = box.find("#comment-textarea");
M.textareaAutoResize($textarea);

return false;
}

function focusAnnotation( event, ui ) {
$(this).val(ui.item.label);
return false;
}

// retrieve shared comments
// also retrieves annotation id to allow easy deletion in the future
function retrieveSharedComments(cb) {
$.getJSON(sharedCommentsPath, function (data) {
localCache['shared_comments'] = {};
data.forEach(e => {
if (!e.problem_id)
return;
localCache['shared_comments'][e.problem_id] ||= [];
localCache['shared_comments'][e.problem_id].push(e);
});
cb?.();
});
}

function purgeCurrentPageCache() {
localCache[currentHeaderPos] = {
codeBox: `<div id="code-box">${$('#code-box').html()}</div>`,
pdf: false,
symbolTree: `<div id="symbol-tree-box">${$('#symbol-tree-box').html()}</div>`,
versionLinks: `<span id="version-links">${$('#version-links').html()}</span>`,
versionDropdown: `<span id="version-dropdown">${$('#version-dropdown').html()}</span>`,
url: window.location.href,
};
}

function plusFix(n) {
n = parseFloat(n)
if (isNaN(n)) n = 0;

if (n > 0) {
return "+" + n.toFixed(2);
}

return n.toFixed(2);
}

function getProblemNameWithId(problem_id) {
var problem_id = parseInt(problem_id, 10);
var problem = _.findWhere(problems, { "id": problem_id });
if (problem == undefined) return "Deleted Problem(s)";
return problem.name;
}


// create an HTML element real nice and easy like
function elt(t, a) {
var el = document.createElement(t);
if (a) {
for (var attr in a)
if (a.hasOwnProperty(attr))
el.setAttribute(attr, a[attr]);
}
for (var i = 2; i < arguments.length; ++i) {
var arg = arguments[i];
if (typeof arg === "string")
arg = document.createTextNode(arg);
el.appendChild(arg);
}
return el;
}


// this creates a JSON representation of what the actual Rails Annotation model looks like
function createAnnotation() {
var annObj = {
submitted_by: cudEmailStr,
};
if (fileNameStr != null) {
annObj.filename = fileNameStr
}

if (currentHeaderPos || currentHeaderPos === 0) {
annObj.position = currentHeaderPos
}

return annObj;
}

function getAnnotationObject(annotationId) {
for (var i = 0; i < annotations.length; i++) {
if (annotations[i].id == annotationId) {
return annotations[i];
}
}
}


var updateAnnotationBox = function (annObj) {

var problemStr = annObj.problem_id ? getProblemNameWithId(annObj.problem_id) : "General";
var valueStr = annObj.value ? annObj.value.toString() : "None";
var commentStr = annObj.comment;

if (annotationMode === "PDF") {
$('#ann-box-' + annObj.id).find('.score-box').html("<div>Problem: " + problemStr + "</div><div> Score: " + valueStr + "</div>");
$("#ann-box-" + annObj.id).find('.body').html(commentStr);
}
else {
$('#ann-box-' + annObj.id).find('.score-box').html("<span>" + problemStr + "</span><span>" + valueStr + "</span>");
}
$('#ann-box-' + annObj.id).find('.edit').show();
$('#ann-box-' + annObj.id).find('.body').show();
$('#ann-box-' + annObj.id).find('.score-box').show();
$('#ann-box-' + annObj.id).find('.minimize').show();
$('#ann-box-' + annObj.id).draggable('enable');
$('#ann-box-' + annObj.id).resizable('enable');
}
158 changes: 158 additions & 0 deletions app/assets/javascripts/annotations_popup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
const updateEditTweakButtons = () => {
tweaks.forEach(({tweak, submission}) => {
get_tweak_total(submission.id).then(data => {
tweak?.setState({ amount: data })
})
})
}
const get_tweak_total = (submission_id) => {
return new Promise((resolve, reject) => {
$.ajax({
url: `submissions/${submission_id}/tweak_total`,
method: 'GET',
dataType: 'json',
success: (data) => {
resolve(data);
},
error: (error) => {
console.error("There was an error fetching the scores:", error);
reject(error);
}
});
});
}
function newAnnotationFormCode() {
var box = $(".base-annotation-line").clone();
box.removeClass("base-annotation-line");

box.addClass("new-annotation");

// Creates a dictionary of problem and grader_id
var problemGraderId = {};

_.each(scores, function (score) {
problemGraderId[score.problem_id] = score.grader_id;
});

_.each(problems, function (problem, i) {
if (problemGraderId[problem.id] !== 0) { // Because grader == 0 is autograder
box.find("select")?.append(
$("<option />").val(problem.id).text(problem.name)
);
}
});

box.find('.annotation-form').show();
box.find('.annotation-cancel-button').click(function (e) {
e.preventDefault();
$(this).parents(".annotation-form").parent().remove();
$('#annotation-modal').modal('close');
})

box.find('#comment-textarea').autocomplete({
appendTo: box.find('#comment-textarea').parent(),
source: getSharedCommentsForProblem(box.find("select").val()) || [],
minLength: 0,
delay: 0,
select: selectAnnotation(box),
focus: focusAnnotation
}).focus(function () {
M.textareaAutoResize($(this));
$(this).autocomplete('search', $(this).val())
});

box.tooltip();

box.find("select").on('change', function () {
const problem_id = $(this).val();

// Update autocomplete to display shared comments for selected problem
box.find("#comment-textarea").autocomplete({
source: getSharedCommentsForProblem(problem_id) || []
});
});

box.find('.annotation-form').submit(function (e) {
e.preventDefault();
var comment = $(this).find(".comment").val();
var shared_comment = $(this).find("#shared-comment").is(":checked");
var score = $(this).find(".score").val();
var problem_id = $(this).find(".problem-id").val();

if (comment === undefined || comment === "") {
box.find('.error').text("Annotation comment can not be blank!").show();
return;
}

if (score === undefined || score === "") {
box.find('.error').text("Annotation score can not be blank!").show();
return;
}

if (problem_id == undefined) {
if ($('.select').children('option').length > 0)
box.find('.error').text("Problem not selected").show();
else
box.find('.error').text("There are no non-autograded problems. Create a new one at Edit Assessment > Problems").show();
return;
}
submitNewAnnotation(comment, shared_comment, true, score, problem_id, 0, $(this));
});

return box;
}

/* sets up and calls $.ajax to submit an annotation */
var submitNewAnnotation = function (comment, shared_comment, global_comment, value, problem_id, lineInd, form) {
var newAnnotation = createAnnotation();
Object.assign(newAnnotation, { line: parseInt(lineInd), comment, value, problem_id, filename: fileNameStr, shared_comment, global_comment });

if (comment === undefined || comment === "") {
$(form).find('.error').text("Could not save annotation. Please refresh the page and try again.").show();
return;
}

$(form).find('.error').hide();

$.ajax({
url: createPath,
accepts: "json",
dataType: "json",
data: {
annotation: newAnnotation
},
type: "POST",
success: function (data, type) {
updateEditTweakButtons();
$(form).parent().remove();
$('#annotation-modal').modal('close');
},
error: function (result, type) {
$(form).find('.error').text("Could not save annotation. Please refresh the page and try again.").show();
},
complete: function (result, type) { }
});

}

var updateAnnotation = function (annotationObj, box) {
$(box).find(".error").hide();
$.ajax({
url: updatePath(annotationObj),
accepts: "json",
dataType: "json",
data: {
annotation: annotationObj
},
type: "PUT",
success: function (data, type) {
$(box).remove();
displayAnnotations();
},
error: function (result, type) {
$(box).find('.error').text("Failed to save changes to the annotation. Please refresh the page and try again.").show();
},
complete: function (result, type) { }
});
}

45 changes: 45 additions & 0 deletions app/assets/javascripts/autolab_component.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/**
* Usage:
* // Create a new instance, associating it with the element specified by id 'app'
const MyComponent = new AutolabComponent('app');
// Define a template for the instance
MyComponent.template = function() {
return `
<div>
<p>Name: ${this.state.name}</p>
<p>Age: ${this.state.age}</p>
</div>
`;
};
// Set the initial state
MyComponent.setState({
name: 'John',
age: 30
});
// Later in the code, you can update the state like this:
// MyComponent.setState({ age: 31 });
*/


function AutolabComponent(elementId, initialState = {}, template = () => {}) {
this.elementId = elementId;
this.state = initialState;
this.template = template;

this.setState = function(newState = {}) {
$.extend(this.state, newState);
this.render();
};

this.template = function() {
// Default template; should be overridden by users of the library
return `<div></div>`;
};

this.render = function() {
$(`#${this.elementId}`).html(this.template());
};
}
Loading

0 comments on commit 320631b

Please sign in to comment.