Dataset Preview
Duplicate
The full dataset viewer is not available (click to read why). Only showing a preview of the rows.
The dataset generation failed
Error code:   DatasetGenerationError
Exception:    ArrowInvalid
Message:      JSON parse error: Missing a closing quotation mark in string. in row 1120
Traceback:    Traceback (most recent call last):
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/packaged_modules/json/json.py", line 145, in _generate_tables
                  dataset = json.load(f)
                File "/usr/local/lib/python3.9/json/__init__.py", line 293, in load
                  return loads(fp.read(),
                File "/usr/local/lib/python3.9/json/__init__.py", line 346, in loads
                  return _default_decoder.decode(s)
                File "/usr/local/lib/python3.9/json/decoder.py", line 340, in decode
                  raise JSONDecodeError("Extra data", s, end)
              json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 655)
              
              During handling of the above exception, another exception occurred:
              
              Traceback (most recent call last):
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1995, in _prepare_split_single
                  for _, table in generator:
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/packaged_modules/json/json.py", line 148, in _generate_tables
                  raise e
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/packaged_modules/json/json.py", line 122, in _generate_tables
                  pa_table = paj.read_json(
                File "pyarrow/_json.pyx", line 308, in pyarrow._json.read_json
                File "pyarrow/error.pxi", line 154, in pyarrow.lib.pyarrow_internal_check_status
                File "pyarrow/error.pxi", line 91, in pyarrow.lib.check_status
              pyarrow.lib.ArrowInvalid: JSON parse error: Missing a closing quotation mark in string. in row 1120
              
              The above exception was the direct cause of the following exception:
              
              Traceback (most recent call last):
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1529, in compute_config_parquet_and_info_response
                  parquet_operations = convert_to_parquet(builder)
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1154, in convert_to_parquet
                  builder.download_and_prepare(
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1027, in download_and_prepare
                  self._download_and_prepare(
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1122, in _download_and_prepare
                  self._prepare_split(split_generator, **prepare_split_kwargs)
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1882, in _prepare_split
                  for job_id, done, content in self._prepare_split_single(
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 2038, in _prepare_split_single
                  raise DatasetGenerationError("An error occurred while generating the dataset") from e
              datasets.exceptions.DatasetGenerationError: An error occurred while generating the dataset

Need help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.

text
string
meta
dict
<?php namespace OrientDB\Classes; class CustomClass implements ClassInterface { use ClassTrait; }
{ "content_hash": "24d2605c34b269de7b418d76c86a9da4", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 43, "avg_line_length": 13, "alnum_prop": 0.7692307692307693, "repo_name": "codemix/php-orientdb", "id": "6984a665179626cd8dc13ef6273d81a4632369d4", "size": "104", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/OrientDB/Classes/CustomClass.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "212700" }, { "name": "Shell", "bytes": "4020" } ] }
package org.sirix.page; import java.util.BitSet; import java.util.List; /** * Simple immutable data/value/bean class. * * @author Johannes Lichtenberger <a href="mailto:lichtenberger.johannes@gmail.com">mail</a> * */ public final class DeserializedBitmapReferencesPageTuple { /** The page references. */ private final List<PageReference> references; /** The bitmap. */ private final BitSet bitmap; /** * Constructor. * * @param references the references * @param bitmap the bitmap */ public DeserializedBitmapReferencesPageTuple(final List<PageReference> references, final BitSet bitmap) { this.references = references; this.bitmap = bitmap; } /** * Get the bitmap. * * @return the bitmap */ public BitSet getBitmap() { return bitmap; } /** * Get the references. * * @return the references */ public List<PageReference> getReferences() { return references; } }
{ "content_hash": "053425f52c5f98fc7bcb304b1ad60ce3", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 107, "avg_line_length": 19.875, "alnum_prop": 0.6729559748427673, "repo_name": "sirixdb/sirix", "id": "6ee1f7c785e05efc357810639af149a6290b9ac8", "size": "2526", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bundles/sirix-core/src/main/java/org/sirix/page/DeserializedBitmapReferencesPageTuple.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Dockerfile", "bytes": "1777" }, { "name": "HTML", "bytes": "3972" }, { "name": "Java", "bytes": "6297391" }, { "name": "Kotlin", "bytes": "406480" }, { "name": "Shell", "bytes": "263" }, { "name": "XQuery", "bytes": "22870" }, { "name": "XSLT", "bytes": "6568" } ] }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Logging.Services { /// <summary> /// Wrapper for a recyleable resource. Encapsulates a function for recycling by abusing the IDiposable pattern. /// This should be disposed after use. /// </summary> /// <typeparam name="ItemType"></typeparam> public class Recyler<ItemType> : IDisposable //This may be abuse of IDiposable Pattern { /// <summary> /// Provides a callback to dispose of the ItemType instance through. /// </summary> private readonly Action<ItemType> recycleAction; /// <summary> /// Holds the instance of ItemType that is recycleable. /// </summary> private readonly ItemType _InstanceOfType; public Recyler(Action<ItemType> action, ItemType instance) { recycleAction = action; _InstanceOfType = instance; } public void Dispose() { //We could check if ItemType implements IDiposable however we don't know if we own the instance. //If it's null we can assume that no action is to be taken. if(recycleAction != null) { recycleAction.Invoke(_InstanceOfType); } } /// <summary> /// Produces an instance object of ItemType. /// </summary> /// <returns>An instance of ItemType</returns> public ItemType Get() { return _InstanceOfType; } } }
{ "content_hash": "52ffffc407efc9137d61a21c338ae1e9", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 112, "avg_line_length": 26.153846153846153, "alnum_prop": 0.7014705882352941, "repo_name": "HelloKitty/.NetLoggingServices", "id": "a90ca24a53668415e6be3feff906e38d51090d62", "size": "1362", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "LoggingServices/Threading/Recyler.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "39579" } ] }
module Ring where -- You can optionally include a list of symbols after an import statement -- to say exactly what you're importing from the other module. This is sometimes -- useful for documentation, and to avoid name clashes between modules. import Control.Arrow ( first ) import Data.Maybe ( listToMaybe ) class Ring a where addId :: a -- additive identity addInv :: a -> a -- additive inverse mulId :: a -- multiplicative identity add :: a -> a -> a -- addition mul :: a -> a -> a -- multiplication -- Something is parsable if there is a way to read it in from a string class Parsable a where -- | If successful, 'parse' returns the thing parsed along with the -- "leftover" string, containing all of the input string except what -- was parsed parse :: String -> Maybe (a, String) -- The canonical instance for integers: instance Ring Integer where addId = 0 addInv = negate mulId = 1 add = (+) mul = (*) instance Parsable Integer where parse = listToMaybe . reads -- Look up these functions online. Think about why this combination works. -- (It should work for any member of the `Read` class. Like `Integer`.) -- | A datatype for storing and manipulating ring expressions. data RingExpr a = Lit a | AddId | AddInv (RingExpr a) | MulId | Add (RingExpr a) (RingExpr a) | Mul (RingExpr a) (RingExpr a) deriving (Show, Eq) instance Ring (RingExpr a) where addId = AddId addInv = AddInv mulId = MulId add = Add mul = Mul instance Parsable a => Parsable (RingExpr a) where parse = fmap (first Lit) . parse -- | Evaluate a 'RingExpr a' using the ring algebra of 'a'. eval :: Ring a => RingExpr a -> a eval (Lit a) = a eval AddId = addId eval (AddInv x) = addInv (eval x) eval MulId = mulId eval (Add x y) = add (eval x) (eval y) eval (Mul x y) = mul (eval x) (eval y)
{ "content_hash": "e497ac24de7502b26767803262649bfb", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 81, "avg_line_length": 30.384615384615383, "alnum_prop": 0.6349367088607595, "repo_name": "sm-haskell-users-group/cis-194", "id": "a36e3c06cfc55b0855fd69ab2c2bf52fbb6afb11", "size": "2076", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/Cis194/Hw/Ring.hs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Haskell", "bytes": "1956504" } ] }
using UnityEngine; public class BoxColliderMatcher : MonoBehaviour { public int padding = 10; public float factor; public float offset; private int _maxBGAccesses = 10; [SerializeField] private UILabel _label; private UISprite _bg; private BoxCollider _collider; public UILabel label { get { if (null == _label) { _label = gameObject.GetComponentInChildren<UILabel>(); } return _label; } } public UISprite bg { get { if (null == _bg && _maxBGAccesses > 0) { _maxBGAccesses--; _bg = gameObject.GetComponentInChildren<UISprite>(); } return _bg; } } public BoxCollider boxCollider { get { if (null == _collider) { _collider = gameObject.GetComponent<BoxCollider>(); } return _collider; } } protected virtual void specificUpdate() { } protected void goLocalCenterSpecificUpdate() { boxCollider.center = gameObject.transform.localPosition; } protected void bgLocalCenterSpecificUpdate() { if (null != bg) boxCollider.center = bg.transform.localPosition; } protected void boxColliderComputedSpecificUpdate() { boxCollider.center = new Vector3( boxCollider.size.x * factor + offset + Mathf.Sign(offset) * label.transform.localScale.x, boxCollider.center.y, boxCollider.center.z); } // Use this for initialization void Start() { } // Update is called once per frame void Update() { boxCollider.size = new Vector3( label.relativeSize.x * label.transform.localScale.x + padding, boxCollider.size.y, boxCollider.size.z); specificUpdate(); if (null != bg) { bg.transform.localScale = boxCollider.size; } } }
{ "content_hash": "c405e36232d5b50a95a9e1b7f3765f36", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 101, "avg_line_length": 21.96842105263158, "alnum_prop": 0.5390512697652132, "repo_name": "CyberCRI/Hero.Coli", "id": "ad67d38b367ac6dccff4edc3e159ac5be1fb5504", "size": "2089", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Assets/Scripts/Buttons/BoxColliderMatcher.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "2356702" }, { "name": "JavaScript", "bytes": "10205" }, { "name": "ShaderLab", "bytes": "16985" }, { "name": "Smalltalk", "bytes": "53914" } ] }
Imports System.IO Imports System.Xml.Serialization ' modGlobal cannot be disabled, Disable and Enable methods will be skipped Public Module modGlobal Public HomeStatus As String Public IsOnline As Boolean = True Public DeviceCollection As New ArrayList Sub LoadModules() If My.Settings.Global_LoadModulesAsync = True Then My.Application.Log.WriteEntry("Loading modules asynchronously") Dim LoadModuleTasks As System.Collections.Concurrent.ConcurrentBag(Of Task) = New System.Collections.Concurrent.ConcurrentBag(Of Task)() LoadModuleTasks.Add(Task.Run(Function() modDatabase.Load())) 'Dependencies: None LoadModuleTasks.Add(Task.Run(Function() modPing.Load())) 'Dependencies: None LoadModuleTasks.Add(Task.Run(Function() modSpeech.Load())) 'Dependencies: None LoadModuleTasks.Add(Task.Run(Function() modMapQuest.Load())) 'Dependencies: None LoadModuleTasks.Add(Task.Run(Function() modWolframAlpha.Load())) 'Dependencies: None LoadModuleTasks.Add(Task.Run(Function() modDreamCheeky.Load())) 'Dependencies: None LoadModuleTasks.Add(Task.Run(Function() modStreamDeck.Load())) 'Dependencies: None LoadModuleTasks.Add(Task.Run(Function() modMusic.Load())) 'Dependencies: None LoadModuleTasks.Add(Task.Run(Function() modComputer.Load())) 'Dependencies: None LoadModuleTasks.Add(Task.Run(Function() modPihole.Load())) 'Dependencies: None LoadModuleTasks.Add(Task.Run(Function() modLibrary.Load())) 'Dependencies: None LoadModuleTasks.Add(Task.Run(Function() modSync.Load())) 'Dependencies: None Task.WaitAll(LoadModuleTasks.ToArray()) LoadModuleTasks.Add(Task.Run(Function() modMail.Load())) 'Dependencies: Database LoadModuleTasks.Add(Task.Run(Function() modOpenWeatherMap.Load())) 'Dependencies: Database LoadModuleTasks.Add(Task.Run(Function() modMatrixLCD.Load())) 'Dependencies: Speech LoadModuleTasks.Add(Task.Run(Function() modGPS.Load())) 'Dependencies: Database Task.WaitAll(LoadModuleTasks.ToArray()) LoadModuleTasks.Add(Task.Run(Function() modInsteon.Load())) 'Dependencies: Database, Mail Task.WaitAll(LoadModuleTasks.ToArray()) Else My.Application.Log.WriteEntry("Loading modules") modDatabase.Load() 'Dependencies: None modPing.Load() 'Dependencies: None modMail.Load() 'Dependencies: Database modInsteon.Load() 'Dependencies: Database, Mail modSpeech.Load() 'Dependencies: None modOpenWeatherMap.Load() 'Dependencies: Database modMatrixLCD.Load() 'Dependencies: Speech modGPS.Load() 'Dependencies: Database modMapQuest.Load() 'Dependencies: None modWolframAlpha.Load() 'Dependencies: None modDreamCheeky.Load() 'Dependencies: None modStreamDeck.Load() 'Dependencies: None modMusic.Load() 'Dependencies: None modComputer.Load() 'Dependencies: None modPihole.Load() 'Dependencies: None modLibrary.Load() 'Dependencies: None modSync.Load() 'Dependencies: None End If My.Application.Log.WriteEntry("Module loading complete") End Sub Sub SaveCollection() Dim targetFile As New StreamWriter("C:\HAC\DeviceCollection.xml") Dim serializedString As String = "" serializedString = XmlSerializerHelper.Current.SerializeToXml(DeviceCollection, True) targetFile.Write(serializedString) targetFile.Close() End Sub Sub SetHomeStatus(ByVal ChangeHomeStatus As String) ' TODO: This could probably use some sort of change countdown with the scheduler modGlobal.HomeStatus = ChangeHomeStatus My.Application.Log.WriteEntry("Home status changed to " + HomeStatus) My.Settings.Global_LastHomeStatus = HomeStatus End Sub Sub UnloadModules() modMail.Unload() modSync.Unload() modOpenWeatherMap.Unload() modPing.Unload() modMatrixLCD.Unload() modStreamDeck.Unload() modMusic.Unload() modGPS.Unload() modInsteon.Unload() modComputer.Unload() modDatabase.Unload() End Sub Function CheckLogFileSize() Dim LogFile As New System.IO.FileInfo(My.Settings.Global_LogFileURI) My.Application.Log.WriteEntry("Log file is " & LogFile.Length & " bytes") If LogFile.Length > (50 * 1024 * 1024) Then My.Application.Log.WriteEntry("Log file exceeds 50 MB, consider clearing", TraceEventType.Warning) End If Return LogFile.Length End Function Function RunUpdate() As String ' HAController isn't fully functional in ClickOnce mode, this will almost never run Dim info As System.Deployment.Application.UpdateCheckInfo = Nothing If (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed) Then My.Application.Log.WriteEntry("Application is a ClickOnce application", TraceEventType.Information) Dim AD As System.Deployment.Application.ApplicationDeployment = System.Deployment.Application.ApplicationDeployment.CurrentDeployment Try info = AD.CheckForDetailedUpdate() Catch DDEExcep As System.Deployment.Application.DeploymentDownloadException My.Application.Log.WriteException(DDEExcep) Return "Cannot download update at this time" Catch IOEExcep As InvalidOperationException My.Application.Log.WriteException(IOEExcep) Return "Cannot be updated" End Try If (info.UpdateAvailable) Then modSpeech.Say("Update found", False) Try AD.Update() Catch DDEExcep As System.Deployment.Application.DeploymentDownloadException My.Application.Log.WriteException(DDEExcep) Return "Cannot install update at this time" End Try modSpeech.Say("Restarting application", False) Application.Restart() Return " " Else My.Application.Log.WriteEntry("No update available") Return "No update available" End If Else My.Application.Log.WriteEntry("Application is not a ClickOnce application", TraceEventType.Information) Dim UpdateDownloadClient As System.Net.WebClient = New System.Net.WebClient Try Dim strLatestVersion As String = UpdateDownloadClient.DownloadString(My.Settings.Global_UpdateCheckURI) My.Application.Log.WriteEntry("Application version is " & My.Application.Info.Version.Revision.ToString & ". Latest version is " & strLatestVersion) If My.Application.Info.Version.Revision.ToString = strLatestVersion Then Return "No update available" ElseIf CInt(My.Application.Info.Version.Revision.ToString) < CInt(strLatestVersion) Then My.Application.Log.WriteEntry("Newer version available") Try modSpeech.Say("Downloading update", False) My.Computer.Network.DownloadFile(My.Settings.Global_UpdateFileURI, My.Settings.Global_ScriptsFolderURI & "update.zip") My.Application.Log.WriteEntry("Decompressing update", TraceEventType.Information) System.IO.Directory.CreateDirectory(My.Settings.Global_ScriptsFolderURI & "temp") System.IO.Compression.ZipFile.ExtractToDirectory(My.Settings.Global_ScriptsFolderURI & "update.zip", My.Settings.Global_ScriptsFolderURI & "temp") System.IO.File.Delete(My.Settings.Global_ScriptsFolderURI & "update.zip") modSpeech.Say("Restarting application", False) modComputer.RunScript("updateoverwrite") Return " " Catch NetExcep As System.Net.WebException My.Application.Log.WriteException(NetExcep) Return "Unable to download updates" End Try Else Return "Application version is newer than online." End If Catch NetExcep As System.Net.WebException My.Application.Log.WriteException(NetExcep) Return "Unable to check for updates" End Try End If End Function Function SendStatusReport() As String Dim strStatusReport As String = "The current time is " & Now() & vbCrLf & vbCrLf & "Home monitoring status is set to " & modGlobal.HomeStatus & "." & vbCrLf & vbCrLf & "The inside temperature read " & My.Settings.Global_LastKnownInsideTemp & " F at " & My.Settings.Global_TimeThermostatLastUpdated.ToShortTimeString & " on " & My.Settings.Global_TimeThermostatLastUpdated.ToShortDateString & "." If My.Settings.Insteon_ThermostatSlaveAddr <> "" Then strStatusReport = strStatusReport & " (Second reading: " & My.Settings.Global_LastKnownInsideTemp2nd & " F)" End If If My.Settings.Global_TimeDoorLastOpened > DateTime.MinValue Then strStatusReport = strStatusReport & vbCrLf & vbCrLf & "The door was last opened at " & My.Settings.Global_TimeDoorLastOpened.ToShortTimeString & " on " & My.Settings.Global_TimeDoorLastOpened.ToShortDateString End If If My.Settings.Pihole_Enable = True Then strStatusReport = strStatusReport & vbCrLf & vbCrLf & modPihole.CheckPiholeStatus() End If modMail.Send("HAController Status Report", strStatusReport) Return "Sending status report" End Function End Module
{ "content_hash": "6059159dd914964075b4f153a014b40a", "timestamp": "", "source": "github", "line_count": 192, "max_line_length": 403, "avg_line_length": 52.145833333333336, "alnum_prop": 0.6547143427886536, "repo_name": "ocdtrekkie/HAController", "id": "c070298fe71b4ec69b21cbfb4a594262eff3e363", "size": "10014", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "modGlobal.vb", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "2969" }, { "name": "Visual Basic .NET", "bytes": "357596" } ] }
import { join } from 'path' import { promisify } from 'util' import globMod from 'glob' const glob = promisify(globMod) const resolveDataDir = join(__dirname, 'fixtures', '**/*') async function test() { const time = process.hrtime() await glob(resolveDataDir) const hrtime = process.hrtime(time) const nanoseconds = hrtime[0] * 1e9 + hrtime[1] const milliseconds = nanoseconds / 1e6 console.log(milliseconds) } async function run() { for (let i = 0; i < 50; i++) { await test() } } run()
{ "content_hash": "31f204265bd8ad00c090bcc25e0d932b", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 58, "avg_line_length": 21.375, "alnum_prop": 0.6647173489278753, "repo_name": "JeromeFitz/next.js", "id": "170f4fb050eb58abeff2807f78fc626ad2149e6f", "size": "513", "binary": false, "copies": "4", "ref": "refs/heads/canary", "path": "bench/readdir/glob.js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "579" }, { "name": "CSS", "bytes": "38864" }, { "name": "JavaScript", "bytes": "8065763" }, { "name": "Rust", "bytes": "165055" }, { "name": "SCSS", "bytes": "5957" }, { "name": "Sass", "bytes": "302" }, { "name": "Shell", "bytes": "4512" }, { "name": "TypeScript", "bytes": "4906530" } ] }
package org.elasticsearch.cluster.node; import com.carrotsearch.hppc.ObjectHashSet; import com.carrotsearch.hppc.cursors.ObjectCursor; import com.carrotsearch.hppc.cursors.ObjectObjectCursor; import org.elasticsearch.Version; import org.elasticsearch.cluster.AbstractDiffable; import org.elasticsearch.common.Booleans; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.collect.ImmutableOpenMap; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.regex.Regex; import org.elasticsearch.common.transport.TransportAddress; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; /** * This class holds all {@link DiscoveryNode} in the cluster and provides convenience methods to * access, modify merge / diff discovery nodes. */ public class DiscoveryNodes extends AbstractDiffable<DiscoveryNodes> implements Iterable<DiscoveryNode> { public static final DiscoveryNodes EMPTY_NODES = builder().build(); public static final DiscoveryNodes PROTO = EMPTY_NODES; private final ImmutableOpenMap<String, DiscoveryNode> nodes; private final ImmutableOpenMap<String, DiscoveryNode> dataNodes; private final ImmutableOpenMap<String, DiscoveryNode> masterNodes; private final String masterNodeId; private final String localNodeId; private final Version minNodeVersion; private final Version minNonClientNodeVersion; private DiscoveryNodes(ImmutableOpenMap<String, DiscoveryNode> nodes, ImmutableOpenMap<String, DiscoveryNode> dataNodes, ImmutableOpenMap<String, DiscoveryNode> masterNodes, String masterNodeId, String localNodeId, Version minNodeVersion, Version minNonClientNodeVersion) { this.nodes = nodes; this.dataNodes = dataNodes; this.masterNodes = masterNodes; this.masterNodeId = masterNodeId; this.localNodeId = localNodeId; this.minNodeVersion = minNodeVersion; this.minNonClientNodeVersion = minNonClientNodeVersion; } @Override public Iterator<DiscoveryNode> iterator() { return nodes.valuesIt(); } /** * Is this a valid nodes that has the minimal information set. The minimal set is defined * by the localNodeId being set. */ public boolean valid() { return localNodeId != null; } /** * Returns <tt>true</tt> if the local node is the master node. */ public boolean localNodeMaster() { if (localNodeId == null) { // we don't know yet the local node id, return false return false; } return localNodeId.equals(masterNodeId); } /** * Get the number of known nodes * * @return number of nodes */ public int size() { return nodes.size(); } /** * Get the number of known nodes * * @return number of nodes */ public int getSize() { return size(); } /** * Get a {@link Map} of the discovered nodes arranged by their ids * * @return {@link Map} of the discovered nodes arranged by their ids */ public ImmutableOpenMap<String, DiscoveryNode> nodes() { return this.nodes; } /** * Get a {@link Map} of the discovered nodes arranged by their ids * * @return {@link Map} of the discovered nodes arranged by their ids */ public ImmutableOpenMap<String, DiscoveryNode> getNodes() { return nodes(); } /** * Get a {@link Map} of the discovered data nodes arranged by their ids * * @return {@link Map} of the discovered data nodes arranged by their ids */ public ImmutableOpenMap<String, DiscoveryNode> dataNodes() { return this.dataNodes; } /** * Get a {@link Map} of the discovered data nodes arranged by their ids * * @return {@link Map} of the discovered data nodes arranged by their ids */ public ImmutableOpenMap<String, DiscoveryNode> getDataNodes() { return dataNodes(); } /** * Get a {@link Map} of the discovered master nodes arranged by their ids * * @return {@link Map} of the discovered master nodes arranged by their ids */ public ImmutableOpenMap<String, DiscoveryNode> masterNodes() { return this.masterNodes; } /** * Get a {@link Map} of the discovered master nodes arranged by their ids * * @return {@link Map} of the discovered master nodes arranged by their ids */ public ImmutableOpenMap<String, DiscoveryNode> getMasterNodes() { return masterNodes(); } /** * Get a {@link Map} of the discovered master and data nodes arranged by their ids * * @return {@link Map} of the discovered master and data nodes arranged by their ids */ public ImmutableOpenMap<String, DiscoveryNode> masterAndDataNodes() { ImmutableOpenMap.Builder<String, DiscoveryNode> nodes = ImmutableOpenMap.builder(dataNodes); nodes.putAll(masterNodes); return nodes.build(); } /** * Get a node by its id * * @param nodeId id of the wanted node * @return wanted node if it exists. Otherwise <code>null</code> */ public DiscoveryNode get(String nodeId) { return nodes.get(nodeId); } /** * Determine if a given node exists * * @param nodeId id of the node which existence should be verified * @return <code>true</code> if the node exists. Otherwise <code>false</code> */ public boolean nodeExists(String nodeId) { return nodes.containsKey(nodeId); } /** * Get the id of the master node * * @return id of the master */ public String masterNodeId() { return this.masterNodeId; } /** * Get the id of the master node * * @return id of the master */ public String getMasterNodeId() { return masterNodeId(); } /** * Get the id of the local node * * @return id of the local node */ public String localNodeId() { return this.localNodeId; } /** * Get the id of the local node * * @return id of the local node */ public String getLocalNodeId() { return localNodeId(); } /** * Get the local node * * @return local node */ public DiscoveryNode localNode() { return nodes.get(localNodeId); } /** * Get the local node * * @return local node */ public DiscoveryNode getLocalNode() { return localNode(); } /** * Get the master node * * @return master node */ public DiscoveryNode masterNode() { return nodes.get(masterNodeId); } /** * Get the master node * * @return master node */ public DiscoveryNode getMasterNode() { return masterNode(); } /** * Get a node by its address * * @param address {@link TransportAddress} of the wanted node * @return node identified by the given address or <code>null</code> if no such node exists */ public DiscoveryNode findByAddress(TransportAddress address) { for (ObjectCursor<DiscoveryNode> cursor : nodes.values()) { DiscoveryNode node = cursor.value; if (node.address().equals(address)) { return node; } } return null; } public boolean isAllNodes(String... nodesIds) { return nodesIds == null || nodesIds.length == 0 || (nodesIds.length == 1 && nodesIds[0].equals("_all")); } /** * Returns the version of the node with the oldest version in the cluster * * @return the oldest version in the cluster */ public Version smallestVersion() { return minNodeVersion; } /** * Returns the version of the node with the oldest version in the cluster that is not a client node * * @return the oldest version in the cluster */ public Version smallestNonClientNodeVersion() { return minNonClientNodeVersion; } /** * Resolve a node with a given id * * @param node id of the node to discover * @return discovered node matching the given id * @throws IllegalArgumentException if more than one node matches the request or no nodes have been resolved */ public DiscoveryNode resolveNode(String node) { String[] resolvedNodeIds = resolveNodesIds(node); if (resolvedNodeIds.length > 1) { throw new IllegalArgumentException("resolved [" + node + "] into [" + resolvedNodeIds.length + "] nodes, where expected to be resolved to a single node"); } if (resolvedNodeIds.length == 0) { throw new IllegalArgumentException("failed to resolve [" + node + "], no matching nodes"); } return nodes.get(resolvedNodeIds[0]); } public String[] resolveNodesIds(String... nodesIds) { if (isAllNodes(nodesIds)) { int index = 0; nodesIds = new String[nodes.size()]; for (DiscoveryNode node : this) { nodesIds[index++] = node.id(); } return nodesIds; } else { ObjectHashSet<String> resolvedNodesIds = new ObjectHashSet<>(nodesIds.length); for (String nodeId : nodesIds) { if (nodeId.equals("_local")) { String localNodeId = localNodeId(); if (localNodeId != null) { resolvedNodesIds.add(localNodeId); } } else if (nodeId.equals("_master")) { String masterNodeId = masterNodeId(); if (masterNodeId != null) { resolvedNodesIds.add(masterNodeId); } } else if (nodeExists(nodeId)) { resolvedNodesIds.add(nodeId); } else { // not a node id, try and search by name for (DiscoveryNode node : this) { if (Regex.simpleMatch(nodeId, node.name())) { resolvedNodesIds.add(node.id()); } } for (DiscoveryNode node : this) { if (Regex.simpleMatch(nodeId, node.getHostAddress())) { resolvedNodesIds.add(node.id()); } else if (Regex.simpleMatch(nodeId, node.getHostName())) { resolvedNodesIds.add(node.id()); } } int index = nodeId.indexOf(':'); if (index != -1) { String matchAttrName = nodeId.substring(0, index); String matchAttrValue = nodeId.substring(index + 1); if ("data".equals(matchAttrName)) { if (Booleans.parseBoolean(matchAttrValue, true)) { resolvedNodesIds.addAll(dataNodes.keys()); } else { resolvedNodesIds.removeAll(dataNodes.keys()); } } else if ("master".equals(matchAttrName)) { if (Booleans.parseBoolean(matchAttrValue, true)) { resolvedNodesIds.addAll(masterNodes.keys()); } else { resolvedNodesIds.removeAll(masterNodes.keys()); } } else { for (DiscoveryNode node : this) { for (ObjectObjectCursor<String, String> entry : node.attributes()) { String attrName = entry.key; String attrValue = entry.value; if (Regex.simpleMatch(matchAttrName, attrName) && Regex.simpleMatch(matchAttrValue, attrValue)) { resolvedNodesIds.add(node.id()); } } } } } } } return resolvedNodesIds.toArray(String.class); } } public DiscoveryNodes removeDeadMembers(Set<String> newNodes, String masterNodeId) { Builder builder = new Builder().masterNodeId(masterNodeId).localNodeId(localNodeId); for (DiscoveryNode node : this) { if (newNodes.contains(node.id())) { builder.put(node); } } return builder.build(); } public DiscoveryNodes newNode(DiscoveryNode node) { return new Builder(this).put(node).build(); } /** * Returns the changes comparing this nodes to the provided nodes. */ public Delta delta(DiscoveryNodes other) { List<DiscoveryNode> removed = new ArrayList<>(); List<DiscoveryNode> added = new ArrayList<>(); for (DiscoveryNode node : other) { if (!this.nodeExists(node.id())) { removed.add(node); } } for (DiscoveryNode node : this) { if (!other.nodeExists(node.id())) { added.add(node); } } DiscoveryNode previousMasterNode = null; DiscoveryNode newMasterNode = null; if (masterNodeId != null) { if (other.masterNodeId == null || !other.masterNodeId.equals(masterNodeId)) { previousMasterNode = other.masterNode(); newMasterNode = masterNode(); } } return new Delta(previousMasterNode, newMasterNode, localNodeId, Collections.unmodifiableList(removed), Collections.unmodifiableList(added)); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); for (DiscoveryNode node : this) { sb.append(node).append(','); } sb.append("}"); return sb.toString(); } public String prettyPrint() { StringBuilder sb = new StringBuilder(); sb.append("nodes: \n"); for (DiscoveryNode node : this) { sb.append(" ").append(node); if (node == localNode()) { sb.append(", local"); } if (node == masterNode()) { sb.append(", master"); } sb.append("\n"); } return sb.toString(); } public Delta emptyDelta() { return new Delta(null, null, localNodeId, DiscoveryNode.EMPTY_LIST, DiscoveryNode.EMPTY_LIST); } public static class Delta { private final String localNodeId; private final DiscoveryNode previousMasterNode; private final DiscoveryNode newMasterNode; private final List<DiscoveryNode> removed; private final List<DiscoveryNode> added; public Delta(String localNodeId, List<DiscoveryNode> removed, List<DiscoveryNode> added) { this(null, null, localNodeId, removed, added); } public Delta(@Nullable DiscoveryNode previousMasterNode, @Nullable DiscoveryNode newMasterNode, String localNodeId, List<DiscoveryNode> removed, List<DiscoveryNode> added) { this.previousMasterNode = previousMasterNode; this.newMasterNode = newMasterNode; this.localNodeId = localNodeId; this.removed = removed; this.added = added; } public boolean hasChanges() { return masterNodeChanged() || !removed.isEmpty() || !added.isEmpty(); } public boolean masterNodeChanged() { return newMasterNode != null; } public DiscoveryNode previousMasterNode() { return previousMasterNode; } public DiscoveryNode newMasterNode() { return newMasterNode; } public boolean removed() { return !removed.isEmpty(); } public List<DiscoveryNode> removedNodes() { return removed; } public boolean added() { return !added.isEmpty(); } public List<DiscoveryNode> addedNodes() { return added; } public String shortSummary() { StringBuilder sb = new StringBuilder(); if (!removed() && masterNodeChanged()) { if (newMasterNode.id().equals(localNodeId)) { // we are the master, no nodes we removed, we are actually the first master sb.append("new_master ").append(newMasterNode()); } else { // we are not the master, so we just got this event. No nodes were removed, so its not a *new* master sb.append("detected_master ").append(newMasterNode()); } } else { if (masterNodeChanged()) { sb.append("master {new ").append(newMasterNode()); if (previousMasterNode() != null) { sb.append(", previous ").append(previousMasterNode()); } sb.append("}"); } if (removed()) { if (masterNodeChanged()) { sb.append(", "); } sb.append("removed {"); for (DiscoveryNode node : removedNodes()) { sb.append(node).append(','); } sb.append("}"); } } if (added()) { // don't print if there is one added, and it is us if (!(addedNodes().size() == 1 && addedNodes().get(0).id().equals(localNodeId))) { if (removed() || masterNodeChanged()) { sb.append(", "); } sb.append("added {"); for (DiscoveryNode node : addedNodes()) { if (!node.id().equals(localNodeId)) { // don't print ourself sb.append(node).append(','); } } sb.append("}"); } } return sb.toString(); } } @Override public void writeTo(StreamOutput out) throws IOException { if (masterNodeId == null) { out.writeBoolean(false); } else { out.writeBoolean(true); out.writeString(masterNodeId); } out.writeVInt(nodes.size()); for (DiscoveryNode node : this) { node.writeTo(out); } } public DiscoveryNodes readFrom(StreamInput in, DiscoveryNode localNode) throws IOException { Builder builder = new Builder(); if (in.readBoolean()) { builder.masterNodeId(in.readString()); } if (localNode != null) { builder.localNodeId(localNode.id()); } int size = in.readVInt(); for (int i = 0; i < size; i++) { DiscoveryNode node = DiscoveryNode.readNode(in); if (localNode != null && node.id().equals(localNode.id())) { // reuse the same instance of our address and local node id for faster equality node = localNode; } builder.put(node); } return builder.build(); } @Override public DiscoveryNodes readFrom(StreamInput in) throws IOException { return readFrom(in, localNode()); } public static Builder builder() { return new Builder(); } public static Builder builder(DiscoveryNodes nodes) { return new Builder(nodes); } public static class Builder { private final ImmutableOpenMap.Builder<String, DiscoveryNode> nodes; private String masterNodeId; private String localNodeId; public Builder() { nodes = ImmutableOpenMap.builder(); } public Builder(DiscoveryNodes nodes) { this.masterNodeId = nodes.masterNodeId(); this.localNodeId = nodes.localNodeId(); this.nodes = ImmutableOpenMap.builder(nodes.nodes()); } public Builder put(DiscoveryNode node) { nodes.put(node.id(), node); return this; } public Builder remove(String nodeId) { nodes.remove(nodeId); return this; } public Builder masterNodeId(String masterNodeId) { this.masterNodeId = masterNodeId; return this; } public Builder localNodeId(String localNodeId) { this.localNodeId = localNodeId; return this; } public DiscoveryNodes build() { ImmutableOpenMap.Builder<String, DiscoveryNode> dataNodesBuilder = ImmutableOpenMap.builder(); ImmutableOpenMap.Builder<String, DiscoveryNode> masterNodesBuilder = ImmutableOpenMap.builder(); Version minNodeVersion = Version.CURRENT; Version minNonClientNodeVersion = Version.CURRENT; for (ObjectObjectCursor<String, DiscoveryNode> nodeEntry : nodes) { if (nodeEntry.value.dataNode()) { dataNodesBuilder.put(nodeEntry.key, nodeEntry.value); minNonClientNodeVersion = Version.smallest(minNonClientNodeVersion, nodeEntry.value.version()); } if (nodeEntry.value.masterNode()) { masterNodesBuilder.put(nodeEntry.key, nodeEntry.value); minNonClientNodeVersion = Version.smallest(minNonClientNodeVersion, nodeEntry.value.version()); } minNodeVersion = Version.smallest(minNodeVersion, nodeEntry.value.version()); } return new DiscoveryNodes(nodes.build(), dataNodesBuilder.build(), masterNodesBuilder.build(), masterNodeId, localNodeId, minNodeVersion, minNonClientNodeVersion); } public static DiscoveryNodes readFrom(StreamInput in, @Nullable DiscoveryNode localNode) throws IOException { return PROTO.readFrom(in, localNode); } } }
{ "content_hash": "d51b7074fadf8fd0716df27273f0baf8", "timestamp": "", "source": "github", "line_count": 661, "max_line_length": 277, "avg_line_length": 34.296520423600604, "alnum_prop": 0.5633877370974857, "repo_name": "davidvgalbraith/elasticsearch", "id": "d07d3c334ac4521e4fe1c4516e67ab481bd997b8", "size": "23458", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/src/main/java/org/elasticsearch/cluster/node/DiscoveryNodes.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "8178" }, { "name": "Batchfile", "bytes": "11635" }, { "name": "Emacs Lisp", "bytes": "3243" }, { "name": "FreeMarker", "bytes": "45" }, { "name": "Groovy", "bytes": "206013" }, { "name": "HTML", "bytes": "3409" }, { "name": "Java", "bytes": "31637089" }, { "name": "Perl", "bytes": "6923" }, { "name": "Python", "bytes": "95334" }, { "name": "Ruby", "bytes": "17776" }, { "name": "Shell", "bytes": "90967" } ] }
<!DOCTYPE html> <html lang="en" prefix="og: http://ogp.me/ns# fb: https://www.facebook.com/2008/fbml"> <head> <title>Donne Martin</title> <!-- Using the latest rendering mode for IE --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <meta name="author" content="Donne Martin" /> <!-- Open Graph tags --> <meta property="og:site_name" content="Donne Martin" /> <meta property="og:type" content="website"/> <meta property="og:title" content="Donne Martin"/> <meta property="og:url" content="."/> <meta property="og:description" content="Donne Martin"/> <!-- Bootstrap --> <link rel="stylesheet" href="./theme/css/bootstrap.min.css" type="text/css"/> <link href="./theme/css/pygments/monokai.css" rel="stylesheet"> <!-- Custom CSS --> <link href="./theme/css/agency.css" rel="stylesheet"> <link href="./theme/css/custom.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="./theme/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"> <link href='https://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond../theme/js/1.4.2/respond.min.js"></script> <![endif]--> </head><body id="page-top" class="index"> <!-- Banner --> <!-- End Banner --> <div class="container"> <div class="row"> <div class="col-lg-12"> <nav class="navbar navbar-default navbar-fixed-top" style="background-color: #000"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header page-scroll"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand page-scroll" href=".">Donne Martin</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li class="hidden"> <a href="#page-top"></a> </li> <li> <a class="page-scroll" href="./#likes">Likes</a> </li> <li> <a class="page-scroll" href="./#portfolio">GitHub</a> </li> <li> <a class="page-scroll" href="./#about">About</a> </li> <li> <a class="page-scroll" href="./#contact">Contact</a> </li> <li> <a class="page-scroll" href="./archives">Blog</a> </li> <li> <a class="page-scroll" href="http://donnemartin.com/viz/">Viz</a> </li> </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container-fluid --> </nav> <section id="content" class="section-top-padding"> <article class="article-top-padding"> <h1> <a href="./my-reading-list.html" rel="bookmark" title="Permalink to My Reading List"> My Reading List </a> </h1> <i><time datetime="2014-11-29T00:00:00-05:00"> Sat 29 November 2014</time></i> <div class="entry-content"> <div class="panel"> <br/> </div> <div class="container"> <br/> <img class="img-responsive" src="https://raw.githubusercontent.com/donnemartin/donnemartin.github.io/master/images/posts/steambw.jpg"> </div> <hr class="featurette-divider"> <p>I've started populating my <a href="http://donnemartin.net/reading-list/" target="_blank">Reading List</a>!  Updates will trickle in over the coming weeks.</p> <p>I'm an avid reader, consuming 1-2 books each month in addition to tech articles, tutorials, and university course materials.</p> <p>Reading helps me:</p> <ul> <li>Dream big and generate ideas for life and for work</li> <li>Increase my breadth and depth of knowledge, fueling my need to constantly learn</li> <li>Challenge and stretch my self discipline</li> <li>Expand my creativity by thinking outside of my comfort zone with new ideas, theories, and beliefs</li> <li>View the world through the brightest minds and teachers of current and previous generations</li> </ul> </div> <hr class="featurette-divider"> <!-- /.entry-content --> </article> </section> </div> </div> </div> <footer> <div class="container"> <div class="row"> <div class="col-md-12 text-left"> <span class="copyright">Copyright &copy; Donne Martin 2014-Present</span> </div> </div> </div> </footer> <script src="./theme/js/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="./theme/js/bootstrap.min.js"></script> <!-- Enable responsive features in IE8 with Respond.js (https://github.com/scottjehl/Respond) --> <script src="./theme/js/respond.min.js"></script> <!-- Plugin JavaScript --> <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script> <script src="./theme/js/classie.js"></script> <script src="./theme/js/cbpAnimatedHeader.js"></script> <!-- Custom Theme JavaScript --> <script src="./theme/js/agency.js"></script> <!-- Google Analytics Universal --> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-54747412-1', 'auto'); ga('send', 'pageview'); </script> <!-- End Google Analytics Universal Code --> </body> </html>
{ "content_hash": "cfef44ac88a2a0d9139e83a99aa651cd", "timestamp": "", "source": "github", "line_count": 180, "max_line_length": 178, "avg_line_length": 41.36666666666667, "alnum_prop": 0.5632554391619662, "repo_name": "donnemartin/outdated-donnemartin.github.io", "id": "1e4ab122688797a1b370c64c8f5935c353315158", "size": "7453", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "my-reading-list.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "506044" }, { "name": "HTML", "bytes": "490082" }, { "name": "JavaScript", "bytes": "137930" }, { "name": "Makefile", "bytes": "4328" }, { "name": "PHP", "bytes": "1016" }, { "name": "Python", "bytes": "2393" }, { "name": "Shell", "bytes": "2202" } ] }
<component name="libraryTable"> <library name="mediarouter-v7-23.0.0"> <ANNOTATIONS> <root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/mediarouter-v7/23.0.0/annotations.zip!/" /> </ANNOTATIONS> <CLASSES> <root url="file://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/mediarouter-v7/23.0.0/res" /> <root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/mediarouter-v7/23.0.0/jars/libs/internal_impl-23.0.0.jar!/" /> <root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/mediarouter-v7/23.0.0/jars/classes.jar!/" /> </CLASSES> <JAVADOC /> <SOURCES> <root url="jar://$USER_HOME$/Android/Sdk/extras/android/m2repository/com/android/support/mediarouter-v7/23.0.0/mediarouter-v7-23.0.0-sources.jar!/" /> </SOURCES> </library> </component>
{ "content_hash": "318c19e7672bf2b6aa833c229cd46f9a", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 156, "avg_line_length": 57.8125, "alnum_prop": 0.6951351351351351, "repo_name": "schemon/congestion-tax", "id": "fc84797f0dd4b6f56ac014b573a94344aa609527", "size": "925", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": ".idea/libraries/mediarouter_v7_23_0_0.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "61471" } ] }
'use strict'; var should = require('should'), request = require('supertest'), path = require('path'), mongoose = require('mongoose'), User = mongoose.model('User'), Spork = mongoose.model('Spork'), express = require(path.resolve('./config/lib/express')); /** * Globals */ var app, agent, credentials, user, spork; /** * Spork routes tests */ describe('Spork CRUD tests', function () { before(function (done) { // Get application app = express.init(mongoose); agent = request.agent(app); done(); }); beforeEach(function (done) { // Create user credentials credentials = { username: 'username', password: 'M3@n.jsI$Aw3$0m3' }; // Create a new user user = new User({ firstName: 'Full', lastName: 'Name', displayName: 'Full Name', email: 'test@test.com', username: credentials.username, password: credentials.password, provider: 'local' }); // Save a user to the test db and create new spork user.save(function () { spork = { title: 'Spork Title', content: 'Spork Content' }; done(); }); }); it('should be able to save an spork if logged in', function (done) { agent.post('/api/auth/signin') .send(credentials) .expect(200) .end(function (signinErr, signinRes) { // Handle signin error if (signinErr) { return done(signinErr); } // Get the userId var userId = user.id; // Save a new spork agent.post('/api/sporks') .send(spork) .expect(200) .end(function (sporkSaveErr, sporkSaveRes) { // Handle spork save error if (sporkSaveErr) { return done(sporkSaveErr); } // Get a list of sporks agent.get('/api/sporks') .end(function (sporksGetErr, sporksGetRes) { // Handle spork save error if (sporksGetErr) { return done(sporksGetErr); } // Get sporks list var sporks = sporksGetRes.body; // Set assertions (sporks[0].user._id).should.equal(userId); (sporks[0].title).should.match('Spork Title'); // Call the assertion callback done(); }); }); }); }); it('should not be able to save an spork if not logged in', function (done) { agent.post('/api/sporks') .send(spork) .expect(403) .end(function (sporkSaveErr, sporkSaveRes) { // Call the assertion callback done(sporkSaveErr); }); }); it('should not be able to save an spork if no title is provided', function (done) { // Invalidate title field spork.title = ''; agent.post('/api/auth/signin') .send(credentials) .expect(200) .end(function (signinErr, signinRes) { // Handle signin error if (signinErr) { return done(signinErr); } // Get the userId var userId = user.id; // Save a new spork agent.post('/api/sporks') .send(spork) .expect(400) .end(function (sporkSaveErr, sporkSaveRes) { // Set message assertion (sporkSaveRes.body.message).should.match('Title cannot be blank'); // Handle spork save error done(sporkSaveErr); }); }); }); it('should be able to update an spork if signed in', function (done) { agent.post('/api/auth/signin') .send(credentials) .expect(200) .end(function (signinErr, signinRes) { // Handle signin error if (signinErr) { return done(signinErr); } // Get the userId var userId = user.id; // Save a new spork agent.post('/api/sporks') .send(spork) .expect(200) .end(function (sporkSaveErr, sporkSaveRes) { // Handle spork save error if (sporkSaveErr) { return done(sporkSaveErr); } // Update spork title spork.title = 'WHY YOU GOTTA BE SO MEAN?'; // Update an existing spork agent.put('/api/sporks/' + sporkSaveRes.body._id) .send(spork) .expect(200) .end(function (sporkUpdateErr, sporkUpdateRes) { // Handle spork update error if (sporkUpdateErr) { return done(sporkUpdateErr); } // Set assertions (sporkUpdateRes.body._id).should.equal(sporkSaveRes.body._id); (sporkUpdateRes.body.title).should.match('WHY YOU GOTTA BE SO MEAN?'); // Call the assertion callback done(); }); }); }); }); it('should be able to get a list of sporks if not signed in', function (done) { // Create new spork model instance var sporkObj = new Spork(spork); // Save the spork sporkObj.save(function () { // Request sporks request(app).get('/api/sporks') .end(function (req, res) { // Set assertion res.body.should.be.instanceof(Array).and.have.lengthOf(1); // Call the assertion callback done(); }); }); }); it('should be able to get a single spork if not signed in', function (done) { // Create new spork model instance var sporkObj = new Spork(spork); // Save the spork sporkObj.save(function () { request(app).get('/api/sporks/' + sporkObj._id) .end(function (req, res) { // Set assertion res.body.should.be.instanceof(Object).and.have.property('title', spork.title); // Call the assertion callback done(); }); }); }); it('should return proper error for single spork with an invalid Id, if not signed in', function (done) { // test is not a valid mongoose Id request(app).get('/api/sporks/test') .end(function (req, res) { // Set assertion res.body.should.be.instanceof(Object).and.have.property('message', 'Spork is invalid'); // Call the assertion callback done(); }); }); it('should return proper error for single spork which doesnt exist, if not signed in', function (done) { // This is a valid mongoose Id but a non-existent spork request(app).get('/api/sporks/559e9cd815f80b4c256a8f41') .end(function (req, res) { // Set assertion res.body.should.be.instanceof(Object).and.have.property('message', 'No spork with that identifier has been found'); // Call the assertion callback done(); }); }); it('should be able to delete an spork if signed in', function (done) { agent.post('/api/auth/signin') .send(credentials) .expect(200) .end(function (signinErr, signinRes) { // Handle signin error if (signinErr) { return done(signinErr); } // Get the userId var userId = user.id; // Save a new spork agent.post('/api/sporks') .send(spork) .expect(200) .end(function (sporkSaveErr, sporkSaveRes) { // Handle spork save error if (sporkSaveErr) { return done(sporkSaveErr); } // Delete an existing spork agent.delete('/api/sporks/' + sporkSaveRes.body._id) .send(spork) .expect(200) .end(function (sporkDeleteErr, sporkDeleteRes) { // Handle spork error error if (sporkDeleteErr) { return done(sporkDeleteErr); } // Set assertions (sporkDeleteRes.body._id).should.equal(sporkSaveRes.body._id); // Call the assertion callback done(); }); }); }); }); it('should not be able to delete an spork if not signed in', function (done) { // Set spork user spork.user = user; // Create new spork model instance var sporkObj = new Spork(spork); // Save the spork sporkObj.save(function () { // Try deleting spork request(app).delete('/api/sporks/' + sporkObj._id) .expect(403) .end(function (sporkDeleteErr, sporkDeleteRes) { // Set message assertion (sporkDeleteRes.body.message).should.match('User is not authorized'); // Handle spork error error done(sporkDeleteErr); }); }); }); afterEach(function (done) { User.remove().exec(function () { Spork.remove().exec(done); }); }); });
{ "content_hash": "9e4bffcc492f99a8038e21d7d96b59db", "timestamp": "", "source": "github", "line_count": 321, "max_line_length": 123, "avg_line_length": 27.557632398753896, "alnum_prop": 0.5384354510513226, "repo_name": "helaili/automatic-octo-spork", "id": "fbe383d16d4d012e7427cdf322fd46fb008a1b4c", "size": "8846", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/sporks/tests/server/spork.server.routes.tests.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1220" }, { "name": "HTML", "bytes": "44775" }, { "name": "JavaScript", "bytes": "325378" }, { "name": "Shell", "bytes": "685" } ] }
/** * @constructor * @extends {WebInspector.ElementsSidebarPane} */ WebInspector.StylesSidebarPane = function() { WebInspector.ElementsSidebarPane.call(this, WebInspector.UIString("Styles")); this.setMinimumSize(96, 26); WebInspector.moduleSetting("colorFormat").addChangeListener(this.update.bind(this)); WebInspector.moduleSetting("textEditorIndent").addChangeListener(this.update.bind(this)); this._sectionsContainer = this.element.createChild("div"); this._stylesPopoverHelper = new WebInspector.StylesPopoverHelper(); this._linkifier = new WebInspector.Linkifier(new WebInspector.Linkifier.DefaultCSSFormatter()); this.element.classList.add("styles-pane"); this.element.addEventListener("mousemove", this._mouseMovedOverElement.bind(this), false); this._keyDownBound = this._keyDown.bind(this); this._keyUpBound = this._keyUp.bind(this); WebInspector.targetManager.addModelListener(WebInspector.CSSModel, WebInspector.CSSModel.Events.LayoutEditorChange, this._onLayoutEditorChange, this); } /** * @param {!WebInspector.CSSProperty} property * @return {!Element} */ WebInspector.StylesSidebarPane.createExclamationMark = function(property) { var exclamationElement = createElement("label", "dt-icon-label"); exclamationElement.className = "exclamation-mark"; if (!WebInspector.StylesSidebarPane.ignoreErrorsForProperty(property)) exclamationElement.type = "warning-icon"; exclamationElement.title = WebInspector.CSSMetadata.cssPropertiesMetainfo.keySet()[property.name.toLowerCase()] ? WebInspector.UIString("Invalid property value") : WebInspector.UIString("Unknown property name"); return exclamationElement; } /** * @param {!WebInspector.CSSProperty} property * @return {boolean} */ WebInspector.StylesSidebarPane.ignoreErrorsForProperty = function(property) { /** * @param {string} string */ function hasUnknownVendorPrefix(string) { return !string.startsWith("-webkit-") && /^[-_][\w\d]+-\w/.test(string); } var name = property.name.toLowerCase(); // IE hack. if (name.charAt(0) === "_") return true; // IE has a different format for this. if (name === "filter") return true; // Common IE-specific property prefix. if (name.startsWith("scrollbar-")) return true; if (hasUnknownVendorPrefix(name)) return true; var value = property.value.toLowerCase(); // IE hack. if (value.endsWith("\9")) return true; if (hasUnknownVendorPrefix(value)) return true; return false; } WebInspector.StylesSidebarPane.prototype = { /** * @param {!WebInspector.Event} event */ _onLayoutEditorChange: function(event) { var cssModel = /** @type {!WebInspector.CSSModel} */(event.target); var styleSheetId = event.data["id"]; var sourceRange = /** @type {!CSSAgent.SourceRange} */(event.data["range"]); var range = WebInspector.TextRange.fromObject(sourceRange); this._decorator = new WebInspector.PropertyChangeHighlighter(this, cssModel, styleSheetId, range); this.update(); }, /** * @param {!WebInspector.CSSProperty} cssProperty */ revealProperty: function(cssProperty) { this._decorator = new WebInspector.PropertyRevealHighlighter(this, cssProperty); this._decorator.perform(); this.update(); }, onUndoOrRedoHappened: function() { this.setNode(this.node()); }, /** * @param {!Event} event */ _onAddButtonLongClick: function(event) { var cssModel = this.cssModel(); if (!cssModel) return; var headers = cssModel.styleSheetHeaders().filter(styleSheetResourceHeader); /** @type {!Array.<{text: string, handler: function()}>} */ var contextMenuDescriptors = []; for (var i = 0; i < headers.length; ++i) { var header = headers[i]; var handler = this._createNewRuleInStyleSheet.bind(this, header); contextMenuDescriptors.push({ text: WebInspector.displayNameForURL(header.resourceURL()), handler: handler }); } contextMenuDescriptors.sort(compareDescriptors); var contextMenu = new WebInspector.ContextMenu(event); for (var i = 0; i < contextMenuDescriptors.length; ++i) { var descriptor = contextMenuDescriptors[i]; contextMenu.appendItem(descriptor.text, descriptor.handler); } if (!contextMenu.isEmpty()) contextMenu.appendSeparator(); contextMenu.appendItem("inspector-stylesheet", this._createNewRuleInViaInspectorStyleSheet.bind(this)); contextMenu.show(); /** * @param {!{text: string, handler: function()}} descriptor1 * @param {!{text: string, handler: function()}} descriptor2 * @return {number} */ function compareDescriptors(descriptor1, descriptor2) { return String.naturalOrderComparator(descriptor1.text, descriptor2.text); } /** * @param {!WebInspector.CSSStyleSheetHeader} header * @return {boolean} */ function styleSheetResourceHeader(header) { return !header.isViaInspector() && !header.isInline && !!header.resourceURL(); } }, /** * @param {?RegExp} regex */ onFilterChanged: function(regex) { this._filterRegex = regex; this._updateFilter(); }, /** * @override * @param {?WebInspector.DOMNode} node */ setNode: function(node) { this._stylesPopoverHelper.hide(); node = WebInspector.SharedSidebarModel.elementNode(node); this._resetCache(); WebInspector.ElementsSidebarPane.prototype.setNode.call(this, node); }, /** * @param {!WebInspector.StylePropertiesSection=} editedSection */ _refreshUpdate: function(editedSection) { var node = this.node(); if (!node) return; var fullRefresh = Runtime.experiments.isEnabled("liveSASS"); for (var section of this.allSections()) { if (section.isBlank) continue; section.update(fullRefresh || section === editedSection); } if (this._filterRegex) this._updateFilter(); this._nodeStylesUpdatedForTest(node, false); }, /** * @override * @return {!Promise.<?>} */ doUpdate: function() { this._discardElementUnderMouse(); return this.fetchMatchedCascade() .then(this._innerRebuildUpdate.bind(this)); }, _resetCache: function() { delete this._matchedCascadePromise; }, /** * @return {!Promise.<?WebInspector.CSSMatchedStyles>} */ fetchMatchedCascade: function() { var node = this.node(); if (!node) return Promise.resolve(/** @type {?WebInspector.CSSMatchedStyles} */(null)); if (!this._matchedCascadePromise) this._matchedCascadePromise = this._matchedStylesForNode(node).then(validateStyles.bind(this)); return this._matchedCascadePromise; /** * @param {?WebInspector.CSSMatchedStyles} matchedStyles * @return {?WebInspector.CSSMatchedStyles} * @this {WebInspector.StylesSidebarPane} */ function validateStyles(matchedStyles) { return matchedStyles && matchedStyles.node() === this.node() ? matchedStyles : null; } }, /** * @param {!WebInspector.DOMNode} node * @return {!Promise.<?WebInspector.CSSMatchedStyles>} */ _matchedStylesForNode: function(node) { var cssModel = this.cssModel(); if (!cssModel) return Promise.resolve(/** @type {?WebInspector.CSSMatchedStyles} */(null)); return cssModel.matchedStylesPromise(node.id) }, /** * @param {boolean} editing */ setEditingStyle: function(editing) { if (this._isEditingStyle === editing) return; this.element.classList.toggle("is-editing-style", editing); this._isEditingStyle = editing; }, /** * @override * @param {!WebInspector.Event=} event */ onCSSModelChanged: function(event) { var edit = event && event.data ? /** @type {?WebInspector.CSSModel.Edit} */(event.data.edit) : null; if (edit) { for (var section of this.allSections()) section._styleSheetEdited(edit); return; } if (this._userOperation || this._isEditingStyle) return; this._resetCache(); this.update(); }, /** * @override */ onFrameResizedThrottled: function() { this.onCSSModelChanged(); }, /** * @override * @param {!WebInspector.DOMNode} node */ onDOMModelChanged: function(node) { // Any attribute removal or modification can affect the styles of "related" nodes. // Do not touch the styles if they are being edited. if (this._isEditingStyle || this._userOperation) return; if (!this._canAffectCurrentStyles(node)) return; this._resetCache(); this.update(); }, /** * @param {?WebInspector.DOMNode} node */ _canAffectCurrentStyles: function(node) { var currentNode = this.node(); return currentNode && (currentNode === node || node.parentNode === currentNode.parentNode || node.isAncestor(currentNode)); }, /** * @param {?WebInspector.CSSMatchedStyles} matchedStyles */ _innerRebuildUpdate: function(matchedStyles) { this._linkifier.reset(); this._sectionsContainer.removeChildren(); this._sectionBlocks = []; var node = this.node(); if (!matchedStyles || !node) return; this._sectionBlocks = this._rebuildSectionsForMatchedStyleRules(matchedStyles); var pseudoTypes = []; var keys = new Set(matchedStyles.pseudoStyles().keys()); if (keys.delete(DOMAgent.PseudoType.Before)) pseudoTypes.push(DOMAgent.PseudoType.Before); pseudoTypes = pseudoTypes.concat(keys.valuesArray().sort()); for (var pseudoType of pseudoTypes) { var block = WebInspector.SectionBlock.createPseudoTypeBlock(pseudoType); var styles = /** @type {!Array<!WebInspector.CSSStyleDeclaration>} */(matchedStyles.pseudoStyles().get(pseudoType)); for (var style of styles) { var section = new WebInspector.StylePropertiesSection(this, matchedStyles, style); block.sections.push(section); } this._sectionBlocks.push(block); } for (var keyframesRule of matchedStyles.keyframes()) { var block = WebInspector.SectionBlock.createKeyframesBlock(keyframesRule.name().text); for (var keyframe of keyframesRule.keyframes()) block.sections.push(new WebInspector.KeyframePropertiesSection(this, matchedStyles, keyframe.style)); this._sectionBlocks.push(block); } for (var block of this._sectionBlocks) { var titleElement = block.titleElement(); if (titleElement) this._sectionsContainer.appendChild(titleElement); for (var section of block.sections) this._sectionsContainer.appendChild(section.element); } if (this._filterRegex) this._updateFilter(); this._nodeStylesUpdatedForTest(node, true); if (this._decorator) { this._decorator.perform(); delete this._decorator; } }, /** * @param {!WebInspector.DOMNode} node * @param {boolean} rebuild */ _nodeStylesUpdatedForTest: function(node, rebuild) { // For sniffing in tests. }, /** * @param {!WebInspector.CSSMatchedStyles} matchedStyles * @return {!Array.<!WebInspector.SectionBlock>} */ _rebuildSectionsForMatchedStyleRules: function(matchedStyles) { var blocks = [new WebInspector.SectionBlock(null)]; var lastParentNode = null; for (var style of matchedStyles.nodeStyles()) { var parentNode = matchedStyles.isInherited(style) ? matchedStyles.nodeForStyle(style) : null; if (parentNode && parentNode !== lastParentNode) { lastParentNode = parentNode; var block = WebInspector.SectionBlock.createInheritedNodeBlock(lastParentNode); blocks.push(block); } var section = new WebInspector.StylePropertiesSection(this, matchedStyles, style); blocks.peekLast().sections.push(section); } return blocks; }, _createNewRuleInViaInspectorStyleSheet: function() { var cssModel = this.cssModel(); var node = this.node(); if (!cssModel || !node) return; this._userOperation = true; cssModel.requestViaInspectorStylesheet(node, onViaInspectorStyleSheet.bind(this)); /** * @param {?WebInspector.CSSStyleSheetHeader} styleSheetHeader * @this {WebInspector.StylesSidebarPane} */ function onViaInspectorStyleSheet(styleSheetHeader) { delete this._userOperation; this._createNewRuleInStyleSheet(styleSheetHeader); } }, /** * @param {?WebInspector.CSSStyleSheetHeader} styleSheetHeader */ _createNewRuleInStyleSheet: function(styleSheetHeader) { if (!styleSheetHeader) return; styleSheetHeader.requestContent().then(onStyleSheetContent.bind(this, styleSheetHeader.id)); /** * @param {string} styleSheetId * @param {?string} text * @this {WebInspector.StylesSidebarPane} */ function onStyleSheetContent(styleSheetId, text) { text = text || ""; var lines = text.split("\n"); var range = WebInspector.TextRange.createFromLocation(lines.length - 1, lines[lines.length - 1].length); this._addBlankSection(this._sectionBlocks[0].sections[0], styleSheetId, range); } }, /** * @param {!WebInspector.StylePropertiesSection} insertAfterSection * @param {string} styleSheetId * @param {!WebInspector.TextRange} ruleLocation */ _addBlankSection: function(insertAfterSection, styleSheetId, ruleLocation) { this.expand(); var node = this.node(); var blankSection = new WebInspector.BlankStylePropertiesSection(this, insertAfterSection._matchedStyles, node ? WebInspector.DOMPresentationUtils.simpleSelector(node) : "", styleSheetId, ruleLocation, insertAfterSection._style); this._sectionsContainer.insertBefore(blankSection.element, insertAfterSection.element.nextSibling); for (var block of this._sectionBlocks) { var index = block.sections.indexOf(insertAfterSection); if (index === -1) continue; block.sections.splice(index + 1, 0, blankSection); blankSection.startEditingSelector(); } }, /** * @param {!WebInspector.StylePropertiesSection} section */ removeSection: function(section) { for (var block of this._sectionBlocks) { var index = block.sections.indexOf(section); if (index === -1) continue; block.sections.splice(index, 1); section.element.remove(); } }, /** * @return {?RegExp} */ filterRegex: function() { return this._filterRegex; }, _updateFilter: function() { for (var block of this._sectionBlocks) block.updateFilter(); }, /** * @override */ wasShown: function() { WebInspector.ElementsSidebarPane.prototype.wasShown.call(this); this.element.ownerDocument.body.addEventListener("keydown", this._keyDownBound, false); this.element.ownerDocument.body.addEventListener("keyup", this._keyUpBound, false); }, /** * @override */ willHide: function() { this.element.ownerDocument.body.removeEventListener("keydown", this._keyDownBound, false); this.element.ownerDocument.body.removeEventListener("keyup", this._keyUpBound, false); this._stylesPopoverHelper.hide(); this._discardElementUnderMouse(); WebInspector.ElementsSidebarPane.prototype.willHide.call(this); }, _discardElementUnderMouse: function() { if (this._elementUnderMouse) this._elementUnderMouse.classList.remove("styles-panel-hovered"); delete this._elementUnderMouse; }, /** * @param {!Event} event */ _mouseMovedOverElement: function(event) { if (this._elementUnderMouse && event.target !== this._elementUnderMouse) this._discardElementUnderMouse(); this._elementUnderMouse = event.target; if (WebInspector.KeyboardShortcut.eventHasCtrlOrMeta(/** @type {!MouseEvent} */(event))) this._elementUnderMouse.classList.add("styles-panel-hovered"); }, /** * @param {!Event} event */ _keyDown: function(event) { if ((!WebInspector.isMac() && event.keyCode === WebInspector.KeyboardShortcut.Keys.Ctrl.code) || (WebInspector.isMac() && event.keyCode === WebInspector.KeyboardShortcut.Keys.Meta.code)) { if (this._elementUnderMouse) this._elementUnderMouse.classList.add("styles-panel-hovered"); } }, /** * @param {!Event} event */ _keyUp: function(event) { if ((!WebInspector.isMac() && event.keyCode === WebInspector.KeyboardShortcut.Keys.Ctrl.code) || (WebInspector.isMac() && event.keyCode === WebInspector.KeyboardShortcut.Keys.Meta.code)) { this._discardElementUnderMouse(); } }, /** * @return {!Array<!WebInspector.StylePropertiesSection>} */ allSections: function() { var sections = []; for (var block of this._sectionBlocks) sections = sections.concat(block.sections); return sections; }, __proto__: WebInspector.ElementsSidebarPane.prototype } /** * @param {string} placeholder * @param {!Element} container * @param {function(?RegExp)} filterCallback * @return {!Element} */ WebInspector.StylesSidebarPane.createPropertyFilterElement = function(placeholder, container, filterCallback) { var input = createElement("input"); input.placeholder = placeholder; function searchHandler() { var regex = input.value ? new RegExp(input.value.escapeForRegExp(), "i") : null; filterCallback(regex); container.classList.toggle("styles-filter-engaged", !!input.value); } input.addEventListener("input", searchHandler, false); /** * @param {!Event} event */ function keydownHandler(event) { var Esc = "U+001B"; if (event.keyIdentifier !== Esc || !input.value) return; event.consume(true); input.value = ""; searchHandler(); } input.addEventListener("keydown", keydownHandler, false); input.setFilterValue = setFilterValue; /** * @param {string} value */ function setFilterValue(value) { input.value = value; input.focus(); searchHandler(); } return input; } /** * @constructor * @param {?Element} titleElement */ WebInspector.SectionBlock = function(titleElement) { this._titleElement = titleElement; this.sections = []; } /** * @param {!DOMAgent.PseudoType} pseudoType * @return {!WebInspector.SectionBlock} */ WebInspector.SectionBlock.createPseudoTypeBlock = function(pseudoType) { var separatorElement = createElement("div"); separatorElement.className = "sidebar-separator"; separatorElement.textContent = WebInspector.UIString("Pseudo ::%s element", pseudoType); return new WebInspector.SectionBlock(separatorElement); } /** * @param {string} keyframesName * @return {!WebInspector.SectionBlock} */ WebInspector.SectionBlock.createKeyframesBlock = function(keyframesName) { var separatorElement = createElement("div"); separatorElement.className = "sidebar-separator"; separatorElement.textContent = WebInspector.UIString("@keyframes " + keyframesName); return new WebInspector.SectionBlock(separatorElement); } /** * @param {!WebInspector.DOMNode} node * @return {!WebInspector.SectionBlock} */ WebInspector.SectionBlock.createInheritedNodeBlock = function(node) { var separatorElement = createElement("div"); separatorElement.className = "sidebar-separator"; var link = WebInspector.DOMPresentationUtils.linkifyNodeReference(node); separatorElement.createTextChild(WebInspector.UIString("Inherited from") + " "); separatorElement.appendChild(link); return new WebInspector.SectionBlock(separatorElement); } WebInspector.SectionBlock.prototype = { updateFilter: function() { var hasAnyVisibleSection = false; for (var section of this.sections) hasAnyVisibleSection |= section._updateFilter(); if (this._titleElement) this._titleElement.classList.toggle("hidden", !hasAnyVisibleSection); }, /** * @return {?Element} */ titleElement: function() { return this._titleElement; } } /** * @constructor * @param {!WebInspector.StylesSidebarPane} parentPane * @param {!WebInspector.CSSMatchedStyles} matchedStyles * @param {!WebInspector.CSSStyleDeclaration} style */ WebInspector.StylePropertiesSection = function(parentPane, matchedStyles, style) { this._parentPane = parentPane; this._style = style; this._matchedStyles = matchedStyles; this.editable = !!(style.styleSheetId && style.range); var rule = style.parentRule; this.element = createElementWithClass("div", "styles-section matched-styles monospace"); this.element._section = this; this._titleElement = this.element.createChild("div", "styles-section-title " + (rule ? "styles-selector" : "")); this.propertiesTreeOutline = new TreeOutline(); this.propertiesTreeOutline.element.classList.add("style-properties", "monospace"); this.propertiesTreeOutline.section = this; this.element.appendChild(this.propertiesTreeOutline.element); var selectorContainer = createElement("div"); this._selectorElement = createElementWithClass("span", "selector"); this._selectorElement.textContent = this._headerText(); selectorContainer.appendChild(this._selectorElement); this._selectorElement.addEventListener("mouseenter", this._onMouseEnterSelector.bind(this), false); this._selectorElement.addEventListener("mouseleave", this._onMouseOutSelector.bind(this), false); var openBrace = createElement("span"); openBrace.textContent = " {"; selectorContainer.appendChild(openBrace); selectorContainer.addEventListener("mousedown", this._handleEmptySpaceMouseDown.bind(this), false); selectorContainer.addEventListener("click", this._handleSelectorContainerClick.bind(this), false); var closeBrace = this.element.createChild("div", "sidebar-pane-closing-brace"); closeBrace.textContent = "}"; if (this.editable) { var items = []; var colorButton = new WebInspector.ToolbarButton(WebInspector.UIString("Add color"), "foreground-color-toolbar-item"); colorButton.addEventListener("click", this._onInsertColorPropertyClick.bind(this)); items.push(colorButton); var backgroundButton = new WebInspector.ToolbarButton(WebInspector.UIString("Add background-color"), "background-color-toolbar-item"); backgroundButton.addEventListener("click", this._onInsertBackgroundColorPropertyClick.bind(this)); items.push(backgroundButton); if (rule) { var newRuleButton = new WebInspector.ToolbarButton(WebInspector.UIString("Insert Style Rule Below"), "add-toolbar-item"); newRuleButton.addEventListener("click", this._onNewRuleClick.bind(this)); items.push(newRuleButton); } var menuButton = new WebInspector.ToolbarButton(WebInspector.UIString("More tools\u2026"), "menu-toolbar-item"); items.push(menuButton); if (items.length) { var sectionToolbar = new WebInspector.Toolbar("sidebar-pane-section-toolbar", closeBrace); for (var i = 0; i < items.length; ++i) sectionToolbar.appendToolbarItem(items[i]); items.pop(); /** * @param {!Array<!WebInspector.ToolbarButton>} items * @param {boolean} value */ function setItemsVisibility(items, value) { for (var i = 0; i < items.length; ++i) items[i].setVisible(value); menuButton.setVisible(!value); } setItemsVisibility(items, false); sectionToolbar.element.addEventListener("mouseenter", setItemsVisibility.bind(null, items, true)); sectionToolbar.element.addEventListener("mouseleave", setItemsVisibility.bind(null, items, false)); } } this._selectorElement.addEventListener("click", this._handleSelectorClick.bind(this), false); this.element.addEventListener("mousedown", this._handleEmptySpaceMouseDown.bind(this), false); this.element.addEventListener("click", this._handleEmptySpaceClick.bind(this), false); if (rule) { // Prevent editing the user agent and user rules. if (rule.isUserAgent() || rule.isInjected()) { this.editable = false; } else { // Check this is a real CSSRule, not a bogus object coming from WebInspector.BlankStylePropertiesSection. if (rule.styleSheetId) this.navigable = !!rule.resourceURL(); } } this._mediaListElement = this._titleElement.createChild("div", "media-list media-matches"); this._selectorRefElement = this._titleElement.createChild("div", "styles-section-subtitle"); this._updateMediaList(); this._updateRuleOrigin(); this._titleElement.appendChild(selectorContainer); this._selectorContainer = selectorContainer; if (this.navigable) this.element.classList.add("navigable"); if (!this.editable) this.element.classList.add("read-only"); this._markSelectorMatches(); this.onpopulate(); } WebInspector.StylePropertiesSection.prototype = { /** * @return {!WebInspector.CSSStyleDeclaration} */ style: function() { return this._style; }, /** * @return {string} */ _headerText: function() { var node = this._matchedStyles.nodeForStyle(this._style); if (this._style.type === WebInspector.CSSStyleDeclaration.Type.Inline) return this._matchedStyles.isInherited(this._style) ? WebInspector.UIString("Style Attribute") : "element.style"; if (this._style.type === WebInspector.CSSStyleDeclaration.Type.Attributes) return node.nodeNameInCorrectCase() + "[" + WebInspector.UIString("Attributes Style") + "]"; return this._style.parentRule.selectorText(); }, _onMouseOutSelector: function() { if (this._hoverTimer) clearTimeout(this._hoverTimer); WebInspector.DOMModel.hideDOMNodeHighlight() }, _onMouseEnterSelector: function() { if (this._hoverTimer) clearTimeout(this._hoverTimer); this._hoverTimer = setTimeout(this._highlight.bind(this), 300); }, _highlight: function() { WebInspector.DOMModel.hideDOMNodeHighlight(); var node = this._parentPane.node(); var domModel = node.domModel(); var selectors = this._style.parentRule ? this._style.parentRule.selectorText() : undefined; domModel.highlightDOMNodeWithConfig(node.id, { mode: "all", showInfo: undefined, selectors: selectors }); }, /** * @return {?WebInspector.StylePropertiesSection} */ firstSibling: function() { var parent = this.element.parentElement; if (!parent) return null; var childElement = parent.firstChild; while (childElement) { if (childElement._section) return childElement._section; childElement = childElement.nextSibling; } return null; }, /** * @return {?WebInspector.StylePropertiesSection} */ lastSibling: function() { var parent = this.element.parentElement; if (!parent) return null; var childElement = parent.lastChild; while (childElement) { if (childElement._section) return childElement._section; childElement = childElement.previousSibling; } return null; }, /** * @return {?WebInspector.StylePropertiesSection} */ nextSibling: function() { var curElement = this.element; do { curElement = curElement.nextSibling; } while (curElement && !curElement._section); return curElement ? curElement._section : null; }, /** * @return {?WebInspector.StylePropertiesSection} */ previousSibling: function() { var curElement = this.element; do { curElement = curElement.previousSibling; } while (curElement && !curElement._section); return curElement ? curElement._section : null; }, /** * @param {!WebInspector.Event} event */ _onNewRuleClick: function(event) { event.consume(); var rule = this._style.parentRule; var range = WebInspector.TextRange.createFromLocation(rule.style.range.endLine, rule.style.range.endColumn + 1); this._parentPane._addBlankSection(this, /** @type {string} */(rule.styleSheetId), range); }, /** * @param {!WebInspector.Event} event */ _onInsertColorPropertyClick: function(event) { event.consume(true); var treeElement = this.addNewBlankProperty(); treeElement.property.name = "color"; treeElement.property.value = "black"; treeElement.updateTitle(); var colorSwatch = WebInspector.ColorSwatchPopoverIcon.forTreeElement(treeElement); if (colorSwatch) colorSwatch.showPopover(); }, /** * @param {!WebInspector.Event} event */ _onInsertBackgroundColorPropertyClick: function(event) { event.consume(true); var treeElement = this.addNewBlankProperty(); treeElement.property.name = "background-color"; treeElement.property.value = "white"; treeElement.updateTitle(); var colorSwatch = WebInspector.ColorSwatchPopoverIcon.forTreeElement(treeElement); if (colorSwatch) colorSwatch.showPopover(); }, /** * @param {!WebInspector.CSSModel.Edit} edit */ _styleSheetEdited: function(edit) { var rule = this._style.parentRule; if (rule) rule.rebase(edit); else this._style.rebase(edit); this._updateMediaList(); this._updateRuleOrigin(); }, /** * @param {!Array.<!WebInspector.CSSMedia>} mediaRules */ _createMediaList: function(mediaRules) { for (var i = mediaRules.length - 1; i >= 0; --i) { var media = mediaRules[i]; // Don't display trivial non-print media types. if (!media.text.includes("(") && media.text !== "print") continue; var mediaDataElement = this._mediaListElement.createChild("div", "media"); var mediaContainerElement = mediaDataElement.createChild("span"); var mediaTextElement = mediaContainerElement.createChild("span", "media-text"); switch (media.source) { case WebInspector.CSSMedia.Source.LINKED_SHEET: case WebInspector.CSSMedia.Source.INLINE_SHEET: mediaTextElement.textContent = "media=\"" + media.text + "\""; break; case WebInspector.CSSMedia.Source.MEDIA_RULE: var decoration = mediaContainerElement.createChild("span"); mediaContainerElement.insertBefore(decoration, mediaTextElement); decoration.textContent = "@media "; mediaTextElement.textContent = media.text; if (media.parentStyleSheetId) { mediaDataElement.classList.add("editable-media"); mediaTextElement.addEventListener("click", this._handleMediaRuleClick.bind(this, media, mediaTextElement), false); } break; case WebInspector.CSSMedia.Source.IMPORT_RULE: mediaTextElement.textContent = "@import " + media.text; break; } } }, _updateMediaList: function() { this._mediaListElement.removeChildren(); if (this._style.parentRule && this._style.parentRule instanceof WebInspector.CSSStyleRule) this._createMediaList(this._style.parentRule.media); }, /** * @param {string} propertyName * @return {boolean} */ isPropertyInherited: function(propertyName) { if (this._matchedStyles.isInherited(this._style)) { // While rendering inherited stylesheet, reverse meaning of this property. // Render truly inherited properties with black, i.e. return them as non-inherited. return !WebInspector.CSSMetadata.isPropertyInherited(propertyName); } return false; }, /** * @return {?WebInspector.StylePropertiesSection} */ nextEditableSibling: function() { var curSection = this; do { curSection = curSection.nextSibling(); } while (curSection && !curSection.editable); if (!curSection) { curSection = this.firstSibling(); while (curSection && !curSection.editable) curSection = curSection.nextSibling(); } return (curSection && curSection.editable) ? curSection : null; }, /** * @return {?WebInspector.StylePropertiesSection} */ previousEditableSibling: function() { var curSection = this; do { curSection = curSection.previousSibling(); } while (curSection && !curSection.editable); if (!curSection) { curSection = this.lastSibling(); while (curSection && !curSection.editable) curSection = curSection.previousSibling(); } return (curSection && curSection.editable) ? curSection : null; }, /** * @param {boolean} full */ update: function(full) { this._selectorElement.textContent = this._headerText(); this._markSelectorMatches(); if (full) { this.propertiesTreeOutline.removeChildren(); this.onpopulate(); } else { var child = this.propertiesTreeOutline.firstChild(); while (child) { child.setOverloaded(this._isPropertyOverloaded(child.property)); child = child.traverseNextTreeElement(false, null, true); } } this.afterUpdate(); }, afterUpdate: function() { if (this._afterUpdate) { this._afterUpdate(this); delete this._afterUpdate; this._afterUpdateFinishedForTest(); } }, _afterUpdateFinishedForTest: function() { }, onpopulate: function() { var style = this._style; for (var property of style.leadingProperties()) { var isShorthand = !!style.longhandProperties(property.name).length; var inherited = this.isPropertyInherited(property.name); var overloaded = this._isPropertyOverloaded(property); var item = new WebInspector.StylePropertyTreeElement(this._parentPane, this._matchedStyles, property, isShorthand, inherited, overloaded); this.propertiesTreeOutline.appendChild(item); } }, /** * @param {!WebInspector.CSSProperty} property * @return {boolean} */ _isPropertyOverloaded: function(property) { return this._matchedStyles.propertyState(property) === WebInspector.CSSMatchedStyles.PropertyState.Overloaded; }, /** * @return {boolean} */ _updateFilter: function() { var hasMatchingChild = false; for (var child of this.propertiesTreeOutline.rootElement().children()) hasMatchingChild |= child._updateFilter(); var regex = this._parentPane.filterRegex(); var hideRule = !hasMatchingChild && !!regex && !regex.test(this.element.textContent); this.element.classList.toggle("hidden", hideRule); if (!hideRule && this._style.parentRule) this._markSelectorHighlights(); return !hideRule; }, _markSelectorMatches: function() { var rule = this._style.parentRule; if (!rule) return; this._mediaListElement.classList.toggle("media-matches", this._matchedStyles.mediaMatches(this._style)); if (!this._matchedStyles.hasMatchingSelectors(/** @type {!WebInspector.CSSStyleRule} */(rule))) return; var selectors = rule.selectors; var fragment = createDocumentFragment(); var currentMatch = 0; var matchingSelectors = this._matchedStyles.matchingSelectors(/** @type {!WebInspector.CSSStyleRule} */(rule)); for (var i = 0; i < selectors.length ; ++i) { if (i) fragment.createTextChild(", "); var isSelectorMatching = matchingSelectors[currentMatch] === i; if (isSelectorMatching) ++currentMatch; var matchingSelectorClass = isSelectorMatching ? " selector-matches" : ""; var selectorElement = createElement("span"); selectorElement.className = "simple-selector" + matchingSelectorClass; if (rule.styleSheetId) selectorElement._selectorIndex = i; selectorElement.textContent = selectors[i].text; fragment.appendChild(selectorElement); } this._selectorElement.removeChildren(); this._selectorElement.appendChild(fragment); this._markSelectorHighlights(); }, _markSelectorHighlights: function() { var selectors = this._selectorElement.getElementsByClassName("simple-selector"); var regex = this._parentPane.filterRegex(); for (var i = 0; i < selectors.length; ++i) { var selectorMatchesFilter = !!regex && regex.test(selectors[i].textContent); selectors[i].classList.toggle("filter-match", selectorMatchesFilter); } }, /** * @return {boolean} */ _checkWillCancelEditing: function() { var willCauseCancelEditing = this._willCauseCancelEditing; delete this._willCauseCancelEditing; return willCauseCancelEditing; }, /** * @param {!Event} event */ _handleSelectorContainerClick: function(event) { if (this._checkWillCancelEditing() || !this.editable) return; if (event.target === this._selectorContainer) { this.addNewBlankProperty(0).startEditing(); event.consume(true); } }, /** * @param {number=} index * @return {!WebInspector.StylePropertyTreeElement} */ addNewBlankProperty: function(index) { var property = this._style.newBlankProperty(index); var item = new WebInspector.StylePropertyTreeElement(this._parentPane, this._matchedStyles, property, false, false, false); index = property.index; this.propertiesTreeOutline.insertChild(item, index); item.listItemElement.textContent = ""; item._newProperty = true; item.updateTitle(); return item; }, _handleEmptySpaceMouseDown: function() { this._willCauseCancelEditing = this._parentPane._isEditingStyle; }, /** * @param {!Event} event */ _handleEmptySpaceClick: function(event) { if (!this.editable) return; if (!event.target.isComponentSelectionCollapsed()) return; if (this._checkWillCancelEditing()) return; if (event.target.enclosingNodeOrSelfWithNodeName("a")) return; if (event.target.classList.contains("header") || this.element.classList.contains("read-only") || event.target.enclosingNodeOrSelfWithClass("media")) { event.consume(); return; } this.addNewBlankProperty().startEditing(); event.consume(true); }, /** * @param {!WebInspector.CSSMedia} media * @param {!Element} element * @param {!Event} event */ _handleMediaRuleClick: function(media, element, event) { if (WebInspector.isBeingEdited(element)) return; if (WebInspector.KeyboardShortcut.eventHasCtrlOrMeta(/** @type {!MouseEvent} */(event)) && this.navigable) { var location = media.rawLocation(); if (!location) { event.consume(true); return; } var uiLocation = WebInspector.cssWorkspaceBinding.rawLocationToUILocation(location); if (uiLocation) WebInspector.Revealer.reveal(uiLocation); event.consume(true); return; } var config = new WebInspector.InplaceEditor.Config(this._editingMediaCommitted.bind(this, media), this._editingMediaCancelled.bind(this, element), undefined, this._editingMediaBlurHandler.bind(this)); WebInspector.InplaceEditor.startEditing(element, config); element.getComponentSelection().setBaseAndExtent(element, 0, element, 1); this._parentPane.setEditingStyle(true); var parentMediaElement = element.enclosingNodeOrSelfWithClass("media"); parentMediaElement.classList.add("editing-media"); event.consume(true); }, /** * @param {!Element} element */ _editingMediaFinished: function(element) { this._parentPane.setEditingStyle(false); var parentMediaElement = element.enclosingNodeOrSelfWithClass("media"); parentMediaElement.classList.remove("editing-media"); }, /** * @param {!Element} element */ _editingMediaCancelled: function(element) { this._editingMediaFinished(element); // Mark the selectors in group if necessary. // This is overridden by BlankStylePropertiesSection. this._markSelectorMatches(); element.getComponentSelection().collapse(element, 0); }, /** * @param {!Element} editor * @param {!Event} blurEvent * @return {boolean} */ _editingMediaBlurHandler: function(editor, blurEvent) { return true; }, /** * @param {!WebInspector.CSSMedia} media * @param {!Element} element * @param {string} newContent * @param {string} oldContent * @param {(!WebInspector.StylePropertyTreeElement.Context|undefined)} context * @param {string} moveDirection */ _editingMediaCommitted: function(media, element, newContent, oldContent, context, moveDirection) { this._parentPane.setEditingStyle(false); this._editingMediaFinished(element); if (newContent) newContent = newContent.trim(); /** * @param {boolean} success * @this {WebInspector.StylePropertiesSection} */ function userCallback(success) { if (success) { this._matchedStyles.resetActiveProperties(); this._parentPane._refreshUpdate(this); } delete this._parentPane._userOperation; this._editingMediaTextCommittedForTest(); } // This gets deleted in finishOperation(), which is called both on success and failure. this._parentPane._userOperation = true; this._parentPane._cssModel.setMediaText(media, newContent, userCallback.bind(this)); }, _editingMediaTextCommittedForTest: function() { }, /** * @param {!Event} event */ _handleSelectorClick: function(event) { if (WebInspector.KeyboardShortcut.eventHasCtrlOrMeta(/** @type {!MouseEvent} */(event)) && this.navigable && event.target.classList.contains("simple-selector")) { var index = event.target._selectorIndex; var cssModel = this._parentPane._cssModel; var rule = this._style.parentRule; var header = cssModel.styleSheetHeaderForId(/** @type {string} */(rule.styleSheetId)); if (!header) { event.consume(true); return; } var rawLocation = new WebInspector.CSSLocation(header, rule.lineNumberInSource(index), rule.columnNumberInSource(index)); var uiLocation = WebInspector.cssWorkspaceBinding.rawLocationToUILocation(rawLocation); if (uiLocation) WebInspector.Revealer.reveal(uiLocation); event.consume(true); return; } this._startEditingOnMouseEvent(); event.consume(true); }, _startEditingOnMouseEvent: function() { if (!this.editable) return; var rule = this._style.parentRule; if (!rule && !this.propertiesTreeOutline.rootElement().childCount()) { this.addNewBlankProperty().startEditing(); return; } if (!rule) return; this.startEditingSelector(); }, startEditingSelector: function() { var element = this._selectorElement; if (WebInspector.isBeingEdited(element)) return; element.scrollIntoViewIfNeeded(false); element.textContent = element.textContent; // Reset selector marks in group. var config = new WebInspector.InplaceEditor.Config(this.editingSelectorCommitted.bind(this), this.editingSelectorCancelled.bind(this)); WebInspector.InplaceEditor.startEditing(this._selectorElement, config); element.getComponentSelection().setBaseAndExtent(element, 0, element, 1); this._parentPane.setEditingStyle(true); }, /** * @param {string} moveDirection */ _moveEditorFromSelector: function(moveDirection) { this._markSelectorMatches(); if (!moveDirection) return; if (moveDirection === "forward") { var firstChild = this.propertiesTreeOutline.firstChild(); while (firstChild && firstChild.inherited()) firstChild = firstChild.nextSibling; if (!firstChild) this.addNewBlankProperty().startEditing(); else firstChild.startEditing(firstChild.nameElement); } else { var previousSection = this.previousEditableSibling(); if (!previousSection) return; previousSection.addNewBlankProperty().startEditing(); } }, /** * @param {!Element} element * @param {string} newContent * @param {string} oldContent * @param {(!WebInspector.StylePropertyTreeElement.Context|undefined)} context * @param {string} moveDirection */ editingSelectorCommitted: function(element, newContent, oldContent, context, moveDirection) { this._editingSelectorEnded(); if (newContent) newContent = newContent.trim(); if (newContent === oldContent) { // Revert to a trimmed version of the selector if need be. this._selectorElement.textContent = newContent; this._moveEditorFromSelector(moveDirection); return; } var rule = this._style.parentRule; if (!rule) return; /** * @this {WebInspector.StylePropertiesSection} */ function headerTextCommitted() { delete this._parentPane._userOperation; this._moveEditorFromSelector(moveDirection); this._editingSelectorCommittedForTest(); } // This gets deleted in finishOperationAndMoveEditor(), which is called both on success and failure. this._parentPane._userOperation = true; this._setHeaderText(rule, newContent).then(headerTextCommitted.bind(this)); }, /** * @param {!WebInspector.CSSRule} rule * @param {string} newContent * @return {!Promise} */ _setHeaderText: function(rule, newContent) { /** * @param {!WebInspector.CSSStyleRule} rule * @param {boolean} success * @return {!Promise} * @this {WebInspector.StylePropertiesSection} */ function onSelectorsUpdated(rule, success) { if (!success) return Promise.resolve(); return this._matchedStyles.recomputeMatchingSelectors(rule) .then(updateSourceRanges.bind(this, rule)); } /** * @param {!WebInspector.CSSStyleRule} rule * @this {WebInspector.StylePropertiesSection} */ function updateSourceRanges(rule) { var doesAffectSelectedNode = this._matchedStyles.matchingSelectors(rule).length > 0; this.element.classList.toggle("no-affect", !doesAffectSelectedNode); this._matchedStyles.resetActiveProperties(); this._parentPane._refreshUpdate(this); } console.assert(rule instanceof WebInspector.CSSStyleRule); var oldSelectorRange = rule.selectorRange(); if (!oldSelectorRange) return Promise.resolve(); var selectedNode = this._parentPane.node(); return rule.setSelectorText(newContent) .then(onSelectorsUpdated.bind(this, /** @type {!WebInspector.CSSStyleRule} */(rule), oldSelectorRange)); }, _editingSelectorCommittedForTest: function() { }, _updateRuleOrigin: function() { this._selectorRefElement.removeChildren(); this._selectorRefElement.appendChild(WebInspector.StylePropertiesSection.createRuleOriginNode(this._matchedStyles, this._parentPane._linkifier, this._style.parentRule)); }, _editingSelectorEnded: function() { this._parentPane.setEditingStyle(false); }, editingSelectorCancelled: function() { this._editingSelectorEnded(); // Mark the selectors in group if necessary. // This is overridden by BlankStylePropertiesSection. this._markSelectorMatches(); } } /** * @param {!WebInspector.CSSMatchedStyles} matchedStyles * @param {!WebInspector.Linkifier} linkifier * @param {?WebInspector.CSSRule} rule * @return {!Node} */ WebInspector.StylePropertiesSection.createRuleOriginNode = function(matchedStyles, linkifier, rule) { if (!rule) return createTextNode(""); var ruleLocation; if (rule instanceof WebInspector.CSSStyleRule) { var matchingSelectors = matchedStyles.matchingSelectors(rule); var firstMatchingIndex = matchingSelectors.length ? matchingSelectors[0] : 0; ruleLocation = rule.selectors[firstMatchingIndex].range; } else if (rule instanceof WebInspector.CSSKeyframeRule) { ruleLocation = rule.key().range; } var header = rule.styleSheetId ? matchedStyles.cssModel().styleSheetHeaderForId(rule.styleSheetId) : null; if (ruleLocation && rule.styleSheetId && header && header.resourceURL()) return WebInspector.StylePropertiesSection._linkifyRuleLocation(matchedStyles.cssModel(), linkifier, rule.styleSheetId, ruleLocation); if (rule.isUserAgent()) return createTextNode(WebInspector.UIString("user agent stylesheet")); if (rule.isInjected()) return createTextNode(WebInspector.UIString("injected stylesheet")); if (rule.isViaInspector()) return createTextNode(WebInspector.UIString("via inspector")); if (header && header.ownerNode) { var link = WebInspector.DOMPresentationUtils.linkifyDeferredNodeReference(header.ownerNode); link.textContent = "<style>…</style>"; return link; } return createTextNode(""); } /** * @param {!WebInspector.CSSModel} cssModel * @param {!WebInspector.Linkifier} linkifier * @param {string} styleSheetId * @param {!WebInspector.TextRange} ruleLocation * @return {!Node} */ WebInspector.StylePropertiesSection._linkifyRuleLocation = function(cssModel, linkifier, styleSheetId, ruleLocation) { var styleSheetHeader = cssModel.styleSheetHeaderForId(styleSheetId); var lineNumber = styleSheetHeader.lineNumberInSource(ruleLocation.startLine); var columnNumber = styleSheetHeader.columnNumberInSource(ruleLocation.startLine, ruleLocation.startColumn); var matchingSelectorLocation = new WebInspector.CSSLocation(styleSheetHeader, lineNumber, columnNumber); return linkifier.linkifyCSSLocation(matchingSelectorLocation); } /** * @constructor * @extends {WebInspector.StylePropertiesSection} * @param {!WebInspector.StylesSidebarPane} stylesPane * @param {!WebInspector.CSSMatchedStyles} matchedStyles * @param {string} defaultSelectorText * @param {string} styleSheetId * @param {!WebInspector.TextRange} ruleLocation * @param {!WebInspector.CSSStyleDeclaration} insertAfterStyle */ WebInspector.BlankStylePropertiesSection = function(stylesPane, matchedStyles, defaultSelectorText, styleSheetId, ruleLocation, insertAfterStyle) { var rule = WebInspector.CSSStyleRule.createDummyRule(stylesPane._cssModel, defaultSelectorText); WebInspector.StylePropertiesSection.call(this, stylesPane, matchedStyles, rule.style); this._ruleLocation = ruleLocation; this._styleSheetId = styleSheetId; this._selectorRefElement.removeChildren(); this._selectorRefElement.appendChild(WebInspector.StylePropertiesSection._linkifyRuleLocation(this._parentPane._cssModel, this._parentPane._linkifier, styleSheetId, this._actualRuleLocation())); if (insertAfterStyle && insertAfterStyle.parentRule) this._createMediaList(insertAfterStyle.parentRule.media); this.element.classList.add("blank-section"); } WebInspector.BlankStylePropertiesSection.prototype = { /** * @return {!WebInspector.TextRange} */ _actualRuleLocation: function() { var prefix = this._rulePrefix(); var lines = prefix.split("\n"); var editRange = new WebInspector.TextRange(0, 0, lines.length - 1, lines.peekLast().length); return this._ruleLocation.rebaseAfterTextEdit(WebInspector.TextRange.createFromLocation(0, 0), editRange); }, /** * @return {string} */ _rulePrefix: function() { return this._ruleLocation.startLine === 0 && this._ruleLocation.startColumn === 0 ? "" : "\n\n"; }, /** * @return {boolean} */ get isBlank() { return !this._normal; }, /** * @override * @param {!Element} element * @param {string} newContent * @param {string} oldContent * @param {!WebInspector.StylePropertyTreeElement.Context|undefined} context * @param {string} moveDirection */ editingSelectorCommitted: function(element, newContent, oldContent, context, moveDirection) { if (!this.isBlank) { WebInspector.StylePropertiesSection.prototype.editingSelectorCommitted.call(this, element, newContent, oldContent, context, moveDirection); return; } /** * @param {?WebInspector.CSSStyleRule} newRule * @return {!Promise} * @this {WebInspector.StylePropertiesSection} */ function onRuleAdded(newRule) { if (!newRule) { this.editingSelectorCancelled(); this._editingSelectorCommittedForTest(); return Promise.resolve(); } return this._matchedStyles.addNewRule(newRule, this._matchedStyles.node()) .then(onAddedToCascade.bind(this, newRule)); } /** * @param {!WebInspector.CSSStyleRule} newRule * @this {WebInspector.StylePropertiesSection} */ function onAddedToCascade(newRule) { var doesSelectorAffectSelectedNode = this._matchedStyles.matchingSelectors(newRule).length > 0; this._makeNormal(newRule); if (!doesSelectorAffectSelectedNode) this.element.classList.add("no-affect"); this._updateRuleOrigin(); if (this.element.parentElement) // Might have been detached already. this._moveEditorFromSelector(moveDirection); delete this._parentPane._userOperation; this._editingSelectorEnded(); this._markSelectorMatches(); this._editingSelectorCommittedForTest(); } if (newContent) newContent = newContent.trim(); this._parentPane._userOperation = true; var cssModel = this._parentPane._cssModel; var ruleText = this._rulePrefix() + newContent + " {}"; cssModel.addRule(this._styleSheetId, ruleText, this._ruleLocation) .then(onRuleAdded.bind(this)); }, editingSelectorCancelled: function() { delete this._parentPane._userOperation; if (!this.isBlank) { WebInspector.StylePropertiesSection.prototype.editingSelectorCancelled.call(this); return; } this._editingSelectorEnded(); this._parentPane.removeSection(this); }, /** * @param {!WebInspector.CSSRule} newRule */ _makeNormal: function(newRule) { this.element.classList.remove("blank-section"); this._style = newRule.style; // FIXME: replace this instance by a normal WebInspector.StylePropertiesSection. this._normal = true; }, __proto__: WebInspector.StylePropertiesSection.prototype } /** * @constructor * @extends {WebInspector.StylePropertiesSection} * @param {!WebInspector.StylesSidebarPane} stylesPane * @param {!WebInspector.CSSMatchedStyles} matchedStyles * @param {!WebInspector.CSSStyleDeclaration} style */ WebInspector.KeyframePropertiesSection = function(stylesPane, matchedStyles, style) { WebInspector.StylePropertiesSection.call(this, stylesPane, matchedStyles, style); this._selectorElement.className = "keyframe-key"; } WebInspector.KeyframePropertiesSection.prototype = { /** * @override * @return {string} */ _headerText: function() { return this._style.parentRule.key().text; }, /** * @override * @param {!WebInspector.CSSRule} rule * @param {string} newContent * @return {!Promise} */ _setHeaderText: function(rule, newContent) { /** * @param {boolean} success * @this {WebInspector.KeyframePropertiesSection} */ function updateSourceRanges(success) { if (!success) return; this._parentPane._refreshUpdate(this); } console.assert(rule instanceof WebInspector.CSSKeyframeRule); var oldRange = rule.key().range; if (!oldRange) return Promise.resolve(); var selectedNode = this._parentPane.node(); return rule.setKeyText(newContent).then(updateSourceRanges.bind(this)); }, /** * @override * @param {string} propertyName * @return {boolean} */ isPropertyInherited: function(propertyName) { return false; }, /** * @override * @param {!WebInspector.CSSProperty} property * @return {boolean} */ _isPropertyOverloaded: function(property) { return false; }, /** * @override */ _markSelectorHighlights: function() { }, /** * @override */ _markSelectorMatches: function() { this._selectorElement.textContent = this._style.parentRule.key().text; }, /** * @override */ _highlight: function() { }, __proto__: WebInspector.StylePropertiesSection.prototype } /** * @constructor * @extends {TreeElement} * @param {!WebInspector.StylesSidebarPane} stylesPane * @param {!WebInspector.CSSMatchedStyles} matchedStyles * @param {!WebInspector.CSSProperty} property * @param {boolean} isShorthand * @param {boolean} inherited * @param {boolean} overloaded */ WebInspector.StylePropertyTreeElement = function(stylesPane, matchedStyles, property, isShorthand, inherited, overloaded) { // Pass an empty title, the title gets made later in onattach. TreeElement.call(this, "", isShorthand); this._style = property.ownerStyle; this._matchedStyles = matchedStyles; this.property = property; this._inherited = inherited; this._overloaded = overloaded; this.selectable = false; this._parentPane = stylesPane; this.isShorthand = isShorthand; this._applyStyleThrottler = new WebInspector.Throttler(0); } /** @typedef {{expanded: boolean, hasChildren: boolean, isEditingName: boolean, previousContent: string}} */ WebInspector.StylePropertyTreeElement.Context; WebInspector.StylePropertyTreeElement.prototype = { /** * @return {boolean} */ _editable: function() { return this._style.styleSheetId && this._style.range; }, /** * @return {boolean} */ inherited: function() { return this._inherited; }, /** * @return {boolean} */ overloaded: function() { return this._overloaded; }, /** * @param {boolean} x */ setOverloaded: function(x) { if (x === this._overloaded) return; this._overloaded = x; this._updateState(); }, get name() { return this.property.name; }, get value() { return this.property.value; }, /** * @return {boolean} */ _updateFilter: function() { var regex = this._parentPane.filterRegex(); var matches = !!regex && (regex.test(this.property.name) || regex.test(this.property.value)); this.listItemElement.classList.toggle("filter-match", matches); this.onpopulate(); var hasMatchingChildren = false; for (var i = 0; i < this.childCount(); ++i) hasMatchingChildren |= this.childAt(i)._updateFilter(); if (!regex) { if (this._expandedDueToFilter) this.collapse(); this._expandedDueToFilter = false; } else if (hasMatchingChildren && !this.expanded) { this.expand(); this._expandedDueToFilter = true; } else if (!hasMatchingChildren && this.expanded && this._expandedDueToFilter) { this.collapse(); this._expandedDueToFilter = false; } return matches; }, /** * @param {string} text * @return {!Node} */ _processColor: function(text) { // We can be called with valid non-color values of |text| (like 'none' from border style) var color = WebInspector.Color.parse(text); if (!color) return createTextNode(text); if (!this._editable()) { var swatch = WebInspector.ColorSwatch.create(); swatch.setColorText(text); return swatch; } var stylesPopoverHelper = this._parentPane._stylesPopoverHelper; var swatchIcon = new WebInspector.ColorSwatchPopoverIcon(this, stylesPopoverHelper, text); /** * @param {?Array<string>} backgroundColors */ function computedCallback(backgroundColors) { // TODO(aboxhall): distinguish between !backgroundColors (no text) and // !backgroundColors.length (no computed bg color) if (!backgroundColors || !backgroundColors.length) return; // TODO(samli): figure out what to do in the case of multiple background colors (i.e. gradients) var bgColorText = backgroundColors[0]; var bgColor = WebInspector.Color.parse(bgColorText); if (!bgColor) return; // If we have a semi-transparent background color over an unknown // background, draw the line for the "worst case" scenario: where // the unknown background is the same color as the text. if (bgColor.hasAlpha) { var blendedRGBA = []; WebInspector.Color.blendColors(bgColor.rgba(), color.rgba(), blendedRGBA); bgColor = new WebInspector.Color(blendedRGBA, WebInspector.Color.Format.RGBA); } swatchIcon.setContrastColor(bgColor); } if (this.property.name === "color" && this._parentPane.cssModel() && this.node()) { var cssModel = this._parentPane.cssModel(); cssModel.backgroundColorsPromise(this.node().id).then(computedCallback); } return swatchIcon.element(); }, /** * @return {string} */ renderedPropertyText: function() { return this.nameElement.textContent + ": " + this.valueElement.textContent; }, /** * @param {string} text * @return {!Node} */ _processBezier: function(text) { var geometry = WebInspector.Geometry.CubicBezier.parse(text); if (!geometry || !this._editable()) return createTextNode(text); var stylesPopoverHelper = this._parentPane._stylesPopoverHelper; return new WebInspector.BezierPopoverIcon(this, stylesPopoverHelper, text).element(); }, _updateState: function() { if (!this.listItemElement) return; if (this._style.isPropertyImplicit(this.name)) this.listItemElement.classList.add("implicit"); else this.listItemElement.classList.remove("implicit"); var hasIgnorableError = !this.property.parsedOk && WebInspector.StylesSidebarPane.ignoreErrorsForProperty(this.property); if (hasIgnorableError) this.listItemElement.classList.add("has-ignorable-error"); else this.listItemElement.classList.remove("has-ignorable-error"); if (this.inherited()) this.listItemElement.classList.add("inherited"); else this.listItemElement.classList.remove("inherited"); if (this.overloaded()) this.listItemElement.classList.add("overloaded"); else this.listItemElement.classList.remove("overloaded"); if (this.property.disabled) this.listItemElement.classList.add("disabled"); else this.listItemElement.classList.remove("disabled"); }, /** * @return {?WebInspector.DOMNode} */ node: function() { return this._parentPane.node(); }, /** * @return {!WebInspector.StylesSidebarPane} */ parentPane: function() { return this._parentPane; }, /** * @return {?WebInspector.StylePropertiesSection} */ section: function() { return this.treeOutline && this.treeOutline.section; }, _updatePane: function() { var section = this.section(); if (section && section._parentPane) section._parentPane._refreshUpdate(section); }, /** * @param {!Event} event */ _toggleEnabled: function(event) { var disabled = !event.target.checked; var oldStyleRange = this._style.range; if (!oldStyleRange) return; /** * @param {boolean} success * @this {WebInspector.StylePropertyTreeElement} */ function callback(success) { delete this._parentPane._userOperation; if (!success) return; this._matchedStyles.resetActiveProperties(); this._updatePane(); this.styleTextAppliedForTest(); } event.consume(); this._parentPane._userOperation = true; this.property.setDisabled(disabled) .then(callback.bind(this)); }, /** * @override */ onpopulate: function() { // Only populate once and if this property is a shorthand. if (this.childCount() || !this.isShorthand) return; var longhandProperties = this._style.longhandProperties(this.name); for (var i = 0; i < longhandProperties.length; ++i) { var name = longhandProperties[i].name; var inherited = false; var overloaded = false; var section = this.section(); if (section) { inherited = section.isPropertyInherited(name); overloaded = this._matchedStyles.propertyState(longhandProperties[i]) === WebInspector.CSSMatchedStyles.PropertyState.Overloaded; } var item = new WebInspector.StylePropertyTreeElement(this._parentPane, this._matchedStyles, longhandProperties[i], false, inherited, overloaded); this.appendChild(item); } }, /** * @override */ onattach: function() { this.updateTitle(); this.listItemElement.addEventListener("mousedown", this._mouseDown.bind(this)); this.listItemElement.addEventListener("mouseup", this._resetMouseDownElement.bind(this)); this.listItemElement.addEventListener("click", this._mouseClick.bind(this)); }, /** * @param {!Event} event */ _mouseDown: function(event) { if (this._parentPane) { this._parentPane._mouseDownTreeElement = this; this._parentPane._mouseDownTreeElementIsName = this.nameElement && this.nameElement.isSelfOrAncestor(event.target); this._parentPane._mouseDownTreeElementIsValue = this.valueElement && this.valueElement.isSelfOrAncestor(event.target); } }, _resetMouseDownElement: function() { if (this._parentPane) { delete this._parentPane._mouseDownTreeElement; delete this._parentPane._mouseDownTreeElementIsName; delete this._parentPane._mouseDownTreeElementIsValue; } }, updateTitle: function() { this._updateState(); this._expandElement = createElement("span"); this._expandElement.className = "expand-element"; var propertyRenderer = new WebInspector.StylesSidebarPropertyRenderer(this._style.parentRule, this.node(), this.name, this.value); if (this.property.parsedOk) { propertyRenderer.setColorHandler(this._processColor.bind(this)); propertyRenderer.setBezierHandler(this._processBezier.bind(this)); } this.listItemElement.removeChildren(); this.nameElement = propertyRenderer.renderName(); this.valueElement = propertyRenderer.renderValue(); if (!this.treeOutline) return; var indent = WebInspector.moduleSetting("textEditorIndent").get(); this.listItemElement.createChild("span", "styles-clipboard-only").createTextChild(indent + (this.property.disabled ? "/* " : "")); this.listItemElement.appendChild(this.nameElement); this.listItemElement.createTextChild(": "); this.listItemElement.appendChild(this._expandElement); this.listItemElement.appendChild(this.valueElement); this.listItemElement.createTextChild(";"); if (this.property.disabled) this.listItemElement.createChild("span", "styles-clipboard-only").createTextChild(" */"); if (!this.property.parsedOk) { // Avoid having longhands under an invalid shorthand. this.listItemElement.classList.add("not-parsed-ok"); // Add a separate exclamation mark IMG element with a tooltip. this.listItemElement.insertBefore(WebInspector.StylesSidebarPane.createExclamationMark(this.property), this.listItemElement.firstChild); } if (!this.property.activeInStyle()) this.listItemElement.classList.add("inactive"); this._updateFilter(); if (this.property.parsedOk && this.section() && this.parent.root) { var enabledCheckboxElement = createElement("input"); enabledCheckboxElement.className = "enabled-button"; enabledCheckboxElement.type = "checkbox"; enabledCheckboxElement.checked = !this.property.disabled; enabledCheckboxElement.addEventListener("click", this._toggleEnabled.bind(this), false); this.listItemElement.insertBefore(enabledCheckboxElement, this.listItemElement.firstChild); } }, /** * @param {!Event} event */ _mouseClick: function(event) { if (!event.target.isComponentSelectionCollapsed()) return; event.consume(true); if (event.target === this.listItemElement) { var section = this.section(); if (!section || !section.editable) return; if (section._checkWillCancelEditing()) return; section.addNewBlankProperty(this.property.index + 1).startEditing(); return; } if (WebInspector.KeyboardShortcut.eventHasCtrlOrMeta(/** @type {!MouseEvent} */(event)) && this.section().navigable) { this._navigateToSource(/** @type {!Element} */(event.target)); return; } this.startEditing(/** @type {!Element} */(event.target)); }, /** * @param {!Element} element */ _navigateToSource: function(element) { console.assert(this.section().navigable); var propertyNameClicked = element === this.nameElement; var uiLocation = WebInspector.cssWorkspaceBinding.propertyUILocation(this.property, propertyNameClicked); if (uiLocation) WebInspector.Revealer.reveal(uiLocation); }, /** * @param {?Element=} selectElement */ startEditing: function(selectElement) { // FIXME: we don't allow editing of longhand properties under a shorthand right now. if (this.parent.isShorthand) return; if (selectElement === this._expandElement) return; var section = this.section(); if (section && !section.editable) return; if (!selectElement) selectElement = this.nameElement; // No arguments passed in - edit the name element by default. else selectElement = selectElement.enclosingNodeOrSelfWithClass("webkit-css-property") || selectElement.enclosingNodeOrSelfWithClass("value"); if (WebInspector.isBeingEdited(selectElement)) return; var isEditingName = selectElement === this.nameElement; if (!isEditingName) this.valueElement.textContent = restoreURLs(this.valueElement.textContent, this.value); /** * @param {string} fieldValue * @param {string} modelValue * @return {string} */ function restoreURLs(fieldValue, modelValue) { const urlRegex = /\b(url\([^)]*\))/g; var splitFieldValue = fieldValue.split(urlRegex); if (splitFieldValue.length === 1) return fieldValue; var modelUrlRegex = new RegExp(urlRegex); for (var i = 1; i < splitFieldValue.length; i += 2) { var match = modelUrlRegex.exec(modelValue); if (match) splitFieldValue[i] = match[0]; } return splitFieldValue.join(""); } /** @type {!WebInspector.StylePropertyTreeElement.Context} */ var context = { expanded: this.expanded, hasChildren: this.isExpandable(), isEditingName: isEditingName, previousContent: selectElement.textContent }; // Lie about our children to prevent expanding on double click and to collapse shorthands. this.setExpandable(false); if (selectElement.parentElement) selectElement.parentElement.classList.add("child-editing"); selectElement.textContent = selectElement.textContent; // remove color swatch and the like /** * @param {!WebInspector.StylePropertyTreeElement.Context} context * @param {!Event} event * @this {WebInspector.StylePropertyTreeElement} */ function pasteHandler(context, event) { var data = event.clipboardData.getData("Text"); if (!data) return; var colonIdx = data.indexOf(":"); if (colonIdx < 0) return; var name = data.substring(0, colonIdx).trim(); var value = data.substring(colonIdx + 1).trim(); event.preventDefault(); if (!("originalName" in context)) { context.originalName = this.nameElement.textContent; context.originalValue = this.valueElement.textContent; } this.property.name = name; this.property.value = value; this.nameElement.textContent = name; this.valueElement.textContent = value; this.nameElement.normalize(); this.valueElement.normalize(); this.editingCommitted(event.target.textContent, context, "forward"); } /** * @param {!WebInspector.StylePropertyTreeElement.Context} context * @param {!Event} event * @this {WebInspector.StylePropertyTreeElement} */ function blurListener(context, event) { var treeElement = this._parentPane._mouseDownTreeElement; var moveDirection = ""; if (treeElement === this) { if (isEditingName && this._parentPane._mouseDownTreeElementIsValue) moveDirection = "forward"; if (!isEditingName && this._parentPane._mouseDownTreeElementIsName) moveDirection = "backward"; } var text = event.target.textContent; if (!context.isEditingName) text = this.value || text; this.editingCommitted(text, context, moveDirection); } this._originalPropertyText = this.property.propertyText; this._parentPane.setEditingStyle(true); if (selectElement.parentElement) selectElement.parentElement.scrollIntoViewIfNeeded(false); var applyItemCallback = !isEditingName ? this._applyFreeFlowStyleTextEdit.bind(this) : undefined; this._prompt = new WebInspector.StylesSidebarPane.CSSPropertyPrompt(isEditingName ? WebInspector.CSSMetadata.cssPropertiesMetainfo : WebInspector.CSSMetadata.keywordsForProperty(this.nameElement.textContent), this, isEditingName); this._prompt.setAutocompletionTimeout(0); if (applyItemCallback) { this._prompt.addEventListener(WebInspector.TextPrompt.Events.ItemApplied, applyItemCallback, this); this._prompt.addEventListener(WebInspector.TextPrompt.Events.ItemAccepted, applyItemCallback, this); } var proxyElement = this._prompt.attachAndStartEditing(selectElement, blurListener.bind(this, context)); proxyElement.addEventListener("keydown", this._editingNameValueKeyDown.bind(this, context), false); proxyElement.addEventListener("keypress", this._editingNameValueKeyPress.bind(this, context), false); proxyElement.addEventListener("input", this._editingNameValueInput.bind(this, context), false); if (isEditingName) proxyElement.addEventListener("paste", pasteHandler.bind(this, context), false); selectElement.getComponentSelection().setBaseAndExtent(selectElement, 0, selectElement, 1); }, /** * @param {!WebInspector.StylePropertyTreeElement.Context} context * @param {!Event} event */ _editingNameValueKeyDown: function(context, event) { if (event.handled) return; var result; if (isEnterKey(event)) { event.preventDefault(); result = "forward"; } else if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Esc.code || event.keyIdentifier === "U+001B") result = "cancel"; else if (!context.isEditingName && this._newProperty && event.keyCode === WebInspector.KeyboardShortcut.Keys.Backspace.code) { // For a new property, when Backspace is pressed at the beginning of new property value, move back to the property name. var selection = event.target.getComponentSelection(); if (selection.isCollapsed && !selection.focusOffset) { event.preventDefault(); result = "backward"; } } else if (event.keyIdentifier === "U+0009") { // Tab key. result = event.shiftKey ? "backward" : "forward"; event.preventDefault(); } if (result) { switch (result) { case "cancel": this.editingCancelled(null, context); break; case "forward": case "backward": this.editingCommitted(event.target.textContent, context, result); break; } event.consume(); return; } }, /** * @param {!WebInspector.StylePropertyTreeElement.Context} context * @param {!Event} event */ _editingNameValueKeyPress: function(context, event) { /** * @param {string} text * @param {number} cursorPosition * @return {boolean} */ function shouldCommitValueSemicolon(text, cursorPosition) { // FIXME: should this account for semicolons inside comments? var openQuote = ""; for (var i = 0; i < cursorPosition; ++i) { var ch = text[i]; if (ch === "\\" && openQuote !== "") ++i; // skip next character inside string else if (!openQuote && (ch === "\"" || ch === "'")) openQuote = ch; else if (openQuote === ch) openQuote = ""; } return !openQuote; } var keyChar = String.fromCharCode(event.charCode); var isFieldInputTerminated = (context.isEditingName ? keyChar === ":" : keyChar === ";" && shouldCommitValueSemicolon(event.target.textContent, event.target.selectionLeftOffset())); if (isFieldInputTerminated) { // Enter or colon (for name)/semicolon outside of string (for value). event.consume(true); this.editingCommitted(event.target.textContent, context, "forward"); return; } }, /** * @param {!WebInspector.StylePropertyTreeElement.Context} context * @param {!Event} event */ _editingNameValueInput: function(context, event) { // Do not live-edit "content" property of pseudo elements. crbug.com/433889 if (!context.isEditingName && (!this._parentPane.node().pseudoType() || this.name !== "content")) this._applyFreeFlowStyleTextEdit(); }, _applyFreeFlowStyleTextEdit: function() { var valueText = this.valueElement.textContent; if (valueText.indexOf(";") === -1) this.applyStyleText(this.nameElement.textContent + ": " + valueText, false); }, kickFreeFlowStyleEditForTest: function() { this._applyFreeFlowStyleTextEdit(); }, /** * @param {!WebInspector.StylePropertyTreeElement.Context} context */ editingEnded: function(context) { this._resetMouseDownElement(); this.setExpandable(context.hasChildren); if (context.expanded) this.expand(); var editedElement = context.isEditingName ? this.nameElement : this.valueElement; // The proxyElement has been deleted, no need to remove listener. if (editedElement.parentElement) editedElement.parentElement.classList.remove("child-editing"); this._parentPane.setEditingStyle(false); }, /** * @param {?Element} element * @param {!WebInspector.StylePropertyTreeElement.Context} context */ editingCancelled: function(element, context) { this._removePrompt(); this._revertStyleUponEditingCanceled(); // This should happen last, as it clears the info necessary to restore the property value after [Page]Up/Down changes. this.editingEnded(context); }, _revertStyleUponEditingCanceled: function() { if (this._propertyHasBeenEditedIncrementally) { this.applyStyleText(this._originalPropertyText, false); delete this._originalPropertyText; } else if (this._newProperty) { this.treeOutline.removeChild(this); } else { this.updateTitle(); } }, /** * @param {string} moveDirection * @return {?WebInspector.StylePropertyTreeElement} */ _findSibling: function(moveDirection) { var target = this; do { target = (moveDirection === "forward" ? target.nextSibling : target.previousSibling); } while(target && target.inherited()); return target; }, /** * @param {string} userInput * @param {!WebInspector.StylePropertyTreeElement.Context} context * @param {string} moveDirection */ editingCommitted: function(userInput, context, moveDirection) { this._removePrompt(); this.editingEnded(context); var isEditingName = context.isEditingName; // Determine where to move to before making changes var createNewProperty, moveToPropertyName, moveToSelector; var isDataPasted = "originalName" in context; var isDirtyViaPaste = isDataPasted && (this.nameElement.textContent !== context.originalName || this.valueElement.textContent !== context.originalValue); var isPropertySplitPaste = isDataPasted && isEditingName && this.valueElement.textContent !== context.originalValue; var moveTo = this; var moveToOther = (isEditingName ^ (moveDirection === "forward")); var abandonNewProperty = this._newProperty && !userInput && (moveToOther || isEditingName); if (moveDirection === "forward" && (!isEditingName || isPropertySplitPaste) || moveDirection === "backward" && isEditingName) { moveTo = moveTo._findSibling(moveDirection); if (moveTo) moveToPropertyName = moveTo.name; else if (moveDirection === "forward" && (!this._newProperty || userInput)) createNewProperty = true; else if (moveDirection === "backward") moveToSelector = true; } // Make the Changes and trigger the moveToNextCallback after updating. var moveToIndex = moveTo && this.treeOutline ? this.treeOutline.rootElement().indexOfChild(moveTo) : -1; var blankInput = userInput.isWhitespace(); var shouldCommitNewProperty = this._newProperty && (isPropertySplitPaste || moveToOther || (!moveDirection && !isEditingName) || (isEditingName && blankInput)); var section = /** @type {!WebInspector.StylePropertiesSection} */(this.section()); if (((userInput !== context.previousContent || isDirtyViaPaste) && !this._newProperty) || shouldCommitNewProperty) { section._afterUpdate = moveToNextCallback.bind(this, this._newProperty, !blankInput, section); var propertyText; if (blankInput || (this._newProperty && this.valueElement.textContent.isWhitespace())) propertyText = ""; else { if (isEditingName) propertyText = userInput + ": " + this.property.value; else propertyText = this.property.name + ": " + userInput; } this.applyStyleText(propertyText, true); } else { if (isEditingName) this.property.name = userInput; else this.property.value = userInput; if (!isDataPasted && !this._newProperty) this.updateTitle(); moveToNextCallback.call(this, this._newProperty, false, section); } /** * The Callback to start editing the next/previous property/selector. * @param {boolean} alreadyNew * @param {boolean} valueChanged * @param {!WebInspector.StylePropertiesSection} section * @this {WebInspector.StylePropertyTreeElement} */ function moveToNextCallback(alreadyNew, valueChanged, section) { if (!moveDirection) return; // User just tabbed through without changes. if (moveTo && moveTo.parent) { moveTo.startEditing(!isEditingName ? moveTo.nameElement : moveTo.valueElement); return; } // User has made a change then tabbed, wiping all the original treeElements. // Recalculate the new treeElement for the same property we were going to edit next. if (moveTo && !moveTo.parent) { var rootElement = section.propertiesTreeOutline.rootElement(); if (moveDirection === "forward" && blankInput && !isEditingName) --moveToIndex; if (moveToIndex >= rootElement.childCount() && !this._newProperty) createNewProperty = true; else { var treeElement = moveToIndex >= 0 ? rootElement.childAt(moveToIndex) : null; if (treeElement) { var elementToEdit = !isEditingName || isPropertySplitPaste ? treeElement.nameElement : treeElement.valueElement; if (alreadyNew && blankInput) elementToEdit = moveDirection === "forward" ? treeElement.nameElement : treeElement.valueElement; treeElement.startEditing(elementToEdit); return; } else if (!alreadyNew) moveToSelector = true; } } // Create a new attribute in this section (or move to next editable selector if possible). if (createNewProperty) { if (alreadyNew && !valueChanged && (isEditingName ^ (moveDirection === "backward"))) return; section.addNewBlankProperty().startEditing(); return; } if (abandonNewProperty) { moveTo = this._findSibling(moveDirection); var sectionToEdit = (moveTo || moveDirection === "backward") ? section : section.nextEditableSibling(); if (sectionToEdit) { if (sectionToEdit.style().parentRule) sectionToEdit.startEditingSelector(); else sectionToEdit._moveEditorFromSelector(moveDirection); } return; } if (moveToSelector) { if (section.style().parentRule) section.startEditingSelector(); else section._moveEditorFromSelector(moveDirection); } } }, _removePrompt: function() { // BUG 53242. This cannot go into editingEnded(), as it should always happen first for any editing outcome. if (this._prompt) { this._prompt.detach(); delete this._prompt; } }, styleTextAppliedForTest: function() { }, /** * @param {string} styleText * @param {boolean} majorChange */ applyStyleText: function(styleText, majorChange) { this._applyStyleThrottler.schedule(this._innerApplyStyleText.bind(this, styleText, majorChange)); }, /** * @param {string} styleText * @param {boolean} majorChange * @return {!Promise.<undefined>} */ _innerApplyStyleText: function(styleText, majorChange) { if (!this.treeOutline) return Promise.resolve(); var oldStyleRange = this._style.range; if (!oldStyleRange) return Promise.resolve(); styleText = styleText.replace(/\s/g, " ").trim(); // Replace &nbsp; with whitespace. if (!styleText.length && majorChange && this._newProperty && !this._propertyHasBeenEditedIncrementally) { // The user deleted everything and never applied a new property value via Up/Down scrolling/live editing, so remove the tree element and update. var section = this.section(); this.parent.removeChild(this); section.afterUpdate(); return Promise.resolve(); } var currentNode = this._parentPane.node(); this._parentPane._userOperation = true; /** * @param {boolean} success * @this {WebInspector.StylePropertyTreeElement} */ function callback(success) { delete this._parentPane._userOperation; if (!success) { if (majorChange) { // It did not apply, cancel editing. this._revertStyleUponEditingCanceled(); } this.styleTextAppliedForTest(); return; } this._matchedStyles.resetActiveProperties(); this._propertyHasBeenEditedIncrementally = true; this.property = this._style.propertyAt(this.property.index); // We are happy to update UI if user is not editing. if (!this._parentPane._isEditingStyle && currentNode === this.node()) this._updatePane(); this.styleTextAppliedForTest(); } // Append a ";" if the new text does not end in ";". // FIXME: this does not handle trailing comments. if (styleText.length && !/;\s*$/.test(styleText)) styleText += ";"; var overwriteProperty = !this._newProperty || this._propertyHasBeenEditedIncrementally; return this.property.setText(styleText, majorChange, overwriteProperty) .then(callback.bind(this)); }, /** * @override * @return {boolean} */ ondblclick: function() { return true; // handled }, /** * @override * @param {!Event} event * @return {boolean} */ isEventWithinDisclosureTriangle: function(event) { return event.target === this._expandElement; }, __proto__: TreeElement.prototype } /** * @constructor * @extends {WebInspector.TextPrompt} * @param {!WebInspector.CSSMetadata} cssCompletions * @param {!WebInspector.StylePropertyTreeElement} treeElement * @param {boolean} isEditingName */ WebInspector.StylesSidebarPane.CSSPropertyPrompt = function(cssCompletions, treeElement, isEditingName) { // Use the same callback both for applyItemCallback and acceptItemCallback. WebInspector.TextPrompt.call(this, this._buildPropertyCompletions.bind(this), WebInspector.StyleValueDelimiters); this.setSuggestBoxEnabled(true); this._cssCompletions = cssCompletions; this._treeElement = treeElement; this._isEditingName = isEditingName; if (!isEditingName) this.disableDefaultSuggestionForEmptyInput(); } WebInspector.StylesSidebarPane.CSSPropertyPrompt.prototype = { /** * @override * @param {!Event} event */ onKeyDown: function(event) { switch (event.keyIdentifier) { case "Up": case "Down": case "PageUp": case "PageDown": if (this._handleNameOrValueUpDown(event)) { event.preventDefault(); return; } break; case "Enter": // Accept any available autocompletions and advance to the next field. if (this.autoCompleteElement && this.autoCompleteElement.textContent.length) { this.tabKeyPressed(); return; } break; } WebInspector.TextPrompt.prototype.onKeyDown.call(this, event); }, /** * @override * @param {!Event} event */ onMouseWheel: function(event) { if (this._handleNameOrValueUpDown(event)) { event.consume(true); return; } WebInspector.TextPrompt.prototype.onMouseWheel.call(this, event); }, /** * @override * @return {boolean} */ tabKeyPressed: function() { this.acceptAutoComplete(); // Always tab to the next field. return false; }, /** * @param {!Event} event * @return {boolean} */ _handleNameOrValueUpDown: function(event) { /** * @param {string} originalValue * @param {string} replacementString * @this {WebInspector.StylesSidebarPane.CSSPropertyPrompt} */ function finishHandler(originalValue, replacementString) { // Synthesize property text disregarding any comments, custom whitespace etc. this._treeElement.applyStyleText(this._treeElement.nameElement.textContent + ": " + this._treeElement.valueElement.textContent, false); } /** * @param {string} prefix * @param {number} number * @param {string} suffix * @return {string} * @this {WebInspector.StylesSidebarPane.CSSPropertyPrompt} */ function customNumberHandler(prefix, number, suffix) { if (number !== 0 && !suffix.length && WebInspector.CSSMetadata.isLengthProperty(this._treeElement.property.name)) suffix = "px"; return prefix + number + suffix; } // Handle numeric value increment/decrement only at this point. if (!this._isEditingName && WebInspector.handleElementValueModifications(event, this._treeElement.valueElement, finishHandler.bind(this), this._isValueSuggestion.bind(this), customNumberHandler.bind(this))) return true; return false; }, /** * @param {string} word * @return {boolean} */ _isValueSuggestion: function(word) { if (!word) return false; word = word.toLowerCase(); return this._cssCompletions.keySet().hasOwnProperty(word); }, /** * @param {!Element} proxyElement * @param {string} text * @param {number} cursorOffset * @param {!Range} wordRange * @param {boolean} force * @param {function(!Array.<string>, number=)} completionsReadyCallback */ _buildPropertyCompletions: function(proxyElement, text, cursorOffset, wordRange, force, completionsReadyCallback) { var prefix = wordRange.toString().toLowerCase(); if (!prefix && !force && (this._isEditingName || proxyElement.textContent.length)) { completionsReadyCallback([]); return; } var results = this._cssCompletions.startsWith(prefix); if (!this._isEditingName && !results.length && prefix.length > 1 && "!important".startsWith(prefix)) results.push("!important"); var userEnteredText = wordRange.toString().replace("-", ""); if (userEnteredText && (userEnteredText === userEnteredText.toUpperCase())) { for (var i = 0; i < results.length; ++i) results[i] = results[i].toUpperCase(); } var selectedIndex = this._cssCompletions.mostUsedOf(results); completionsReadyCallback(results, selectedIndex); }, __proto__: WebInspector.TextPrompt.prototype } /** * @constructor * @param {?WebInspector.CSSRule} rule * @param {?WebInspector.DOMNode} node * @param {string} name * @param {string} value */ WebInspector.StylesSidebarPropertyRenderer = function(rule, node, name, value) { this._rule = rule; this._node = node; this._propertyName = name; this._propertyValue = value; } WebInspector.StylesSidebarPropertyRenderer._variableRegex = /(var\(--.*?\))/g; WebInspector.StylesSidebarPropertyRenderer._colorRegex = /((?:rgb|hsl)a?\([^)]+\)|#[0-9a-fA-F]{6}|#[0-9a-fA-F]{3}|\b\w+\b(?!-))/g; WebInspector.StylesSidebarPropertyRenderer._bezierRegex = /((cubic-bezier\([^)]+\))|\b(linear|ease-in-out|ease-in|ease-out|ease)\b)/g; /** * @param {string} value * @return {!RegExp} */ WebInspector.StylesSidebarPropertyRenderer._urlRegex = function(value) { // Heuristically choose between single-quoted, double-quoted or plain URL regex. if (/url\(\s*'.*\s*'\s*\)/.test(value)) return /url\(\s*('.+?')\s*\)/g; if (/url\(\s*".*\s*"\s*\)/.test(value)) return /url\(\s*(".+?")\s*\)/g; return /url\(\s*([^)]+)\s*\)/g; } WebInspector.StylesSidebarPropertyRenderer.prototype = { /** * @param {function(string):!Node} handler */ setColorHandler: function(handler) { this._colorHandler = handler; }, /** * @param {function(string):!Node} handler */ setBezierHandler: function(handler) { this._bezierHandler = handler; }, /** * @return {!Element} */ renderName: function() { var nameElement = createElement("span"); nameElement.className = "webkit-css-property"; nameElement.textContent = this._propertyName; nameElement.normalize(); return nameElement; }, /** * @return {!Element} */ renderValue: function() { var valueElement = createElement("span"); valueElement.className = "value"; if (!this._propertyValue) return valueElement; var formatter = new WebInspector.StringFormatter(); formatter.addProcessor(WebInspector.StylesSidebarPropertyRenderer._variableRegex, createTextNode); formatter.addProcessor(WebInspector.StylesSidebarPropertyRenderer._urlRegex(this._propertyValue), this._processURL.bind(this)); if (this._bezierHandler && WebInspector.CSSMetadata.isBezierAwareProperty(this._propertyName)) formatter.addProcessor(WebInspector.StylesSidebarPropertyRenderer._bezierRegex, this._bezierHandler); if (this._colorHandler && WebInspector.CSSMetadata.isColorAwareProperty(this._propertyName)) formatter.addProcessor(WebInspector.StylesSidebarPropertyRenderer._colorRegex, this._colorHandler); valueElement.appendChild(formatter.formatText(this._propertyValue)); valueElement.normalize(); return valueElement; }, /** * @param {string} url * @return {!Node} */ _processURL: function(url) { var hrefUrl = url; var match = hrefUrl.match(/['"]?([^'"]+)/); if (match) hrefUrl = match[1]; var container = createDocumentFragment(); container.createTextChild("url("); if (this._rule && this._rule.resourceURL()) hrefUrl = WebInspector.ParsedURL.completeURL(this._rule.resourceURL(), hrefUrl); else if (this._node) hrefUrl = this._node.resolveURL(hrefUrl); var hasResource = hrefUrl && !!WebInspector.resourceForURL(hrefUrl); // FIXME: WebInspector.linkifyURLAsNode() should really use baseURI. container.appendChild(WebInspector.linkifyURLAsNode(hrefUrl || url, url, undefined, !hasResource)); container.createTextChild(")"); return container; } } /** * @return {!WebInspector.ToolbarItem} */ WebInspector.StylesSidebarPane.createAddNewRuleButton = function(stylesSidebarPane) { var button = new WebInspector.ToolbarButton(WebInspector.UIString("New Style Rule"), "add-toolbar-item"); button.addEventListener("click", stylesSidebarPane._createNewRuleInViaInspectorStyleSheet, stylesSidebarPane); button.element.createChild("div", "long-click-glyph toolbar-button-theme"); new WebInspector.LongClickController(button.element, stylesSidebarPane._onAddButtonLongClick.bind(stylesSidebarPane)); WebInspector.context.addFlavorChangeListener(WebInspector.DOMNode, onNodeChanged); onNodeChanged(); return button; function onNodeChanged() { var node = WebInspector.context.flavor(WebInspector.DOMNode); button.setEnabled(!!node); } }
{ "content_hash": "2dacb4f19caa62d314e7d3e56a232733", "timestamp": "", "source": "github", "line_count": 3072, "max_line_length": 238, "avg_line_length": 34.3740234375, "alnum_prop": 0.6177542922620908, "repo_name": "weexteam/weex-devtool", "id": "fa507a75a58bb9e8345e7def17227458da46c5c2", "size": "107204", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "frontend/devtools/elements/StylesSidebarPane.js", "mode": "33188", "license": "mit", "language": [ { "name": "AppleScript", "bytes": "1224" }, { "name": "CSS", "bytes": "344284" }, { "name": "HTML", "bytes": "18727" }, { "name": "JavaScript", "bytes": "7200252" }, { "name": "Python", "bytes": "3369" } ] }
package com.intellij.codeInsight.daemon.impl; import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer; import com.intellij.codeInsight.daemon.DaemonCodeAnalyzerSettings; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.ex.EditorMarkupModel; import com.intellij.openapi.editor.ex.ErrorStripTooltipRendererProvider; import com.intellij.openapi.editor.impl.EditorMarkupModelImpl; import com.intellij.openapi.editor.markup.ErrorStripeRenderer; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.ui.PopupHandler; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class ErrorStripeUpdateManager { public static ErrorStripeUpdateManager getInstance(Project project) { return ServiceManager.getService(project, ErrorStripeUpdateManager.class); } private final Project myProject; private final PsiDocumentManager myPsiDocumentManager; public ErrorStripeUpdateManager(Project project, PsiDocumentManager psiDocumentManager) { myProject = project; myPsiDocumentManager = psiDocumentManager; } @SuppressWarnings("WeakerAccess") // Used in Rider public void repaintErrorStripePanel(@NotNull Editor editor) { ApplicationManager.getApplication().assertIsDispatchThread(); if (!myProject.isInitialized()) return; PsiFile file = myPsiDocumentManager.getPsiFile(editor.getDocument()); final EditorMarkupModel markup = (EditorMarkupModel) editor.getMarkupModel(); markup.setErrorPanelPopupHandler(createPopup(file)); markup.setErrorStripTooltipRendererProvider(createTooltipRenderer()); markup.setMinMarkHeight(DaemonCodeAnalyzerSettings.getInstance().ERROR_STRIPE_MARK_MIN_HEIGHT); setOrRefreshErrorStripeRenderer(markup, file); } @SuppressWarnings("WeakerAccess") // Used in Rider protected void setOrRefreshErrorStripeRenderer(@NotNull EditorMarkupModel editorMarkupModel, @Nullable PsiFile file) { ApplicationManager.getApplication().assertIsDispatchThread(); if (!editorMarkupModel.isErrorStripeVisible() || !DaemonCodeAnalyzer.getInstance(myProject).isHighlightingAvailable(file)) { return; } ErrorStripeRenderer renderer = editorMarkupModel.getErrorStripeRenderer(); if (renderer instanceof TrafficLightRenderer) { TrafficLightRenderer tlr = (TrafficLightRenderer) renderer; EditorMarkupModelImpl markupModelImpl = (EditorMarkupModelImpl) editorMarkupModel; tlr.refresh(markupModelImpl); markupModelImpl.repaintVerticalScrollBar(); if (tlr.isValid()) return; } Editor editor = editorMarkupModel.getEditor(); if (editor.isDisposed()) return; editorMarkupModel.setErrorStripeRenderer(createRenderer(editor, file)); } @NotNull private static PopupHandler createPopup(@Nullable PsiFile psiFile) { return new DaemonEditorPopup(psiFile); } @NotNull private ErrorStripTooltipRendererProvider createTooltipRenderer() { return new DaemonTooltipRendererProvider(myProject); } @Nullable protected TrafficLightRenderer createRenderer(@NotNull Editor editor, @Nullable PsiFile file) { for (TrafficLightRendererContributor contributor : TrafficLightRendererContributor.EP_NAME.getExtensionList()) { TrafficLightRenderer renderer = contributor.createRenderer(editor, file); if (renderer != null) { return renderer; } } return new TrafficLightRenderer(myProject, editor.getDocument(), file); } }
{ "content_hash": "60f49a7a1eae4886b8ca95528426bff9", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 128, "avg_line_length": 43.082352941176474, "alnum_prop": 0.7971054068814856, "repo_name": "goodwinnk/intellij-community", "id": "fb83e6257aefb7d766d716e2738e8c70770c90d3", "size": "3803", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ErrorStripeUpdateManager.java", "mode": "33188", "license": "apache-2.0", "language": [] }
End of preview.

No dataset card yet

Downloads last month
3