#151 Add logic to add widgets to a hub
Merged 7 years ago by pingou. Opened 7 years ago by pingou.
pingou/fedora-hubs add_widget  into  develop

file modified
+162 -16
@@ -11,6 +11,7 @@ 

  from flask.ext.openid import OpenID

  

  import hubs.models

+ import hubs.widgets

  

  import datanommer.models

  
@@ -131,35 +132,70 @@ 

      return flask.render_template(

          'hubs.html', hub=hub, session=session, edit=True)

  

+ 

  def hub_edit_post(name):

      hub = get_hub(session, name)

      is_js = flask.request.form.get('js', False)

  

      error = False

+ 

      # Check the input submitted

-     widget_ids = [

-         w.strip().replace('widget-', '') for w in flask.request.form.getlist('widgets[]')

+     # Right side

+     r_widget_ids = [

+         w.strip().replace('widget-', '')

+         for w in flask.request.form.getlist('right_widgets[]')

+         if w.strip()

+     ]

+     try:

+         r_widget_ids = [int(w) for w in r_widget_ids]

+     except:

+         flask.flash('Invalid widget identifiers submitted', 'error')

+         error = True

+ 

+     r_indexes = [

+         i.strip() for i in flask.request.form.getlist('right_indexes[]')

+         if i.strip()

+     ]

+ 

+     try:

+         r_indexes = [int(i) for i in r_indexes]

+     except:

+         if not is_js:

+             flask.flash('Invalid indexes submitted', 'error')

+         error = True

+ 

+     if len(r_widget_ids) != len(r_indexes):

+         if not is_js:

+             flask.flash(

+                 'The number of indexes and the number of widgets are not of '

+                 'the same length', 'error')

+         error = True

+ 

+     # Left side

+     l_widget_ids = [

+         w.strip().replace('widget-', '')

+         for w in flask.request.form.getlist('left_widgets[]')

          if w.strip()

      ]

      try:

-         widget_ids = [int(w) for w in widget_ids]

+         l_widget_ids = [int(w) for w in l_widget_ids]

      except:

          flask.flash('Invalid widget identifiers submitted', 'error')

          error = True

  

-     indexes = [

-         i.strip() for i in flask.request.form.getlist('indexes[]')

+     l_indexes = [

+         i.strip() for i in flask.request.form.getlist('left_indexes[]')

          if i.strip()

      ]

  

      try:

-         indexes = [int(i) for i in indexes]

+         l_indexes = [int(i) for i in l_indexes]

      except:

          if not is_js:

              flask.flash('Invalid indexes submitted', 'error')

          error = True

  

-     if len(widget_ids) != len(indexes):

+     if len(l_widget_ids) != len(l_indexes):

          if not is_js:

              flask.flash(

                  'The number of indexes and the number of widgets are not of '
@@ -168,10 +204,15 @@ 

  

      # If all good, update the database

      if not error:

-         for cnt, wid in enumerate(widget_ids):

+         for cnt, wid in enumerate(r_widget_ids):

+             widget = hubs.models.Widget.get(session, wid)

+             if widget.index != r_indexes[cnt]:

+                 widget.index = r_indexes[cnt]

+                 session.add(widget)

+         for cnt, wid in enumerate(l_widget_ids):

              widget = hubs.models.Widget.get(session, wid)

-             if widget.index != indexes[cnt]:

-                 widget.index = indexes[cnt]

+             if widget.index != l_indexes[cnt]:

+                 widget.index = l_indexes[cnt]

                  session.add(widget)

          hub.last_edited = datetime.datetime.utcnow()

          session.add(hub)
@@ -193,6 +234,106 @@ 

          return flask.redirect(flask.url_for('hub', name=name))

  

  

+ @app.route('/<name>/add/', methods=['GET', 'POST'])

+ @app.route('/<name>/add', methods=['GET', 'POST'])

+ def hub_add_widgets(name):

+     if flask.request.method == 'POST':

+         return hub_add_widget_post(name)

+     else:

+         return hub_add_widget_get(name)

+ 

+ 

+ @app.route('/<name>/add/<widget_name>/', methods=['GET'])

+ @app.route('/<name>/add/<widget_name>', methods=['GET'])

+ def hub_add_widget(name, widget_name):

+     hub = get_hub(session, name)

+     side = str(flask.request.args.get('position')).lower()

+     if side not in ['right', 'left']:

+         flask.abort(400, 'Invalid position provided')

+ 

+     widget = None

+     w_name = None

+     for widgt in hubs.widgets.registry:

+         if hubs.widgets.registry[widgt].position in ['both', side] \

+                 and widgt == widget_name:

+             w_name = widgt

+             widget = hubs.widgets.registry[widgt]

+ 

+     return flask.render_template(

+         'add_widget.html',

+         hub=hub,

+         widget=widget,

+         widget_name=w_name,

+         side=side,

+         url_to=flask.url_for('hub_add_widgets', name=name),

+     )

+ 

+ 

+ def hub_add_widget_get(name):

+     hub = get_hub(session, name)

+     side = str(flask.request.args.get('position')).lower()

+     if side not in ['right', 'left']:

+         flask.abort(400, 'Invalid position provided')

+ 

+     widgets = [

+         widget

+         for widget in hubs.widgets.registry

+         if hubs.widgets.registry[widget].position in ['both', side]

+     ]

+     return flask.render_template(

+         'add_widget.html',

+         hub=hub,

+         widgets=widgets,

+         side=side,

+     )

+ 

+ 

+ def hub_add_widget_post(name):

+     print flask.request.form

+     widget_name = flask.request.form.get('widget_name')

+     position = flask.request.form.get('position', '').lower()

+     if not widget_name:

+         flask.abort(400, 'Invalid request sent')

+     if widget_name not in hubs.widgets.registry:

+         flask.abort(404, 'Unknown widget called')

+ 

+     hub = get_hub(session, name)

+ 

+     widget = widget = hubs.models.Widget(

+         plugin=widget_name, index=-1, left=position=='left')

+     error = False

+     config = {}

+     for arg in widget.module.data.widget_arguments:

+         val = flask.request.form.get(arg.name)

+         if not val:

+             flask.flash(

+                 'You must provide a value for: %s' % arg.name, 'error')

+             error = True

+             break

+         try:

+             arg.validator(session, val)

+             config[arg.name] = val

+         except Exception as err:

+             flask.flash('Invalid data provided, error: %s' % err, 'error')

+             error = True

+     if not error:

+         widget.hub = hub

+         widget.config = config

+         try:

+             session.add(widget)

+             session.flush()

+             widget.hub.last_edited = datetime.datetime.utcnow()

+             session.commit()

+         except Exception as err:

+             print err

+             flask.flash(

+                 'Could not save the configuration to the database '\

+                 'if the error persists, please warn an admin',

+                 'error')

+ 

+     return flask.render_template(

+         'hubs.html', hub=hub, session=session, edit=True)

+ 

  

  @app.route('/<hub>/<idx>/')

  @app.route('/<hub>/<idx>')
@@ -211,20 +352,25 @@ 

      return response

  

  

- @app.route('/<hub>/<idx>/edit/', methods=['GET'])

- @app.route('/<hub>/<idx>/edit', methods=['GET'])

+ @app.route('/<hub>/<idx>/edit/', methods=['GET', 'POST'])

+ @app.route('/<hub>/<idx>/edit', methods=['GET', 'POST'])

+ def widget_edit(hub, idx):

+     if flask.request.method == 'POST':

+         return widget_edit_post(hub, idx)

+     else:

+         return widget_edit_get(hub, idx)

+ 

+ 

  def widget_edit_get(hub, idx):

      widget = get_widget(session, hub, idx)

      return flask.render_template(

          'edit.html',

          hub=hub,

          widget=widget,

-         url_to=flask.url_for('widget_edit_post', hub=hub, idx=idx)

+         url_to=flask.url_for('widget_edit', hub=hub, idx=idx)

      )

  

  

- @app.route('/<hub>/<idx>/edit/', methods=['POST'])

- @app.route('/<hub>/<idx>/edit', methods=['POST'])

  def widget_edit_post(hub, idx):

      widget = get_widget(session, hub, idx)

      error = False
@@ -271,7 +417,7 @@ 

              'Could not delete this widget from this hub in the database '\

              'if the error persists, please warn an admin',

              'error')

-     return flask.redirect(flask.url_for('hub', name=hub))

+     return flask.redirect(flask.url_for('hub_edit', name=hub))

  

  

  @app.route('/source/<name>/')

@@ -0,0 +1,84 @@ 

+ 

+ <div class="modal-dialog" id="adding_form">

+   <div class="modal-content">

+     {% if widget %}

+     <form method="post" action="{{ url_to }}">

+     {% endif %}

+     <!-- Modal content-->

+       <div class="modal-header">

+         <button type="button" class="close" data-dismiss="modal">&times;</button>

+         <h4 class="modal-title">

+           Adding widget {% if widget %}"{{ widget_name }}"{% endif -%} to hub: {{ hub.name }}

+         </h4>

+       </div>

+       <div class="modal-body">

+         {% if widgets %}

+         <select id="widget" class="c-select" name="widget">

+             {% for w in widgets %}

+             <option value="{{ w }}">{{ w }}</option>

+             {% endfor %}

+         </select>

+         {% elif widget %}

+         <input name="widget_name" type="hidden" value="{{ widget_name }}">

+         <input name="position" type="hidden" value="{{ side }}">

+         {% if widget.data.widget_arguments %}

+           {% for arg in widget.data.widget_arguments %}

+             <fieldset class="form-group ">

+               <strong>{{ arg.name | capitalize }}</strong>

+               <input id="{{ arg.name }}" class="form-control" type="text"

+                 value="{{ arg.default if arg.default else '' }}"

+                 name="{{ arg.name }}" />

+             </fieldset>

+             {% if arg.help %}

+               <div>

+                 <small class="text-muted">{{ arg.help }}</small>

+               </div>

+             {% endif %}

+           {% endfor %}

+         {% else %}

+           <p>Nothing to configure</p>

+         {% endif %}

+         {% endif %}

+       </div>

+       <div class="modal-footer">

+         <button type="button" class="btn btn-default" data-dismiss="modal">

+           Close

+         </button>

+         <button type="submit" class="btn btn-default" id="submit_btn">

+           Add

+         </button>

+       </div>

+     {% if widget %}

+     </form>

+     {% endif %}

+   </div>

+ </div>

+ 

+ {% if widgets %}

+ <script type="text/javascript">

+ $("#submit_btn").unbind();

+ $("#submit_btn").click(function() {

+   console.log($('#widget').val());

+ 

+   $.ajax({

+     url: 'add/' + $('#widget').val() + '?position={{ side }}',

+     dataType: 'html',

+     success: function(html) {

+       $('#adding_form').html(html);

+     },

+     error: function() {

+       $('#adding_form').html(

+         '<div class="modal-dialog"><div class="modal-content"> \

+         <div class="modal-body"> \

+         An error occured when trying to add a new widget\

+         </div></div></div>'

+       );

+       console.log('error');

+       console.trace();

+     },

+   });

+   return false;

+ 

+ });

+ </script>

+ {% endif %}

file modified
+55 -10
@@ -91,10 +91,10 @@ 

            <div class="media-left">

            {% if hub.archived %}

              <img class="media-object square-32"

-               src="{{flask.url_for('static', filename='img/archived.png')}}"/>

+               src="{{ url_for('static', filename='img/archived.png') }}"/>

            {% else %}

              <img class="media-object square-32"

-               src="{{flask.url_for('static', filename='img/cobweb.png')}}"/>

+               src="{{ url_for('static', filename='img/cobweb.png') }}"/>

            {% endif %}

            </div>

            <div class="media-body">
@@ -114,7 +114,7 @@ 

          <div class="card">

            <div class="card-block">

              <h4>

-               <a href="#">

+               <a href="#" class="add_widget" data-position="left">

                  <span class="oi" data-glyph="plus"></span> Add a widget

                </a>

              </h4>
@@ -125,7 +125,7 @@ 

  

        <div id="left_widgets">

          {% for widget in hub.left_widgets %}

-         <div id="widget-{{ widget.idx }}" class="row"></div>

+         <div id="widget-{{ widget.idx }}" class="widget row"></div>

          {% endfor %}

        </div>

      </div>
@@ -136,7 +136,7 @@ 

          <div class="card">

            <div class="card-block">

              <h4>

-               <a href="#">

+               <a href="#" class="add_widget" data-position="right">

                  <span class="oi" data-glyph="plus"></span> Add a widget

                </a>

              </h4>
@@ -175,6 +175,12 @@ 

  function make_widget_sortable() {

    var byId = function (id) { return document.getElementById(id); }

  

+   Sortable.create(byId('left_widgets'), {

+     animation: 150,

+     draggable: '.widget',

+     handle: '.card',

+   });

+ 

    Sortable.create(byId('right_widgets'), {

      animation: 150,

      draggable: '.widget',
@@ -183,17 +189,55 @@ 

  

  };

  

+ function setup_add_btns() {

+   $(".add_widget").unbind();

+   $(".add_widget").click(function() {

+     console.log($(this));

+     var _pos = $(this).attr('data-position');

+ 

+     $.ajax({

+       url: 'add?position=' + _pos,

+       dataType: 'html',

+       success: function(html) {

+         $('#edit_modal_content').html(html);

+         $('#edit_modal').modal();

+       },

+       error: function() {

+         $('#edit_modal_content').html(

+           '<div class="modal-dialog"><div class="modal-content"> \

+           <div class="modal-body"> \

+           An error occured when trying to add a new widget\

+           </div></div></div>'

+         );

+         console.log('error');

+         console.trace();

+         $('#edit_modal').modal();

+       },

+     });

+     return false;

+   });

+ }

+ 

  $('#save_edits_btn').click(function() {

-   var _indexes = [];

-   var _widgets = [];

+   var _r_indexes = [];

+   var _r_widgets = [];

    $.each($('#right_widgets .widget'), function(i, el) {

-     _indexes.push(i);

-     _widgets.push($(el).attr('id').split('widget-')[1])

+     _r_indexes.push(i);

+     _r_widgets.push($(el).attr('id').split('widget-')[1])

+   });

+ 

+   var _l_indexes = [];

+   var _l_widgets = [];

+   $.each($('#left_widgets .widget'), function(i, el) {

+     _l_indexes.push(i);

+     _l_widgets.push($(el).attr('id').split('widget-')[1])

    });

  

    $.post(

      '{{ url_for("hub_edit", name=hub.name) }}',

-     {'indexes': _indexes, 'widgets': _widgets, 'js': true},

+     {'right_indexes': _r_indexes, 'right_widgets': _r_widgets,

+      'left_indexes': _l_indexes, 'left_widgets': _l_widgets,

+      'js': true},

      function(){ window.location = '{{ url_for("hub", name=hub.name) }}' }

    );

  });
@@ -257,6 +301,7 @@ 

  

    {% if edit -%}

    make_widget_sortable();

+   setup_add_btns();

    {%- endif %}

  }

  

file modified
+1 -1
@@ -49,7 +49,7 @@ 

              result['widget_url'] = flask.url_for(

                  'widget_render', hub=widget.hub.name, idx=widget.idx)

              result['edit_url'] = flask.url_for(

-                 'widget_edit_get', hub=widget.hub.name, idx=widget.idx)

+                 'widget_edit', hub=widget.hub.name, idx=widget.idx)

              result['widget'] = widget

              return result

  

no initial comment

rebased

7 years ago

Pull-Request has been merged by pingou

7 years ago